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?
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
assertraises is a function that fails unless an exception is raised by an object of a class. It is mostly used in testing scenarios to prevent our code from malfunctioning.
Just trick it to always skip with the argument True : @skipIf(True, "I don't want to run this test yet") def test_something(): ... If you are looking to simply not run certain test files, the best way is probably to use fab or other tool and run particular tests.
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')
Note that you can't test the exception message with this construction - if you want to test the message you need to use assertRaises
as a context manager:
with self.assertRaises(ValidationError, msg='Invalid question kind'):
w.validate_kind('test')
The accepted answer isn't correct. self.assertRaises()
doesn't check the exception message.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With