Unit Test Problem with assertRaises
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 o开发者_如何学编程f 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
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)
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
精彩评论