Effective Python - 59 Specific Ways to Write Better Python.

Chapter 8 - Production

Book by Brett Slatkin. Summary notes by Tyler Banks.

Item 56: Test Everything with unittest

  • Use unittest module to test your utilities
In [4]:
# utils.py
def to_str(data):
    if isinstance(data, str):
        return data
    elif isinstance(data, bytes):
        return data.decode('utf-8')
        raise TypeError('Must supply str or bytes, found: %r' % data)
In [11]:
# utils_test.py
from unittest import TestCase, main
#from utils import to_str
class UtilsTestCase(TestCase):
    def test_to_str_bytes(self):
        self.assertEqual('hello', to_str(b'hello'))
    def test_to_str_str(self):
        self.assertEqual('hello', to_str('hello'))
    def test_to_str_bad(self):
        self.assertRaises(TypeError, to_str, object())
#if __name__ == '__main__':
#    main()
  • Use setUp and tearDown
In [9]:
class MyTest(TestCase):
    def setUp(self):
        self.test_dir = TemporaryDirectory()
    def tearDown(self):
In [ ]: