Change language

Python | Registering test results to a file


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.


Best laptop for Sims 4


Best laptop for Zoom


Best laptop for Minecraft


Best laptop for engineering student


Best laptop for development


Best laptop for Cricut Maker


Best laptop for hacking


Best laptop for Machine Learning


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method