Code

Opened 5 years ago

Closed 5 years ago

#11064 closed (wontfix)

TestCase Docs: Problematic import in Codesnippet

Reported by: kanu@… Owned by: nobody
Component: Documentation Version: 1.0
Severity: Keywords: Test Signal IntegrityError
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

There is a problem when importing models into your test.py as mentioned in http://docs.djangoproject.com/en/dev/topics/testing/#writing-unit-tests.

from myapp.models import Animal

If you register your signals in the models.py as suggested in the docs. They will be registered twice when testing and therefore will be called twice during test runs.
At least this isn't the demanded behavior at worst it throws a an error where no error is.
eg:

class Member(models.Model):
  user = models.ForeignKey(User, unique=True)
  ...

def create_user_profile(sender,instance,created,**kws):
  if create:
    m = Member(user = instance )
    m.save()

signals.post_save.connect(create_user_profile,sender=User)

The second time create_user_profile() is called it throws a IntegrityError: duplicate key value violates.

To fix this you can change the import in test.py to

from myproject.myapp.models import Animal

or

from models import Animal 

the handler are registered only once and everything works fine when running tests.

Attachments (0)

Change History (1)

comment:1 Changed 5 years ago by russellm

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to wontfix
  • Status changed from new to closed

As a result of the way Python handles imports, from myproject.myapp.models import Animal and from myapp.models import Animal import different instances of the models module, which causes the double instantiation of the signal. However, each import mode, in and of itself, is entirely valid. It simply isn't true to say that 'myproject.myapp.models' is the 'right' format - anyone that has consistently used 'myapp.models' to import will get bitten by exactly the same problem for exactly the same reason if they use myproject.myapp.models in their test case.

Therefore, this isn't an 'error' in the test docs - it's an aspect of model import that you need to be aware of if you are using signals. Marking wontfix for that reason.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.