0

In my test.py I have:

with self.assertRaises(ValidationError):
    validate_zipfile(test_zip_path + '.zip')

And this works as intended. I also want to access the error message this ValidationError raises, so I can do this:

self.assertEqual(#error that I extract from the code above, 'Zip file not in correct format.')
3
  • Can you just write your own try-except here to check what you want? Commented Nov 12, 2015 at 17:06
  • 2
    @shuttle87: this is about unittesting, for which there is a handy framework to make assertions about exceptions being raised. Commented Nov 12, 2015 at 17:06
  • 1
    @MartijnPieters I see that it is. Previously I was using try-except with some assertions inside those because I didn't know you could store the context like you show in your answer. I'm going to go and change a couple of unit tests in my own code now to do this! Commented Nov 12, 2015 at 17:08

1 Answer 1

6

Store the assertRaises() context manager, it has an exception attribute for you to introspect the exception raised:

with self.assertRaises(ValidationError) as exception_cm:
    validate_zipfile(test_zip_path + '.zip')

exception = exception_cm.exception
self.assertIn('Zip file not in correct format.', exception.messages)

You could use the Django-specific assertRaisesMessage() method, but take into account that that test does a simple substring test (e.g. you could potentially run into a false positive where you test for a substring of a longer message). Since ValidationError handles a list of messages, a test against ValidationError.messages is going to be more robust.

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

3 Comments

Ty, simple and effective.
How do you get the ValidationError.code from this method?
@alias51 the exception attribute on the context manager is the exception instance. If you are expecting a ValidationError exception with a code attribute then that object should have the attribute: exception_cm.exception.code.

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.