Integration Testing Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Integration Testing runs in O(n) time and O(n) space, in Python as in every other language.
- ✓The standard library gives you unittest (TestCase, setUpClass, setUpModule) and unittest.mock, but integration work settled on pytest, whose fixtures carry scope="session" and yield-based teardown that unittest has no equivalent for.
- ✓Reviewers want the container session-scoped and the data function-scoped, shared fixtures in conftest.py rather than imported from a helper module, and an explicit pytest.mark.integration so -m "not integration" stays fast.
- ✓The Python trap: Event-loop scoping. An asyncpg pool built in a session-scoped fixture is bound to whichever loop was current then; pytest-asyncio's default function-scoped loop closes after the first test, and every later test raises "attached to a different loop" or "Event loop is closed".
- ✓Container startup dominates, one to five seconds even with the image cached, so amortise it with a session-scoped fixture.
What Integration Testing actually is
Integration Testing in Python: what you actually reach for
Python implementation
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from testcontainers.postgres import PostgresContainer
@pytest.fixture(scope="session")
def engine():
with PostgresContainer("postgres:16-alpine") as pg:
eng = create_engine(pg.get_connection_url())
with eng.begin() as conn:
conn.execute(text(
"CREATE TABLE orders (id serial PRIMARY KEY, sku text NOT NULL)"))
yield eng
eng.dispose()
@pytest.fixture()
def db(engine):
conn = engine.connect()
outer = conn.begin()
session = Session(bind=conn, join_transaction_mode="create_savepoint")
try:
yield session
finally:
session.close()
outer.rollback() # every write this test made disappears
conn.close()
@pytest.mark.integration
def test_insert_is_visible_then_rolled_back(db):
db.execute(text("INSERT INTO orders (sku) VALUES ('ABC-1')"))
db.flush()
n = db.execute(text("SELECT count(*) FROM orders")).scalar_one()
assert n == 1
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Integration Testing?
The standard library gives you unittest (TestCase, setUpClass, setUpModule) and unittest.mock, but integration work settled on pytest, whose fixtures carry scope="session" and yield-based teardown that unittest has no equivalent for. Ephemeral dependencies come from testcontainers (testcontainers.postgres.PostgresContainer, .get_connection_url()); pytest-xdist forks workers; pytest-asyncio drives coroutine tests. The per-test rollback primitive is SQLAlchemy 2.0's Session(bind=connection, join_transaction_mode="create_savepoint"); Django ships django.test.TransactionTestCase and pytest-django exposes the django_db marker.
What is the most common Python mistake when implementing Integration Testing?
Event-loop scoping. An asyncpg pool built in a session-scoped fixture is bound to whichever loop was current then; pytest-asyncio's default function-scoped loop closes after the first test, and every later test raises "attached to a different loop" or "Event loop is closed". Second, modules are singletons in sys.modules, so a module-level engine = create_engine(os.environ["DSN"]) captured the environment at import time and monkeypatch.setenv arrives too late. Third, a failing assert keeps the traceback, the traceback keeps the frame, the frame keeps the local connection alive, so refcounting frees connections in passing runs and leaks them in failing ones.
How does Integration Testing actually perform in Python?
Container startup dominates, one to five seconds even with the image cached, so amortise it with a session-scoped fixture. Per-test ROLLBACK costs about a millisecond, TRUNCATE a few tens, DROP and CREATE DATABASE hundreds. The GIL buys nothing for these tests since they are IO-bound, but pytest-xdist gives real parallelism at the price of one schema or database per worker; key it off the PYTEST_XDIST_WORKER environment variable. Fixture teardown is LIFO, and collection imports every test module, so import-time database work is paid even under -k. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.