首页 > 解决方案 > 测试用户模型是否有密码的正确方法

问题描述

我有这个模型

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 引发


我想我测试错了。正确的方法是什么?


眼镜:

标签: pythondjango

解决方案


您可能遇到了 Django 模型将blank=False无错误地保存字段的性质。你可以找到关于它的冗长辩论。要在model.save级别强制执行它,您必须覆盖 save 方法。

def save(self, *args, **kwargs):
    self.full_clean()
    super().save(*args, **kwargs)

推荐阅读