【问题标题】:Upgrade to Django 4.0 has caused tests to fail even when the feature being tested works升级到 Django 4.0 导致测试失败,即使正在测试的功能正常
【发布时间】:2023-01-19 22:43:30
【问题描述】:

有点奇怪。我已经从 Django 3.2 升级到 4.0。我的很多测试都失败了,而且在我测试表单提交结果的地方它们都失败了。然而,当我使用我的浏览器测试它们时,这些表单本身工作正常。所有测试都以完全相同的方式失败并显示消息AssertionError: The form 'form' in context 166 does not contain the field 'date'(显然每个测试中的字段、表单名称和编号都不同)。

我查看了 Django 文档以查看应测试表单的方式是否已更改,但我没有看到任何可能导致此问题的提及。

样品测试:

    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')

示例输出:

======================================================================
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'

【问题讨论】:

  • 啊。我也刚刚偶然发现了这个问题,不明白为什么我的assertFormError 测试突然失败了。你找到问题的根源了吗?
  • 我没有追根究底。我暂时将我的 Django 留在第 3 版。

标签: django django-tests django-4.0


【解决方案1】:

答案是在 Django 4 assertFormError 中没有在 args 中得到响应 https://docs.djangoproject.com/en/4.1/releases/4.1/#id2

将响应对象和表单/表单集名称传递给 SimpleTestCase.assertFormError() 和 assertFormsetError() 已弃用。利用: assertFormError(response.context['form_name'], …) assertFormsetError(response.context['formset_name'], …)

你的测试将是正确的:

self.assertFormError(response.context['form'], 'date', 'Date must be within current financial year')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2015-03-13
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多