Django unitTest response.content 没有显示正确的用户信息

Django unitTest response.content doesnt show proper user info

我面临以下问题。当我运行 进行单元测试以验证用户是否正确登录时,返回的 HTTP 响应不包含模板中的变量。

class WorkflowViewTest(TestCase):

    def test_response_authorized(self):
        User = get_user_model()
        user = User.objects.get(username='JohnDoe')

        self.client.force_login(user)
        response = self.client.get('/workflow/')

        print(response.content.decode()) # response content is not right

        self.assertEqual(response.status_code, 200) # assertions are passing just fine
        self.assertTemplateUsed(response, 'workflow.html')

使用模板'workflow.html'的简化内容为:

{% extends "base_generic.html" %}
{% load static %}

{% block content %}

{% if user %}
{{user}}
{{user.username}}
{{user.first_name}}
{{user.last_name}}
{{user.email}}

{% else %}

User variable not provided

{% endif %}
{% endblock %}

response.context.content 编码如下:

<body>

AnonymousUser





</body>
</html>

我尝试在测试的设置中创建一个用户,我也手动创建了用户,我尝试了 self.client.force_login()self.client.login()。 None 我发现的建议解决方案有效。

我非常感谢任何见解。谢谢

我没有意识到我在 settings.py 默认 AUTHENTICATION_BACKENDS 中更改了我公司的后台。为了在没有用户真正登录的情况下测试应用程序的行为,我必须另外对上述更改进行 @modify_settings 或创建 test_setting 如下:

@modify_settings(AUTHENTICATION_BACKENDS={'remove': 'django.contrib.auth.backends.RemoteUserBackend',
                                          'append': 'django.contrib.auth.backends.ModelBackend'})
class WorkflowViewTest(TestCase):

    def setUp(self):