Skip to content

Commit 5560d2a

Browse files
gmoonclaude
andcommitted
docs: Add concurrency test guidelines to CONTRIBUTING.md
Documents pitfalls when writing tests with threads: - SQLAlchemy sessions are not thread-safe - Threads can't see test fixture data (transaction isolation) - Solution: Pass session factory configured for test database Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent fb53a17 commit 5560d2a

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

CONTRIBUTING.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,40 @@ def test_create_user_with_duplicate_email_returns_409():
142142
def test_get_user_when_not_authenticated_returns_401():
143143
```
144144

145+
### Concurrency Tests
146+
147+
When writing tests that spawn threads (e.g., stress tests, race condition tests):
148+
149+
1. **Threads cannot share database sessions** - SQLAlchemy sessions are not thread-safe
150+
2. **Threads cannot see test fixture data** - Test fixtures use transactions that are isolated from other sessions
151+
3. **Don't import `SessionLocal` directly in threads** - It may connect to the wrong database
152+
153+
**Solution**: Pass a session factory configured for the test database to threads:
154+
155+
```python
156+
from sqlalchemy import create_engine
157+
from sqlalchemy.orm import sessionmaker
158+
159+
TEST_DATABASE_URL = "postgresql://admin:secret@localhost:5432/test_db"
160+
161+
@pytest.fixture
162+
def test_session_factory():
163+
"""Session factory for threads to use."""
164+
engine = create_engine(TEST_DATABASE_URL)
165+
return sessionmaker(bind=engine)
166+
167+
def test_concurrent_operations(test_session_factory):
168+
def worker():
169+
session = test_session_factory()
170+
try:
171+
# Use session...
172+
finally:
173+
session.close()
174+
175+
with ThreadPoolExecutor(max_workers=5) as executor:
176+
futures = [executor.submit(worker) for _ in range(10)]
177+
```
178+
145179
---
146180

147181
## Git Workflow

0 commit comments

Comments
 (0)