python - 如何对 ValidationError 进行单元测试并断言使用了正确的代码?

标签 python django python-unittest django-testing django-tests

我有一个带有 ValidationError 的模型约束:

class MyModel(models.Model)
    title = models.CharField()
      
    def clean(self):
        error_dict = {}
        if self.title='invalid_title':
                 error_dict['title'] = ValidationError(
                         'Title is invalid', code='invalid_title_code')
        
        if error_dict:
                 raise ValidationError(error_dict)

我想对这个 ValidationError 进行单元测试, 但我该如何测试 code是正确的?例如:

def test_title_invalid(self):

     with self.assertRaises(ValidationError) as cm: 
          MyModel.objects.create(title='invalid_title')
     
     exception = cm.exception

     # Test the key exists
     self.assertTrue(hasattr(exception, 'error_dict'))
     self.assertIn('title', exception.error_dict)

     # Test the message exists
     self.assertIn('Title is invalid', exception.messages)

     # Test the code exists
     self.assertIn('invalid_title_code', exception.code)

self.assertIn('invalid_title_code', exception.code) 之前一切正常,结果为 AttributeError表示'ValidationError' object has no attribute 'code'

django.core.exceptions.ValidationError 的 django 源代码中看来,如果你通过 dict object,不添加code属性:

class ValidationError(Exception):
    """An error while validating data."""
    def __init__(self, message, code=None, params=None):
        super().__init__(message, code, params)

        if isinstance(message, dict):
            self.error_dict = {}
            for field, messages in message.items():
                if not isinstance(messages, ValidationError):
                    messages = ValidationError(messages)
                self.error_dict[field] = messages.error_list
 
        else:
            self.message = message
            self.code = code
            self.params = params
            self.error_list = [self]

这是问题的原因吗?

最佳答案

这是一个嵌套异常,您可以通过以下方式访问它:

exception = cm.exception
self.assertTrue(hasattr(exception, 'error_dict'))
self.assertIn('title', exception.error_dict)
title_exceptions = <b>exception.error_dict['title']</b>
self.assertEqual(1, len(title_exceptions))
title_exception = <b>title_exceptions[0]</b>
self.assertEqual('invalid_title_code', <b>title_exception.code</b>)

关于python - 如何对 ValidationError 进行单元测试并断言使用了正确的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62877716/

相关文章:

Python:用于快速全屏 jpg/png 显示的 OSX 库

Python 请求 : Using lists when specifying parameters

python - 将 ModelMultipleChoiceField 的查询集动态设置为自定义记录集

python - django上传没有模型的文件

python - 如何为 OSError 编写单元测试?

python - 如何遍历 Python unittest runner 的所有成功测试结果?

python - 将定位器与页面对象类分开 Python Selenium

python - 在 Bokeh javascript 回调中返回源

python - 理解 Django 内部工作——从哪里开始?

python - Unittest 的 subTest 不能与 Pytest 一起使用,还是我疯了?