11

I have the following validation function in my model:

@classmethod
def validate_kind(cls, kind):
    if kind == 'test':
        raise ValidationError("Invalid question kind")

which I am trying to test as follows:

w = Model.objects.get(id=1) 

self.assertRaises(ValidationError, w.validate_kind('test'),msg='Invalid question kind')

I also tried:

self.assertRaisesRegex(w.validate_kind('test'),'Invalid question kind')

Both of these don't work correctly. What am I doing wrong?

Beliaf
  • 577
  • 2
  • 8
  • 25

3 Answers3

29

The way you are calling assertRaises is wrong - you need to pass a callable instead of calling the function itself, and pass any arguments to the function as arguments to assertRaises. Change it to:

self.assertRaises(ValidationError, w.validate_kind, 'test')
solarissmoke
  • 30,039
  • 14
  • 71
  • 73
7

The accepted answer isn't correct. self.assertRaises() doesn't check the exception message.

Correct answer

If you want to assert the exception message, you should use self.assertRaisesRegex().

self.assertRaisesRegex(ValidationError, 'Invalid question kind', w.validate_kind, 'test')

or

with self.assertRaisesRegex(ValidationError, 'Invalid question kind'):
    w.validate_kind('test')
0

I would do:

with self.assertRaises(ValidationError, msg='Invalid question kind'):
    w.validate_kind('test')

This may well be a change in Python since the question was originally asked.