我正在尝试使用其内置登录功能登录测试客户端。我正在尝试进行单元测试视图,并需要登录以测试其中一些。我一直在尝试做太久,需要帮助。一些注释:

create_user()确实创建有效的用户,它已在其他位置使用。

从我看到的client.login()的情况下,它返回了布尔值,当我进行测试时,故障是“ false是不正确的”,所以这似乎是正确的。

我成功登录的唯一方法是调用客户端。我觉得很奇怪。

def setUp(self):
    """
    Initializes the test client and logs it in.
    """
    self.user = create_user()
    self.logged_in = self.client.login(username=self.user.username, password=self.user.password)

def test_valid(self):
    self.assertTrue(self.logged_in)

我已将其更改为以下内容:

def setUp(self):
    """
    Initializes the test client and logs it in.
    """
    self.password = "password"
    self.user = create_user(password=self.password)
    self.logged_in = self.client.login(username=self.user.username, password=self.password)

它仍然无法登录。

Create用户在类“静态”中,并在user_count初始化为0中,该函数如下:

def create_user(username=None, password=None, email=None, is_superuser=False):
    if username is None:
        username = "user%d" % Static.user_count
        while User.objects.filter(username=username).count() != 0:
            Static.user_count += 1
            username = "user%d" % Static.user_count
    if password is None:
        password = "password"
    if email is None:
        email="user%d@test.com" % Static.user_count

    Static.user_count += 1
    user = User.objects.create(username=username, password=password,   is_superuser=is_superuser)
有帮助吗?

解决方案

您无法直接访问密码。这 password 属性是加密的。 (看 Django密码管理.)

例如,这里的密码示例输出。

>>> user = User.objects.create_user(username='asdf', email='asdf@example.com', password='xxxx')
>>> user.password
'sha1$166e7$4028738f0c0df0e7ec3cec06843c35d2b5a1aae8'

如你看到的, user.password 不是 xxxx 我给了。

我会修改 create_user 接受可选密码参数。并将密码传递给 create_user, , 和 client.login 如下:

def setUp(self):
    """
    Initializes the test client and logs it in.
    """
    password = 'secret'
    self.user = create_user(password=password)
    self.logged_in = self.client.login(username=self.user.username, password=password)

更新

create_user 应该使用 User.objects.create_user 代替 User.objects.create. 。并且应返回创建的用户对象:

def create_user(username=None, password=None, email=None, is_superuser=False):
    if username is None:
        username = "user%d" % Static.user_count
        while User.objects.filter(username=username).count() != 0:
            Static.user_count += 1
            username = "user%d" % Static.user_count
    if password is None:
        password = "password"
    if email is None:
        email="user%d@test.com" % Static.user_count

    Static.user_count += 1
    user = User.objects.create_user(username=username, password=password)
    #                   ^^^^^^^^^^^
    user.is_superuser = is_superuser
    user.save()
    return user # <---
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top