/ test / conftest.py
conftest.py
 1  import pytest
 2  
 3  from config import settings
 4  from allthethings.app import create_app
 5  
 6  
 7  @pytest.fixture(scope="session")
 8  def app():
 9      """
10      Setup our flask test app, this only gets executed once.
11  
12      :return: Flask app
13      """
14      db_uri = f"{settings.SQLALCHEMY_DATABASE_URI}_test"
15      params = {
16          "DEBUG": False,
17          "TESTING": True,
18          "WTF_CSRF_ENABLED": False,
19          "SQLALCHEMY_DATABASE_URI": db_uri,
20      }
21  
22      _app = create_app(settings_override=params)
23  
24      # Establish an application context before running the tests.
25      ctx = _app.app_context()
26      ctx.push()
27  
28      yield _app
29  
30      ctx.pop()
31  
32  
33  @pytest.fixture(scope="function")
34  def client(app):
35      """
36      Setup an app client, this gets executed for each test function.
37  
38      :param app: Pytest fixture
39      :return: Flask app client
40      """
41      yield app.test_client()
42  
43  
44  @pytest.fixture(scope="session")
45  def db(app):
46      """
47      Setup our database, this only gets executed once per session.
48  
49      :param app: Pytest fixture
50      :return: SQLAlchemy database session
51      """
52      _db.drop_all()
53      _db.create_all()
54  
55      return _db
56  
57  
58  @pytest.fixture(scope="function")
59  def session(db):
60      """
61      Allow very fast tests by using rollbacks and nested sessions. This does
62      require that your database supports SQL savepoints, and Postgres does.
63  
64      Read more about this at:
65      http://stackoverflow.com/a/26624146
66  
67      :param db: Pytest fixture
68      :return: None
69      """
70      db.session.begin_nested()
71  
72      yield db.session
73  
74      db.session.rollback()