pytest-dev / pytest-dev/pytest-django

Testing code with deferred unique constraints gives false positives

Open
#786 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
1.5k
Forks
367
PR merge metrics
No merged PRs in 30d

Description

Hey,

I have a formset of let's say Animal objects Animal1(age=1, name='test') and Animal2(age=4, name='rex') which have a unique constrain on name field. I want a formset to validate when a user switches the names in the UI. This will normally raise at least a django.db.utils.IntegrityError.

I managed to achieve that using the postges' deferred unique constraint. What I also needed to do is run formset.save() inside the transaction.atomic() block for the deferred constraint to be triggered. When I click through my local build everything works as expected.

Problem comes when I want to test it: the test passes on every setup (with or without the mentioned atomic block) resulting in a false positive.

I guess it has to do with how transactions are handled. I see there is transactional_db fixture, I've tried to use it but without any luck.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the formset scenario with PostgreSQL deferred unique constraints, comparing saves inside and outside transaction.atomic() and using the transactional_db fixture. The issue is resolved when the test fails for the missing atomic block and passes only when deferred constraint violations are correctly triggered.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
database, testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.