A bit of an odd one. I've upgraded from Django 3.2 to 4.0. A lot of my tests fail and they all fail where I'm testing the result of a form submission. However the forms themselves work fine when I test them using my browser. And all the tests fail in exactly the same way with the message AssertionError: The form 'form' in context 166 does not contain the field 'date'
(obviously the field, form name and number are different in each test).
I've looked though the Django documents to see if the way forms should be tested has changed but I don't see any mention of anything that could have caused this.
Sample test:
def test_expenses_new_and_edit_ye(self):
""" Submits expense before and after ye date, then again with edit """
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
# Redate the most recent YE to 10 days ago
ye = JournalEntry.objects.filter(type='YE').order_by('-id')[0]
ye.date = (datetime.today() - relativedelta(days=10))
ye.save()
# Try to submit into previous financial year
date = (datetime.today() - relativedelta(days=10)).strftime('%Y-%m-%d')
response = self.client.post(reverse('journal:expenses_new'), {'date':date, 'account': 20, 'expense': 7, 'project': 1, 'store': 'Test store 223', 'amount': 10})
self.assertFormError(response, 'form', 'date', 'Date must be within current financial year')
Sample output:
======================================================================
FAIL: test_expenses_new_and_edit_ye (journal.tests.test_main.ExpensesChecks)
Submits expense before and after ye date, then again with edit
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\Philip\CodeRepos\Acacia2\journal\tests\test_main.py", line 1049, in test_expenses_new_and_edit_ye
self.assertFormError(response, 'form', 'date', 'Date must be within current financial year')
File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\test\testcases.py", line 517, in assertFormError
self.fail(
AssertionError: The form 'form' in context 166 does not contain the field 'date'
Answer is that in Django 4.1 assertFormError don't get response in args https://docs.djangoproject.com/en/4.1/releases/4.1/#id2
Passing a response object and a form/formset name to SimpleTestCase.assertFormError() and assertFormsetError() is deprecated. Use:
assertFormError(response.context['form_name'], …)
assertFormsetError(response.context['formset_name'], …)
your test will be correct:
self.assertFormError(response.context['form'], 'date', 'Date must be within current financial year')