I'm currently writing some tests for a Django app. I've got the following standalone function in my app's signals.py file:
def updateLeaveCounts():
# Setting some variables here
todaysPeriods = Period.objects.filter(end__lte=today_end, end__gte=today_start).filter(request__leavetype="AN")
for period in todaysPeriods:
print period
counter = LeaveCounter.objects.get(pk=period.request.submitter)
# some Logic here
period.batch_processed = True
period.save()
and in my TestCase, I'm calling it as follows:
def test_johnsPostLeaveCounters(self):
# Some setup here
p = Period.objects.create(request=request,start=datetime(today.year,today.month,today.day,9),end=datetime(today.year,today.month,today.day,16,30),length='whole')
updateLeaveCounts()
self.assertEqual(p.batch_processed,True)
updateLeaveCounts()
is catching my newly created Period object in the for loop (I can see its details printed to the console by print period
), but my assertEqual() test is failing - telling me that the batch_processed attribute is still False.
It's as if the period.save()
transaction isn't being called.
I'm aware that in Django versions prior to 1.8, you'd have to use the TransactionTestCase class, but I'm running 1.8.3 for this project at the moment, so I don't believe that's the issue.
Is there something I need to do to have the TestCases correctly reflect the model.save()
action I'm performing in this function and hence have this function covered by tests?
Try to use refresh_from_db:
# ...
updateLeaveCounts()
p.refresh_from_db()
self.assertEqual(p.batch_processed, True)
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With