- 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):
...
assertFalse(x, msg), assertTrue(x, msg)
assertIsNone(x, msg), assertIsNotNone(x, msg)
assertEqual(x, y, msg), assertNotEqual(x, y, msg)
assertAlmostEqual(x, y, places, msg, delta), assertNotAlmostEqual(x, y, places, msg, delta)
assertGreater(x, y, msg), assertGreaterEqual(x, y, msg)
assertLess(x, y, msg), assertLessEqual(x, y, msg)
assertIs(x, y, msg), assertIsNot(x, y, msg)
assertIn(x, seq, msg), assertNotIn(x, seq, msg)
assertIsInstance(x, cls, msg), assertNotIsInstance(x, cls, msg)
assertRegex(text, regex, msg), assertNotRegex(text, regex, msg)
assertRaises(exception, callable, *args, **kwargs)
fail(msg)
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")