I'm porting the tests of a Flask application from unittest to pytest. For tests that need a database I added a fixture that returns a DB session
The DB is an SQLAlchemy object that runs a PostgreSQL database
import pytest
from app import create_app, db
from app.models import Project, Client
@pytest.fixture(scope='function')
def db_session():
app = create_app('testing')
app_context = app.app_context()
app_context.push()
db.create_all()
yield db.session
db.session.remove()
db.drop_all()
app_context.pop()
def test_getJson_withOneProjectSet_returnsBasicClientJson(db_session):
testClient = Client()
db_session.add(testClient)
testProject = Project()
db_session.add(testProject)
testClient.projects.append(testProject)
db_session.commit()
clientJson = testClient.getJson()
assert len(clientJson['projects']) == 1
def test_getJson_withThreeProjectsSet_returnsBasicClientJson(db_session):
testClient = Client()
db_session.add(testClient)
testProject1 = Project()
db_session.add(testProject1)
testProject2 = Project()
db_session.add(testProject2)
testProject3 = Project()
db_session.add(testProject3)
testClient.projects.append(testProject1)
testClient.projects.append(testProject2)
testClient.projects.append(testProject3)
db_session.commit()
clientJson = testClient.getJson()
assert len(clientJson['projects']) == 3
When running the tests, the first one passes but the second one returns an integrity error: sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) duplicate key value violates unique constraint "project_code_key"
Apparently the DB is not cleaned up after finishing a test-function
The fixture is a port from a working unittest setup/teardown function that has no problems with integrity errors:
# def setUp(self):
# self.app = create_app('testing')
# self.app_context = self.app.app_context()
# self.app_context.push()
# db.create_all()
#
# def tearDown(self):
# db.session.remove()
# db.drop_all()
# self.app_context.pop()