Can somebody tell me why the following unit-test is failing on the ValueError in test_bad, rather than catching it with assertRaises and succeeding? I think I'm using the correct procedure and syntax, but the ValueError is not getting caught.
I'm using Python 2.7.5 on a linux box.
Here is the code …
import unittest class IsOne(object): def __init__(self): pass def is_one(self, i): if (i != 1): raise ValueError class IsOne_test(unittest.TestCase): def setUp(self): self.isone = IsOne() def test_good(self): self.isone.is_one(1) self.assertTrue(True) def test_bad(self): self.assertRaises(ValueError, self.isone.is_one(2)) if __name__ == "__main__": unittest.main()
and here is the output of the unit-test:
====================================================================== ERROR: test_bad (__main__.IsOne_test) ---------------------------------------------------------------------- Traceback (most recent call last): File "test/raises.py", line 20, in test_bad self.assertRaises(ValueError, self.isone.is_one(2)) File "test/raises.py", line 8, in is_one raise ValueError ValueError ---------------------------------------------------------------------- Ran 2 tests in 0.008s FAILED (errors=1)
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.
assertRaises(exception, callable, *args, **kwds) The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.
unittest-parallel is a parallel unit test runner for Python with coverage support. By default, unittest-parallel runs unit tests on all CPU cores available. To run your unit tests with coverage, add either the "--coverage" option (for line coverage) or the "--coverage-branch" for line and branch coverage.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
Unittest's assertRaises takes a callable and arguments, so in your case, you'd call it like:
self.assertRaises(ValueError, self.isone.is_one, 2)
If you prefer, as of Python2.7, you could also use it as a context manager like:
with self.assertRaises(ValueError): self.isone.is_one(2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With