1

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

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
juankysmith
  • 11,839
  • 5
  • 37
  • 62

2 Answers2

3

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)
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
2

In your test, you get the Person instance from the database, then you execute the view, that modifies the database, but not the object you retrieved before. You need to call person.refresh_from_db() (documentation) after you execute the view, to get most recent changes from database.

Maciek
  • 3,174
  • 1
  • 22
  • 26