为什么我需要在Django的TestCase中使用辅助方法create_user()?

用户名

测试失败:

class LoginTest(TestCase):
    def test_login(self):
        self.user = User(username='test', password='test')
        self.user.save()
        login = self.client.login(username='test', password='test')
        self.assertTrue(login)

但这通过了:

class LoginTest(TestCase):
    def test_login(self):
        self.user = User.objects.create_user(username='test', password='test')
        login = self.client.login(username='test', password='test')
        self.assertTrue(login)

谁能解释我为什么?在TestCase类之外,它可以工作。

编辑:它正在TestCase之外工作,因为我正在尝试使用一个现有的用户。参见falsetru答案。

虚假的

如果您不使用User.objects.create_user,密码将按原样保存(不加密)。

check_password(由login,,authenticate...依次使用)期望密码已加密。

如果不使用User.objects.create_user以下代码,则最终代码将失败

>>> from django.test import Client
>>> c = Client()
>>> user = User(username='test', password='test')
>>> user.save()
>>> c.login(username='test', password='test')
False
>>> from django.contrib.auth import authenticate
>>> authenticate(username='test', password='test') # => None
>>>

使用User.objects.create_user

>>> user2 = User.objects.create_user(username='test2', password='test')
>>> c.login(username='test2', password='test')
True
>>> authenticate(username='test2', password='test')
<User: test2>
>>> user2.check_password('test')
True

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我需要在 Django 中使用 SlugField?

为什么我需要在 shareReplay 中使用管道?

为什么我需要在Android中使用super()?

为什么我们需要在C ++头文件中使用“ #if defined Identifier”?

为什么我们需要在图灵的暂停证明中使用否定部分?

为什么我们需要在Java中使用移位运算符?

为什么我需要在node-postgres中使用async / await两次

为什么我需要在代码中使用 `display: flex` 来实现纵横比技术?

为什么我需要在以下场景中使用 ReactJS state 在 AJAX 之后更新 UI

为什么我永远不需要在Redux中使用subscription?

为什么我需要在C#和PostgreSQL中使用Npgsql引用列和表?

为什么我需要在工厂中使用angular.copy?

如果我支持Fvoid类型,为什么需要在F#中使用单位类型?

为什么我们需要在Inno Setup中使用#expr指令?

为什么我需要在索引中使用下划线命名属性?

为什么我需要在所有传递闭包中使用ConfigureAwait(false)?

为什么我们需要在Html.BeginForm中使用@using

为什么我们需要在IOS中使用类别?

为什么我们需要在 ReactJs 中使用 web-pack?

为什么我需要在函数中使用数组解构来重新呈现组件?

为什么我需要在using块中使用odbcconnection.open

为什么我们需要在 Spring 中使用注解?

为什么我们需要在并发 GC 跟踪中使用 SATB 算法?

为什么我们需要在两个选择中使用 () 和?

为什么我有时需要在列表中使用 key()?

为什么我们需要在 Spring Data JPA 中使用 @Transactional 注释 Service 类

为什么需要在这段代码中使用 super 方法

为什么需要在nodejs中使用path模块?

为什么我需要在此React方法上使用这些花括号