Your SQLAlchemy test factory fails at random past 50 rows. Here's the one-line fix.
You write a test that seeds a hundred rows with a factory. It fails with IntegrityError: UNIQUE constraint failed: users.id . You run it again and it passes. You run it a third time and it fails. Nothing is wrong with your models. The factory is drawing primary keys out of a hat. I measured it with polyfactory 3.3.0 and SQLAlchemy 2.1.1, and the fix is one line. I maintain seedgraph , a library…
A test factory designed to create 100 rows of data using SQLAlchemy failed sporadically when the number of rows exceeded 50. The issue stemmed from the factory's default behavior of filling primary key columns with values generated by Faker's pyint(), which had a limited range of 0 to 9999. This limited range made it likely for duplicate values to appear, causing a UNIQUE constraint violation due to the UNIQUE constraint on the id field in the User model.
To resolve this issue, the code was modified by setting the __set_primary_key__ attribute of the PostFactory to False. By doing so, the factory left the primary keys empty, allowing the database to assign them. This change eliminated the intermittent failures and improved the reliability of the test.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.