Django AssertRedirects 抛出断言错误 301 != 302

Django AssertRedirects throws Assertion error 301 != 302

我的 Django 视图在调用 'get' 时有条件地重定向到错误页面或目标页面。我正在使用 redirect(reverse()) 作为重定向逻辑。当我 运行 此应用程序时, url 重定向按预期工作。为了编写测试用例,我模拟了 returns this redirect(reverse()) 的函数。我确认调用该方法时正在返回模拟响应。但是测试用例中的响应显示 http404ResponseNotFound 或断言错误 301 != 302。如何正确测试重定向?

如果我使用 self.assertRedirects(response, '/view/step/123', fetch_redirect_response=False),它会抛出 Assertion error: 301 != 302

如果我使用 self.assertRedirects(response, '/view/step/123', status_code=301, fetch_redirect_response=False),它会抛出 Assertion error: 404 != 200

Class MyView:
   def foo(self):
    try:
      # some logic
      return redirect(reverse('someview', kwargs={'key': '12345'}))
    except(ExceptionClass1, ExceptionClass2) as err:
      return errorView.as_view()(err)

   def get(self):
      # some logic
      if (some_condition)
          return self.foo() # Test case is for this line.
      return something_else
Class MyViewTests:
   @mock.patch(MyView.foo)
   def test_1(self, mock_foo):
       mock_foo.return_value = redirect(reverse('step', kwargs={'key': '123'}))
       client = Client()
       response = client.get('/myview', follow=True)
       self.assertRedirects(response, '/view/step/123', fetch_redirect_response=False)
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/mock/mock.py", line 1346, in patched
    return func(*newargs, **newkeywargs)
  File "/usr/src/app/django/tests/test_api.py", line 488, in test_1
    self.assertRedirects(response, '/view/step/123', fetch_redirect_response=False)
  File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 274, in assertRedirects
    self.assertEqual(
AssertionError: 301 != 302 : Initial response didn't redirect as expected: Response code was 301 (expected 302)

已解决。问题是,由于 follow=True ,所有后续请求也都被跟踪,如果我想断言重定向,这是必需的。因此,'assertRedirects' 将针对最终重定向的状态代码断言为 target_status_code。 200 似乎是默认值。 就我而言,我不需要测试后续重定向的行为。所以,我将代码更改为 self.assertRedirects(response, '/view/step/123', status_code=301, target_status_code=404)