One SQLAlchemy factory setting stops random IntegrityError failures in test suites
Developers using polyfactory with SQLAlchemy may encounter intermittent IntegrityError UNIQUE constraint failures when seeding test data, a bug that rarely appears below 50 rows but affects over 75% of runs at 100 rows. The root cause is that SQLAlchemyFactory generates integer primary keys using Faker's pyint(), which draws from only 10,000 possible values, making collisions statistically likely as row counts grow — a classic birthday problem. Testing with polyfactory 3.3.0 and SQLAlchemy 2.1.1 confirmed the failure rates match mathematical predictions across multiple table types. The fix is setting __set_primary_key__ = False in the factory class, which delegates primary key assignment to the database instead of the factory. The only trade-off is that object IDs remain None until the session is flushed, so tests that read IDs before a write must call flush explicitly.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in