python – Start and Drop Bank in flask test


I'm doing an api test, which I pass a json it validates if everything is ok:

my base class:

# -*- coding: utf-8 -*-

import os
import unittest
from app import initialize
from mock import mock
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from app import database
os.environ = {

test_app = Flask(__name__)
database.AppRepository.db = SQLAlchemy(test_app)

class TestCase(unittest.TestCase):
    mock = mock
    user = initialize.web_app.test_client()

I believe that in this base file, it should have the teardown, Setup etc functions..

 json_gardener = {"id": "1",
                    "name": "Jamme"}

And I have the following function that makes the post in this case:

def test_post_gardener(self):
             response ='/gardeners', headers={'VALIDATION': 'XXXX'}, data=self.json_gardener)
            self.assertEqual(response.status_code, 201)

So far, everything is ok, it works perfectly, but when I run it the second time, obviously it will show that the id already exists in the bank and it will give an error.

My question is, is there a way to upload a database to test and when it finishes running it dismount?


According to Flask's own documentation there is a tempfile class that can be used for this as a database instance in the test class.

import os
import flaskr
import unittest
import tempfile

class FlaskrTestCase(unittest.TestCase):

    def setUp(self):
        self.db_fd,['DATABASE'] = tempfile.mkstemp()['TESTING'] = True =

    def tearDown(self):

    def test_empty_db(self):
        rv ='/')
        assert b'No entries here so far' in

    def login(self, username, password):
    return'/login', data=dict(
    ), follow_redirects=True)

    def logout(self):
        return'/logout', follow_redirects=True)

    def test_login_logout(self):
        rv = self.login('admin', 'default')
        assert b'You were logged in' in
        rv = self.logout()
        assert b'You were logged out' in
        rv = self.login('adminx', 'default')
        assert b'Invalid username' in
        rv = self.login('admin', 'defaultx')
        assert b'Invalid password' in

if __name__ == '__main__':


Scroll to Top