gpt4 book ai didi

django - 测试何时引发 ValidationError

转载 作者:行者123 更新时间:2023-11-28 21:20:43 27 4
gpt4 key购买 nike

我是编程和 Django 的新手。我正在尝试测试我的功能之一以确保引发验证错误。测试确认出现了错误,但也表示测试失败。这怎么可能?

**models.py**
def check_user_words(sender, instance, **kwargs):
for field in instance._meta.get_fields():
#field_name = getattr(instance, field.attname)
if (isinstance(field, models.CharField) and
contains_bad_words(getattr(instance, field.attname))):
raise ValidationError("We don't use words like '{}' around here!".format(getattr(instance, field.attname)))

#tests.py
from __future__ import unicode_literals
import datetime
from django.test import TestCase
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
from .models import Question, Choice, contains_bad_words, check_user_words
from django.core.exceptions import ValidationError


def create_question(question_text, days):
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)


class ContainsBadWordsTests(TestCase):
def test_check_user_words(self):
question = create_question(question_text="What a minute bucko", days=1)
with self.assertRaises(ValidationError):
check_user_words(question)
question.full_clean()

#after running python manage.py test polls
......
raise ValidationError("We don't use words like '{}' around here!".format(getattr(instance, field.attname)))
ValidationError: [u"We don't use words like 'What a minute bucko' around here!"]

models.py 我如何导入

from __future__ import unicode_literals .... (and others)

filepath = "polls/static/polls/blacklist.yaml"
config = yaml_loader(filepath)
blacklist = [word.lower() for word in config['blacklist']]

def contains_bad_words(user_input_txt):
""" remove punctuation from text
and make it case-insensitive"""
user_typ = user_input_txt.encode()
translate_table = maketrans(string.punctuation, 32 * " ")
words = user_typ.translate(translate_table).lower().split()
for bad_word in blacklist:
for word in words:
if word == bad_word:
return True
return False

@receiver(pre_save)
def check_user_words(sender, instance, **kwargs):
for field in instance._meta.get_fields():
if (isinstance(field, models.CharField) and
contains_bad_words(getattr(instance, field.attname))):
raise ValidationError("We don't use words like '{}' around here!".format(getattr(instance, field.attname)))

最佳答案

我们需要查看更多您的代码(特别是 create_question() 以及 check_user_words 如何连接到信号)才能确定,但​​我认为问题在于您正在使用 post_save 信号处理程序来执行 check_user_words()

如果是这种情况,那么您的测试失败的原因是 create_question() 会导致 post_save 信号触发,而 check_user_words() 将立即执行 - 即 with self.assertRaises 上下文之前,因此您的测试失败。

如果是这种情况,那么试试这个:

def test_check_user_words(self):
with self.assertRaises(ValidationError):
create_question(question_text="What a minute bucko", days=1)

这个测试现在应该通过了,因为一旦你尝试创建问题就会抛出验证错误。

但是请注意,在信号中执行此操作会在尝试保存对象时导致未捕获的异常。根据您的用例,您最好在模型本身 ( see docs here ) 的 clean() 方法中执行此操作,因为这会导致在模型表单上报告适当的错误等:

def clean(self):
for field in instance._meta.get_fields():
if (isinstance(field, models.CharField) and contains_bad_words(getattr(instance, field.attname))):
raise ValidationError("We don't use words like '{}' around here!".format(getattr(instance, field.attname)))

(然后放下您的信号处理程序)。然后你可以测试这个:

q = create_question(question_text="What a minute bucko", days=1)
with self.assertRaises(ValidationError):
q.clean()

关于django - 测试何时引发 ValidationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52473412/

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