Ensure test seed data never causes unique constraint violations — UUID-based, timestamp-based, counter-based, or Faker patterns for any field with a UNIQUE index, primary key, or slug constraint.
Instrucciones de origen · Vista previa de solo lectura
name
test-seed-uniqueness
version
1.0.0
category
software-development
description
Ensure test seed data never causes unique constraint violations — UUID-based, timestamp-based, counter-based, or Faker patterns for any field with a UNIQUE index, primary key, or slug constraint.
Every test needs seed data. Agents instinctively write:
user = User.objects.create(email="alice@example.com", username="alice")
This works once. On the next test run, or when tests run in parallel, or when a second test also creates an alice:
django.db.utils.IntegrityError: duplicate key value violates unique constraint
The agent didn't do anything wrong — it just picked a natural-looking value for a field that happens to have a UNIQUE constraint. The database doesn't care how pretty the data is; it cares about uniqueness.
The Rule
Every value inserted into a uniquely-constrained field MUST be dynamically unique at runtime.
id / pk (unless using auto-increment — then let the DB handle it)
email
username
slug
external_id / stripe_id / github_id — any third-party ID
api_key / token / secret
invite_code / referral_code
phone_number
handle / display_handle / profile_url
Any field with unique=True, unique_together, or UniqueConstraint
Integration with change-test-loop
When the RED phase fails not because the test logic is wrong but because of a unique constraint violation:
Don't change the test logic — the test is correct
Fix the seed data to use a dynamic uniqueness pattern
Re-score RED: the test should now fail for the intended reason (feature missing)
When GREEN phase passes but seed data has hardcoded unique fields: this is a REFACTOR concern — dynamize the seed data while keeping tests green.
Verification
Before declaring seed data done:
✅ Every uniquely-constrained field uses a dynamic pattern (UUID, timestamp, counter, or Faker)
✅ No hardcoded alice@example.com, testuser, demo-slug, or similar in seed data
✅ Tests pass on re-run without cleanup
✅ Tests pass in parallel (xdist or similar)
✅ factory_boy fixtures use Sequence() for all unique fields
✅ Non-unique fields are still readable/human-friendly (don't over-randomize)