【问题标题】:Django tests not isolated when testing authentication测试身份验证时 Django 测试未隔离
【发布时间】:2022-11-02 02:24:28
【问题描述】:

我正在使用django.test.Client 测试我的身份验证,两个测试用例失败,因为一旦我测试我的test_login_success 测试用例,其他测试失败,因为用户仍然经过身份验证,即使我在setUp 类中实例化一个新客户端也是如此甚至删除tearDown 中的用户。

我的代码:

from django.test import Client, TestCase

from app.users.models import User


class TestLogin(TestCase):

    def setUp(self):
        super().setUp()
        self.email = 'test@test.com'
        self.password = 'SomeRandomPass96'
        User.objects.create_user(email=self.email, password=self.password)
        self.client = Client()

    def tearDown(self):
        User.objects.filter(email=self.email).delete()
        super().tearDown()

    def test_not_authenticated(self):  # success the first time, fails after test_login_success is executed for the first time.
        user = User.objects.get(email=self.email)
        assert not user.is_authenticated

    def test_login_success(self):  # always success
        self.client.post(
            '/users/login/',
            {'email': self.email, 'password': self.password}
        )
    
        user = User.objects.get(email=self.email)
        assert user.is_authenticated

    def test_login_wrong_credentials(self):  # success the first time, fails after test_login_success is executed for the first time.
        self.client.post(
            '/users/login/',
            {'email': self.email, 'password': 'wrongPassword123'}
        )

        user = User.objects.get(email=self.email)
        assert not user.is_authenticated

【问题讨论】:

    标签: python django unit-testing django-tests


    【解决方案1】:

    也许您可以使用 Client 类中的 logout 方法。 此方法“通过删除 cookie 和会话对象注销用户。”

    告诉我这是否有效。

    【讨论】:

    • 我试过了,它仍然是经过身份验证的......非常奇怪,但很酷我知道现在存在这种方法
    【解决方案2】:

    错误:user.is_authenticated 未执行此代码中的预期操作。由于视图中request 对象中的用户将是AnonymousUser 或User 实例,具体取决于它是否经过身份验证并且我直接从数据库访问用户实例。

    正确的方法是从请求对象访问用户,并且由于我们在测试用例中没有视图上下文,因此 Django 在响应中提供它返回,如下所示:

    def test_not_authenticated(self):
        response = self.client.get('')
        user = response.wsgi_request.user
        assert not user.is_authenticated
    

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 2015-06-01
      • 2018-07-04
      • 2013-02-21
      • 2015-08-18
      • 2022-01-04
      • 2015-11-04
      • 1970-01-01
      相关资源
      最近更新 更多