# Unique constraint failed in a test

Classification: test-data
Frameworks: pytest, Jest, CI
Canonical: https://automationtester.in/failures/test-data-unique-constraint

## Recognizable error

```text
Unique constraint failed on the fields
```

## What it means

The test attempted to create a record whose unique value already exists in the database visible to that test.

## Ranked causes, checks, and fixes

### 1. Parallel tests share fixed fixture values

Two workers create the same email, slug, key, or external id.

Diagnostic: Compare worker IDs and the colliding field across concurrent tests.

Fix: Generate a deterministic worker-scoped value and keep assertions independent of the literal.

### 2. Cleanup did not run after an earlier failure

A previous test left data that the next run assumes is absent.

Diagnostic: Query the record before setup and inspect teardown failures.

Fix: Use transaction rollback, isolated schemas, or idempotent setup and teardown.

### 3. A retry repeats a non-idempotent setup

The retried test creates the same record without resetting state.

Diagnostic: Check whether setup is inside the retried boundary.

Fix: Make setup idempotent or create fresh retry-scoped data.

## Prevention

- Give each worker isolated data.
- Use transactional cleanup.
- Make retry setup idempotent.

## Primary references

- [PostgreSQL unique constraints](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS)

Triage this failure locally: https://automationtester.in/tools/test-failure-triage