Last active
November 19, 2024 23:52
-
Star
(108)
You must be signed in to star a gist -
Fork
(18)
You must be signed in to fork a gist
-
-
Save kissgyorgy/e2365f25a213de44b9a2 to your computer and use it in GitHub Desktop.
Python: py.test fixture for SQLAlchemy test in a transaction, create tables only once!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import create_engine | |
from sqlalchemy.orm import Session | |
from myapp.models import BaseModel | |
import pytest | |
@pytest.fixture(scope="session") | |
def engine(): | |
return create_engine("postgresql://localhost/test_database") | |
@pytest.fixture(scope="session") | |
def tables(engine): | |
BaseModel.metadata.create_all(engine) | |
yield | |
BaseModel.metadata.drop_all(engine) | |
@pytest.fixture | |
def dbsession(engine, tables): | |
"""Returns an sqlalchemy session, and after the test tears down everything properly.""" | |
connection = engine.connect() | |
# begin the nested transaction | |
transaction = connection.begin() | |
# use the connection with the already started transaction | |
session = Session(bind=connection) | |
yield session | |
session.close() | |
# roll back the broader transaction | |
transaction.rollback() | |
# put back the connection to the connection pool | |
connection.close() |
With pytest-xdist, you should make a different test database for every process.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the answer, I tried that too but that would not help.
Altho I found the problematic part but I don't know how to solve it yet. The issue is that I have a lot of Core CPUs and I had pytest
--numprocesses/-n
onauto
. My assumption is that 2 (or more) of the tests from the same class - which are using these db fixtures - were running on different processes which would create new test session. Setting it to 1 (or not adding it) solved the problem.