gpt4 book ai didi

python - 测试用户模型是否有密码的正确方法

转载 作者:行者123 更新时间:2023-12-01 01:05:14 25 4
gpt4 key购买 nike

我有这个型号

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" 我得到了

======================================================================

FAIL: test_user_password_cannot_be_empty (myapp.tests_user_testcase.UserTestCase) AssertionError: Exception not raised by create_user_without_password

<小时/>

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

<小时/>

规范:

  • Python 3.6.1
  • Django 2.1.1
  • Windows 10

最佳答案

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

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

关于python - 测试用户模型是否有密码的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55421547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com