Skip to content

Instantly share code, notes, and snippets.

@comalex
Forked from mogproject/PythonUnitTestCheatSheet.md
Last active July 16, 2017 14:03
Show Gist options
  • Save comalex/c2e9f4a348648e80ac32d68441ca454d to your computer and use it in GitHub Desktop.
Save comalex/c2e9f4a348648e80ac32d68441ca454d to your computer and use it in GitHub Desktop.
Python unittest Cheat Sheet

Python unittest Cheat Sheet

Skeleton

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

Basic tests

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)


Test for expected exception

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

Asserting stdout

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)

Skipping test

@unittest.skip("demonstrating skipping")
def test_nothing(self):
    self.fail("never happens")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment