David Dahan
David Dahan

Reputation: 11152

How to use AssertRaisesMessage() in Django tests

I followed the Django doc to write tests with assertRaisesMessage() but the problem is the exception itself is raised when executing test (so, the test is not executed). Note that the exception called is an exception I voluntarily raise in a method of my model (not in the view).

class MyTestCase(TestCase):
    def test_invertRewardState_view_fails_notmy_reward(self):
        self.client.login(email='[email protected]', password='azerty')
        resp = self.client.get(reverse(invertRewardState, args=(1,)))
        self.assertRaisesMessage(
            expected_exception=Exception,
            expected_message=EXC_NOT_YOURS,
            callable_obj=resp)

How Should I use AssertRaisesMessage() to let my test be executed without raising the Exception? Thanks.

EDIT : After trying falsetru 1st solution, the problem is still the same. As soon as my test enters in the resp = ... part, view is called, then related model method is called and raises the exception. the full stack trace :

Traceback (most recent call last):
  File "/Users/walt/Code/hellodjango/clientizr/tests.py", line 338, in test_invertRewardState_view_fails_notmy_reward
    resp = self.client.get(reverse(invertRewardState, args=('1',)))
  File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/test/client.py", line 473, in get
    response = super(Client, self).get(path, data=data, **extra)
  File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/test/client.py", line 280, in get
    return self.request(**r)
  File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/test/client.py", line 444, in request
    six.reraise(*exc_info)
  File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/walt/Code/hellodjango/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/walt/Code/hellodjango/clientizr/views.py", line 234, in invertRewardState
    reward.invert_reward_state(request.user)
  File "/Users/walt/Code/hellodjango/clientizr/models.py", line 606, in invert_reward_state
    self.throw_error_if_not_owner_reward(cur_user)
  File "/Users/walt/Code/hellodjango/clientizr/models.py", line 587, in throw_error_if_not_owner_reward
    raise Exception(EXC_NOT_YOURS)
Exception: Cet objet n'est pas le v\xf4tre

Upvotes: 8

Views: 4424

Answers (2)

falsetru
falsetru

Reputation: 368894

If you use self.client.get, you will not get an exception directly, but you can check status code.

def test_invertRewardState_view_fails_notmy_reward(self):
    self.client.login(email='[email protected]', password='azerty')
    resp = self.client.get(reverse(invertRewardState, args=('1',)))
    self.assertEqual(resp.status_code, 500)
    self.assertIn(EXC_NOT_YOURS in resp.content)

If you want to get an exception, call the view directly.

def test_invertRewardState_view_fails_notmy_reward(self):
    request = HttpRequest()
    request.user = User.objects.create(email='[email protected]')  # login
    self.assertRaisesMessage(Exception, EXC_NOT_YOURS, invertRewardState, '1')

You can use context manager form as Ned Batchelder suggested.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375484

You use assertRaisesMessage as a context manager around the code you expect to fail:

class MyTestCase(TestCase):
    def test_invertRewardState_view_fails_notmy_reward(self):
        self.client.login(email='[email protected]', password='azerty')
        url = reverse(invertRewardState, args=(1,))
        with self.assertRaisesMessage(Exception, EXC_NOT_YOURS):
            self.client.get(url)

Upvotes: 14

Related Questions