>>>>> "RJ" == robin and jim <rob...@ea...> writes:
RJ> Hello, I'm using the unittest module shipped with PythonWin
RJ> 2.2.1, and I am having trouble using assertRaises. Here is a
RJ> code fragment example.
RJ> def test_01(self):
RJ> '''handling the failure to connect with and log onto a
RJ> FTP server'''
RJ> try:
RJ> self.testable.open()
RJ> except Exception:
RJ> pass
RJ> else:
RJ> self.fail('exception not raised')
RJ> def test_02(self):
RJ> '''handling the failure to connect with and log onto a FTP server'''
RJ> self.assertRaises(Exception, self.testable.open())
RJ> test_01 works as expected (i.e., when the open() operation
RJ> fails, the test succeeds).
RJ> However, test_02 does not work as expected; when the open()
RJ> operation fails, the test also fails (i.e., the exception is not
RJ> caught by assertRaises).
RJ> What am I doing wrong?
Do not call open() before passing it to assertRaises().
self.assertRaises(Exception, self.testable.open)
should work just like test_01. The code you wrote will call
self.testable.open() before calling assertRaises(), which means
assertRaises() will never get a chance to catch the exception. You
probably overlooked that assertRaises() takes a callable object -- a
function or method or something like that -- as its second argument.
It also takes a variable number of other arguments that is passes as
arguments to the callable.
Say you were testing this function:
def f(x, y):
return x / y
You would write:
self.assertRaises(ZeroDivisionError, f, 12, 0)
Internally, assertRaises() will call f(12, 0) within a try/except
block that catches ZeroDivisionError.
Jeremy
|