【问题标题】:e.message_dict keeps throwing exceptions when accessing in test filese.message_dict 在测试文件中访问时不断抛出异常
【发布时间】:2019-05-19 20:27:05
【问题描述】:

当我在测试中访问变量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'字段的错误信息。它转到异常部分,但只是我无法从错误实例中检索数据。

更新: 评论中的解决方案解决了这个问题。

【问题讨论】:

  • 错误信息%(value) is too short (minimum 6 characters)的目的是什么?您没有提供名为 value 的参数。
  • 哦,是的,这就是这个错误的原因。谢谢你帮我找出来。我真的不需要这个。
  • 你应该把这个评论变成一个简洁的答案@JohnGordon,好地方。

标签: django testing django-models django-rest-framework


【解决方案1】:

这个问题是因为models.py 中的错误,我不需要使用%() 来尝试将变量值读入字符串,但它导致了错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多