siebenschlaefer
4/29/2015 - 7:07 PM

template for a python unit test

template for a python unit test

#! /usr/bin/env python

import unittest


class DummyTest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_dummy(self):
        self.skipTest("just examples")
        self.assertEqual(a, b)  # a == b
        self.assertNotEqual(a, b)  # a != b
        self.assertTrue(x)  # bool(x) is True
        self.assertFalse(x)  # bool(x) is False
        self.assertIs(a, b)  # a is b
        self.assertIsNot(a, b)  # a is not b
        self.assertIsNone(x)  # x is None
        self.assertIsNotNone(x)  # x is not None
        self.assertIn(a, b)  # a in b
        self.assertNotIn(a, b)  # a not in b
        self.assertIsInstance(a, b)  # isinstance(a, b)
        self.assertNotIsInstance(a, b)  # not isinstance(a, b)
        self.assertAlmostEqual(a, b)  # round(a-b, 7) == 0
        self.assertNotAlmostEqual(a, b)  # round(a-b, 7) != 0
        self.assertGreater(a, b)  # a > b
        self.assertGreaterEqual(a, b)  # a >= b
        self.assertLess(a, b)  # a < b
        self.assertLessEqual(a, b)  # a <= b
        self.assertRegexpMatches(s, re)  # regex.search(s)
        self.assertNotRegexpMatches(s, re)  # not regex.search(s)
        self.assertItemsEqual(a, b)  # sorted(a) == sorted(b) and works with unhashable objs
        self.assertDictContainsSubset(a, b)  # all the key/value pairs in a exist in b

    def test_exception(self):
        self.skipTest("just examples")

        self.assertRaises(SomeException, callable, *args, **kwds)

        with self.assertRaises(SomeException) as cm:
            do_something()
        the_exception = cm.exception
        self.assertEqual(the_exception.error_code, 3)

        self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$', int, 'XYZ')

        with self.assertRaisesRegexp(ValueError, 'literal'):
            int('XYZ')

if __name__ == '__main__':
    unittest.main()

# vim: set ft=python sw=4 et sta: