Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use assertRaises in Django

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?

like image 765
Beliaf Avatar asked Apr 21 '18 10:04

Beliaf


People also ask

How do you use assertRaises?

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.

What is assertRaises?

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.

How do I skip a Django test?

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.


2 Answers

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')
like image 187
solarissmoke Avatar answered Nov 01 '22 08:11

solarissmoke


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')
like image 37
Thibault Deutsch Avatar answered Nov 01 '22 09:11

Thibault Deutsch