18

I am trying to test for an exception.

I have:

def test_set_catch_status_exception(self):
    mro = self.mro
    NEW_STATUS = 'No such status'
    self.assertRaises(ValueError,mro.setStatus(NEW_STATUS))

I get the following error:

======================================================================
ERROR: test_set_catch_status_exception (__main__.TestManagementReviewGoalGetters)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_ManagementReviewObjective.py", line 68, in test_set_catch_status_exception
    self.assertRaises(ValueError,mro.setStatus(NEW_STATUS))
  File "/Users/eric/Dropbox/ManagementReview.py", line 277, in setStatus
    raise ValueError('%s is not in the list of allowed statuses: %s' % (status,LIST_OF_STATUSES))
ValueError: No such status is not in the list of allowed statuses: ['Concern or Delay', 'On Track', 'Off Track/Needs Attention']

----------------------------------------------------------------------

Thanks

2 Answers2

41

self.assertRaises expects a function mro.setStatus, followed by an arbitrary number of arguments: in this case, just NEW_STATUS. self.assertRaises assembles its arguments into the function call mro.setStatus(NEW_STATUS) inside a try...except block, thus catching and recording the ValueError if it occurs.

Passing mro.setStatus(NEW_STATUS) as an argument to self.assertRaises causes the ValueError to occur before self.assertRaises can trap it.

So the fix is to change the parentheses to a comma:

self.assertRaises(ValueError,mro.setStatus,NEW_STATUS)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • I am using python 3.3 interpreter in pycharm IDE. What if I want to pass arguments to the function under test and also include a message in case the desired error is not raised ? Example - `self.assertRaises(ValueError, person.set_age_method, -10, "Error: Person's age cannot be negative.")` With this, I get an exception: `set_age_method takes 2 positional arguments but 3 were given`. How do I fix this ? Btw, the docs for this assertion don't clearly tell you how to do it. https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises . What is **kwds ? – MasterJoe Oct 05 '16 at 22:17
1

Be careful if you're using factory boy, this package doesn't allow the exception to be raised to the assert level which will always fail

Julio Marins
  • 10,039
  • 8
  • 48
  • 54