Home > Software engineering >  Django Update view doesn't update an object during test
Django Update view doesn't update an object during test

Time:06-08

I'm writing tests for my views and I'm stuck with the UpdateView and the POST request. For this simple test I try just to change first_name but assertion fails. What am I doing wrong? However, when I call the response.context it gives me that (it has the updated employee):

[{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7f070ed6eee0>>, 'request': <WSGIRequest: POST '/employees/7/update'>, 'user': <SimpleLazyObject: <User: [email protected]>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7f070ecb33d0>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f070ed1b130>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Employee: John Smith>, 'employee': <Employee: John Smith>, 'form': <EmployeeUpdateForm bound=True, valid=False, fields=(first_name;last_name;user;position;reports_to;birthday;hire_date;address;phone_number;pfp)>, 'view': <employees.views.EmployeesUpdateView object at 0x7f070ed1b310>}]

The test:

class TestEmployeesUpdateView(TestCase):

def setUp(self):
    self.test_user = User.objects.create_user(
        username='test_user', email=
        '[email protected]', password='Testing12345')
    self.test_employee = Employee.objects.create(
        first_name='Bob', last_name='Smith', user=self.test_user, position='SM',
        birthday=date(year=1995, month=3, day=20),
        hire_date=date(year=2019, month=2, day=15),
        address='...',
    )
    self.client = Client()


def test_updateview_post(self):
    self.client.force_login(user=self.test_user)
    response = self.client.post(reverse('employees:employee-update', kwargs={'pk': self.test_employee.pk}), {'first_name': 'John'})
    self.test_employee.refresh_from_db()
    self.assertEqual(self.test_employee.first_name, 'John')

The view:

class EmployeesUpdateView(LoginRequiredMixin, UpdateView):
model = Employee
template_name = 'employees/employee_details.html'
form_class = EmployeeUpdateForm

And the error:

FAIL: test_updateview_post (employees.tests.test_views.TestEmployeesUpdateView)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/main/dev/project1/employees/tests/test_views.py", line 63, in test_updateview_post
    self.assertEqual(self.test_employee.first_name, 'John')
AssertionError: 'Bob' != 'John'
- Bob
  John

Edit: typo.

CodePudding user response:

You got a typo in your test_updateview_post() It is {'frist_name': 'John'}

Judging from you User, Employee Model I don't see any frist_name

CodePudding user response:

Your form is not valid, check response.context['form'].errors for errors.

  • Related