1

I have two directly related questions.

Django documentation recommends raising ValidationError with a code:

# Good
ValidationError(_('Invalid value'), code='invalid')

# Bad
ValidationError(_('Invalid value'))

How can I access this code in tests? All my attempts to use as_data, as_json, or simply .code on the caught exception fail. Unfortunately, the suggestions I see all relate to form validation. My test validates the models.

It is almost the same question as asked before (I don't use forms).

The related question: the same documentation page linked above gives a few examples of how to raise ValidationError, and while "Raising ValidationError" section recommends using the code, "Using validation in practice" never mentions it again, and the examples there don't use code. I wonder if that's an indication of this feature being stale.

3
  • the exception you are catching just try putting it in dir(e) and see the output. It will show you the available methods and variables on that object Commented Sep 4, 2017 at 12:26
  • It outputs ['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', '__weakref__', 'args', 'error_dict', 'message_dict', 'messages', 'update_error_dict', 'with_traceback']. Not sure what to do with it. Commented Sep 4, 2017 at 12:42
  • I think error_dict or message_dict or messages would be the attributes to try with. Just try e.messages Commented Sep 4, 2017 at 12:45

1 Answer 1

2

I learned how to debug Django tests in PyCharm, and it helped me find a solution. For others' sake:

The error codes are accessible via exception.error_dict[field_name][err_no].code. For example, the following checks a very specific error is raised:

def test_negative_photo_number(self):
    """Cannot create photo with negative photo number"""
    with self.assertRaises(ValidationError) as ve_context:
        self.create_photo(album_number=1, photo_number=-2)

    e = ve_context.exception
    print(e.error_dict)
    self.assertEqual(len(e.error_dict.keys()), 1, 'Encountered more than one problematic field')
    self.assertEqual(len(e.error_dict['number']), 1, 'Encountered more than one error')
    self.assertEqual(e.error_dict['number'][0].code, 'min_value')

For ValidationError raised outside field validators (e.g. by model.clean method), replace field name ('number' above) with __all__.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.