[英]Django Update view doesn't update an object during test
我正在為我的視圖編寫測試,但我堅持使用 UpdateView 和 POST 請求。 對於這個簡單的測試,我嘗試只更改 first_name 但斷言失敗。 我究竟做錯了什么? 但是,當我調用 response.context 時,它給了我(它有更新的員工):
[{'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: testuser@test.com>>, '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>}]
考試:
class TestEmployeesUpdateView(TestCase):
def setUp(self):
self.test_user = User.objects.create_user(
username='test_user', email=
'testuser@test.com', 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')
風景:
class EmployeesUpdateView(LoginRequiredMixin, UpdateView):
model = Employee
template_name = 'employees/employee_details.html'
form_class = EmployeeUpdateForm
和錯誤:
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
編輯:錯字。
你的 test_updateview_post() 中有錯字是 {'frist_name': 'John'}
從你的用戶來看,員工 Model 我沒有看到任何 frist_name
您的表單無效,請檢查 response.context['form'].errors 是否有錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.