在测试中访问变量e.message_dict
时遇到以下错误,其中e
是ValidationError实例。
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E.
======================================================================
ERROR: test_invalid_user (userstweetsmanager.tests.test_models.UserTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\sites\tweet_scheduler\userstweetsmanager\tests\test_models.py", line 23, in test_invalid_user
password_too_short_user.full_clean()
File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 1203, in full_clean
raise ValidationError(errors)
django.core.exceptions.ValidationError: <unprintable ValidationError object>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\sites\tweet_scheduler\userstweetsmanager\tests\test_models.py", line 26, in test_invalid_user
self.assertTrue('password' in e.message_dict)
File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\exceptions.py", line 145, in message_dict
return dict(self)
File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\exceptions.py", line 164, in __iter__
yield field, list(ValidationError(errors))
File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\exceptions.py", line 169, in __iter__
message %= error.params
KeyError: 'value'
----------------------------------------------------------------------
Ran 2 tests in 0.005s
FAILED (errors=1)
Destroying test database for alias 'default'...
我正在使用什么: Django:版本2.2.1 Django rest框架:版本3.9.4
我在这里看到了访问错误消息的方法: https://goodcode.io/articles/django-assert-raises-validationerror/
这是我的models.py
import datetime
from django.db import models
from django import forms
from django.core.exceptions import ValidationError
from userstweetsmanager.constants import LANGUAGE_CHOICES
def password_validator(value):
if len(value) < 6:
raise ValidationError(
str('%(value) is too short (minimum 6 characters)'),
code='invalid',
params={'password': value}
)
class User(models.Model):
name = models.TextField(max_length=30, unique=True)
password = models.TextField(validators=[password_validator])
twitter_api_key = models.TextField(null=True, blank=True)
twitter_api_secret_key = models.TextField(null=True, blank=True)
twitter_access_token = models.TextField(null=True, blank=True)
twitter_access_token_secret = models.TextField(null=True, blank=True)
expire_date = models.DateField(default=datetime.date.today)
language = models.TextField(choices=LANGUAGE_CHOICES, default='1')
class Tweet(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=140)
schedule_date = models.DateField()
这是我的tests.py
from django.test import TestCase
from django.core.exceptions import ValidationError
from userstweetsmanager.models import User, Tweet
class UserTest(TestCase):
""" Test module for User model """
def setUp(self):
pass
def test_invalid_user(self):
password_too_short_user = User(name="Hello", password="fooba")
try:
password_too_short_user.full_clean()
raise AssertionError("ValidationError should be thrown")
except ValidationError as e:
self.assertTrue('password' in e.message_dict)
在此测试用例中,由于“ password”字段太短,因此它在message_dict中应该有关于“ password”字段的错误消息。它转到异常部分,但只是我无法从错误实例中检索数据。
更新: 评论中的解决方案解决了这个问题。
答案 0 :(得分:0)
发生此问题是由于models.py
中的错误,我不需要使用%()
来尝试将可变值读取到字符串中,但这引起了错误。