- References
- Dependency
unittest2
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
class TestXxx(unittest.TestCase):
def setUp(self):
...
def tearDown(self):
...
def test_yyy_description1(self):
...
def test_yyy_description2(self):
...
self.assertTrue(1 + 2 == 3)
self.assertFalse(1 + 2 == 4)
self.assertEqual(actual, expected)
self.assertNotEqual(actual, not_expected)
self.assertIn('b', ['a', 'b', 'c'])
self.assertRaises(ValueError, your_func, arg1, arg2)
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
e.g. Function for testing exit code
def _assert_system_exit(self, expected_code, f):
with self.assertRaises(SystemExit) as cm:
f()
if isinstance(cm.exception, int):
self.assertEqual(cm.exception, expected_code)
else:
self.assertEqual(cm.exception.code, expected_code)
self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$', int, 'XYZ')
Prepare helper function.
import sys
from contextlib import contextmanager
from StringIO import StringIO
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
Then, in the test code...
with captured_output() as (out, err):
...
lines = out.getvalue().splitlines()
self.assertIn('xxx', lines)
@unittest.skip("demonstrating skipping")
def test_nothing(self):
self.fail("never happens")