Django 断言错误 - 302 不是 302

Django AssertionError - 302 is not 302

我为接受 POST 文件请求的端点设置了一个超级简单的单元测试,并在成功上传后将用户重定向到新页面。此单元测试的目标是确保文件上传正常工作。

tests.py

c = Client()
with open('replays/static/test.txt', 'r', ) as f:
    response = c.post(
        '/upload/',
        {
            'summoner': 'test user',
            'title': 'Testing title',
            'replay': f
        },
        follow=False
    )

    print(response.status_code)
    print(response.status_code == 302)
    self.assertIs(response.status_code, 302)

输出

$ python manage.py test replays
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
302
True
======================================================================
FAIL: test_create_replay (replays.tests.ReplayCreationTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/project/tests.py", line 52, in test_create_replay
    self.assertIs(response.status_code, 302)
AssertionError: 302 is not 302

----------------------------------------------------------------------
Ran 1 test in 0.173s

FAILED (failures=1)
Destroying test database for alias 'default'...

如果我在调用测试客户端的 post 方法时更改了以下重定向的参数,一切都会按预期工作,response_status 为 200

tests.py - 跟随重定向

c = Client()
    with open('replays/static/test.txt', 'r', ) as f:
        response = c.post(
            '/upload/',
            {
                'summoner': 'test user',
                'title': 'Testing title',
                'replay': f
            },
            follow=True
        )

    print(response.status_code)
    print(response.status_code == 200)
    self.assertIs(response.status_code, 200)

输出

$ python manage.py test replays
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
200
True
.
----------------------------------------------------------------------
Ran 1 test in 0.196s

OK
Destroying test database for alias 'default'...

我错过了什么?这似乎不应该是断言语句的预期行为。我正在使用 Django 3.1。

AssertIs 检查是否 x is y,换句话说,xy 指的是 相同的 对象。但是你可以有两个 int 对象,它们都是 302,但不是同一个对象。

你应该使用 .AssertEqual(…) [Python-doc]:

self.<b>assertEqual(</b>302, response.status_code<b>)</b>

对于小整数,CPython 解释器将为 -5 到 256 构造 int 对象,因此使用 享元模式:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

这意味着对于-5到256之间的int,它将引用相同的对象,对于该范围之外的值,它通常会构造一个新对象.