Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 42piratas/bc339cd430c538a2092639750c658f54 to your computer and use it in GitHub Desktop.
Save 42piratas/bc339cd430c538a2092639750c658f54 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

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

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