I see some really amazing and unpleasant behavior when testing Django. Model objects are "discovered" using the appropriate search, but no model objects exist. (We apologize for the strange description here ... the behavior is rather strange that I don’t know how to describe it. Are there objects? Do I exist? You?)
I need them to exist, so I have a method that creates them if they do not exist. The problem is that on one line, Django discovers that they exist, and therefore they are not created ... and then on the next line we can confirm that such objects do not exist.
My tests give errors in test_something () due to the lack of the required TaskMetadata object.
class TaskMetadata(models.Model):
task = models.OneToOneField(ContentType)
...
class SimpleTest(TestCase):
def setUp(self):
some_utility_function()
def test_something(self):
...something that requires TaskMetadata...
def some_utility_function():
task = ...whatever...
ctype = ContentType.objects.get_for_model(task)
try:
ctype.taskmetadata
except TaskMetadata.DoesNotExist:
...create TaskMetadata...
print "Created TaskMetadata object for %s" % task.__name__
else:
print "TaskMetadata object already exists for %s" % task.__name__
print ctype.taskmetadata
print "ALL OF THEM!! %s" % TaskMetadata.objects.all()
and the printed result of some_utility_function ():
TaskMetadata object already exists for SomeTask
some task
ALL OF THEM!! [] # <-- NOTE EMPTY QUERYSET
In conclusion: "Yes, the TaskMetadata object exists. Yes, the TaskMetadata object exists. No, there are no TaskMetadata objects at all!"
So seriously, what's going on here? Is this a cache problem? I tried to clear the cache (I think I don't have CACHES configured in settings.py)
def setUp(self):
cache.clear()
some_utility_function()
Does not help. Perhaps a transaction? I'm at a dead end. How do I debug this?
UPDATE:
See the Minimal django project, which replicates the problem here .
When the first test test is run, TaskMetadata.objects.all () is NOT an empty set of queries (in fact, it is filled with objects, as you would expect); when the second test test is executed (exactly the same as the first), it is empty.
, , TaskMetadata, , , some_utility_function() , TaskMetadata. 1) ? 2) ? 3) Django, ?
Django