A very common technique for running unit tests — include a small piece of code (as shown in the code below) at the bottom of the test file.
Code # 1:
This makes the test executable and prints the test execution results to standard output. To redirect this output, unwind the main () call a bit and write your own main () function as shown in the code below:
Code # 2:
How it works:
- The interesting thing in the code is not so much the problem of redirecting the results The fact that this exposes some of the notable inner workings of the unittest module.
- At a basic level, the unittest module works by building a suite of tests first.
- This test suite consists of various test methods that you have defined. Once a package is built, its tests are run.
- These two parts of unit testing are separate from each other. The
unittest.TestLoaderinstance created in the solution is used to build the test suite.
loadTestsFromModule ()is one of several methods it defines for collecting tests ... In this case, it scans the module for TestCase classes and extracts test methods from them.
loadTestsFromTestCase ()method (not shown) can be used to extract test methods from a separate class, which inherits from TestCase.
TextTestRunnerclass is an example of a test runner class. The main purpose of this class is — run the tests contained in the test suite. This class — the same test runner that sits behind the