Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittest: assert right SystemExit code

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'
like image 527
user1251007 Avatar asked Nov 21 '12 10:11

user1251007


People also ask

What does unittest assert do?

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.

How do you assert false in Python?

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.

How do I run a unittest code in Python?

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 .

Is PyUnit and unittest same?

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.)


1 Answers

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)
like image 129
user1251007 Avatar answered Sep 18 '22 01:09

user1251007