Search code examples
pythondjangopython-3.xunit-testingdjango-unittest

Django unit test not modifying database


I am creating a unit test for a view PersonRemoveView that simply modifies a datetime field called deletion_date in a model called Person. This field is None until this view is executed, then it is set to timezone.now()

The problem is that the value of deletion_date is None after executing the view from the unit test.

This is the test:

def test_person_remove_view(self):
    person = models.Person.objects.get(pk=1)
    request = self.factory.post('/person/remove/{}'.format(person.id))
    response = PersonRemoveView.as_view()(request, pk=person.id)
    self.assertIsNotNone(person.deletion_date)

and this is the view:

class PersonRemoveView(PermissionRequiredMixin, generic.DeleteView):
    model = Person
    success_url = reverse_lazy('control:person_list')

   def dispatch(self, request, *args, **kwargs):
       self.object = self.get_object()
       self.object.deletion_date = timezone.now()
       self.object.save()
       return HttpResponseRedirect(self.success_url)

I have been debugging and the dispatch method is executed as expected but the temporary test database does not change and the assertIsNotNone method fails


Solution

  • Models instances are not shared so you have to reload your instance in the test to find out if the view correctly changed the underlying database record:

    def test_person_remove_view(self):
        person = models.Person.objects.get(pk=1)
        request = self.factory.post('/person/remove/{}'.format(person.id))
        response = PersonRemoveView.as_view()(request, pk=person.id)
        # reloads our instance values from the database
        person.refresh_from_db()
        self.assertIsNotNone(person.deletion_date)