Python | Registering test results to a file

File handling | Python Methods and Functions

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:

import unittest

class MyTest ( unittest.TestCase):


if __ name__ = = `__main__` :

  unittest.main ()

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:

import sys


def main (out = sys.stderr, verbosity = 2 ) :

loader = unittest.TestLoader ()


  suite = loader.loadTestsFrom Module (sys.modules [__ name__])

unittest.TextTestRunner (out, verbosity = verbosity) .run (suite)


if __ name__ = = `__main__` :

with open ( `testing.out` , ` w` ) as f:

  main (f)

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.TestLoader instance 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.
  • The loadTestsFromTestCase () method (not shown) can be used to extract test methods from a separate class, which inherits from TestCase.
  • The TextTestRunner class 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 unittest.main () function.

Get Solution for free from DataCamp guru