Pytest: setup testclient and DB
You must be using flask-sqlalchemy, behind the scenes, it uses the declarative extension to define your models.
By subclassing a sqlalchemy declarative base class, sqlalchemy will generate Table
and mapper
for you, newly created table info stores in the corresponding Metadata
obj. db.create_all()
actually is metadata.create_all()
, which will only create tables stored in the metadata.
Therefore, before you try to create a table with metadata.create_all
, you have to store the info of that table into the metadata
registry first, which equals to define a declarative base subclass. In python, this means to get your class definition code executed, which in turns, import
the module
the classes defined.
I found the solution.
@dmitrybelyakov was quite close to it:
importing the model was the hint.
What does not work:
from application.model import Order
What does work:
from application.model import *
I don't know exactly, why it does not work to import a single model, but finally it's running. Here my complete fixture:
import pytestfrom config import TestingConfigfrom application import create_app, dbfrom application.models import *# ############################ ## functional tests# ###########################@pytest.fixture(scope='module')def test_client(): app = create_app(TestingConfig) # Flask provides a way to test your application by exposing the Werkzeug # test Client and handling the context locals for you. testing_client = app.test_client() with app.app_context(): db.create_all() yield testing_client # this is where the testing happens! db.drop_all()