python / expert
Snippet
Transactional Boundary Mocking in Integration Test Suites
Wrapping Django transaction.on_commit hooks with test decorators forces execution of post-commit side-effect callbacks synchronously while applying context mocks inside integration tests.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import functoolsfrom unittest.mock import patchfrom django.db import transactiondef mock_external_call_on_commit(mock_target: str):def decorator(func):@functools.wraps(func)def wrapper(*args, **kwargs):def patched_on_commit(callback, using=None):with patch(mock_target) as mock_obj:callback()with patch.object(transaction, 'on_commit', side_effect=patched_on_commit):return func(*args, **kwargs)return wrapperreturn decorator
django
Breakdown
1
def mock_external_call_on_commit(mock_target: str):
Parametrized test decorator taking string path to target function being mocked.
2
def patched_on_commit(callback, using=None):
Interceptors replacing transaction.on_commit behavior to execute callbacks immediately.
3
with patch(mock_target) as mock_obj:
Applies unittest mock within execution context of the commit callback.
4
with patch.object(transaction, 'on_commit', side_effect=patched_on_commit):
Patches transaction module level on_commit handler during test execution.