Using the unittest library for testing
For more complex testing, the doctest
examples may not provide enough depth or flexibility. A docstring with a large number of cases would become too long to be effective as documentation. A docstring with complex test setup, teardown, or mock objects may not be useful as documentation either.
For these cases, we'll use the unittest
module to define test cases and test suites. When using unittest
, we'll generally create separate modules. These test modules will contain TestCase
classes that contain test methods.
Here's a quick overview of a typical test case class definition:
import unittest from Chapter_7.ch07_ex1 import FtoC class Test_FtoC(unittest.TestCase): def setUp(self): self.temps= [50, 60, 72] def test_single(self): self.assertAlmostEqual(0.0, FtoC(32)) self.assertAlmostEqual(100.0, FtoC(212)) def test_map(self): temps_c = list(map(FtoC, self.temps)) self.assertEqual(3, len...