python - 测试用户模型是否有密码的正确方法
问题描述
我有这个模型
from django.db import models
from django.contrib.auth.models import AbstractUser
class Account(AbstractUser):
last_updated = models.DateTimeField(default=datetime.now, blank=False, null=False)
class User(Account):
security_question = models.TextField(blank=True)
security_answer = models.CharField(max_length=50, blank=True)
这个简单的测试用例:
from django import test
from myapp import models
class UserTestCase(test.TestCase):
def test_user_password_cannot_be_empty(self):
def create_user_without_password():
models.User.objects.create(
username='usr2',
first_name='Name',
last_name='Name2',
email='me@email.com'
)
# should throw an error
self.assertRaises(
Exception,
create_user_without_password
)
测试应该通过,因为密码是必填字段,但通过运行python manage.py test --pattern="tests_*.py"
我得到
==================================================== =====================
失败:test_user_password_cannot_be_empty (myapp.tests_user_testcase.UserTestCase) AssertionError: 异常未由 create_user_without_password 引发
我想我测试错了。正确的方法是什么?
眼镜:
- Python 3.6.1
- Django 2.1.1
- 视窗 10
解决方案
您可能遇到了 Django 模型将blank=False
无错误地保存字段的性质。你可以找到关于它的冗长辩论。要在model.save
级别强制执行它,您必须覆盖 save 方法。
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
推荐阅读
- python - 如何仅在python中的某个块内读取HTML文件?
- regex - 正则表达式:匹配两个关键字之间的字符串与多行无用数据混合
- java - 显示输出后如何在我的数组中搜索元素?
- python - 将列动态添加到 pyplot 不起作用
- java - Maven,org.apache.maven.plugins:maven-compiler-plugin:3.8.0 中的编译失败
- wpf - 有没有办法在屏幕上移动一些图像并在它们移动时将场景记录为视频?
- javascript - 单击图像时隐藏 div 并打开另一个 div
- python - on_disconnect 没有被触发 python
- c# - 使用 XAML 中的转换器更改背景颜色
- java - 加载 spring 上下文时,不会创建存储库 bean