I am using unittest to assert that my script raises the right SystemExit
code.
Based on the example from http://docs.python.org/3.3/library/unittest.html#unittest.TestCase.assertRaises
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
I coded this:
with self.assertRaises(SystemExit) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
However, this does not work. The following error comes up:
AttributeError: 'SystemExit' object has no attribute 'error_code'
The assert section ensures that the code behaves as expected. Assertions replace us humans in checking that the software does what it should. They express requirements that the unit under test is expected to meet. Now, often one can write slightly different assertions to capture a given requirement.
Python unittest – assertFalse() function This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false.
The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .
PyUnit is an easy way to create unit testing programs and UnitTests with Python. (Note that docs.python.org uses the name "unittest", which is also the module name.)
SystemExit derives directly from BaseException and not StandardError, thus it does not have the attribute error_code
.
Instead of error_code
you have to use the attribute code
. The example would look like this:
with self.assertRaises(SystemExit) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.code, 3)
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