Opened 11 years ago

Closed 11 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: no UI/UX: no


There is a problem when importing models into your as mentioned in

from myapp.models import Animal

If you register your signals in the 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.

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

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


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 to

from myproject.myapp.models import Animal


from models import Animal 

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

Change History (1)

comment:1 Changed 11 years ago by Russell Keith-Magee

Resolution: wontfix
Status: newclosed

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.

Note: See TracTickets for help on using tickets.
Back to Top