Opened 16 years ago
Closed 15 years ago
#11064 closed (wontfix)
TestCase Docs: Problematic import in Codesnippet
Reported by: | 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 |
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.
As a result of the way Python handles imports,
from myproject.myapp.models import Animal
andfrom 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.