Python - Test

1 - Test Runner

Test Runner in Python

1.1 - Unittest

From the standard library:


import unittest
import mypackage

class TestMain(unittest.TestCase):

    def test_main(self):

if __name__ == '__main__':

1.2 - Pytest

1.3 - doctest

doctest describe test that look like interactive Python sessions with:

  • the command
  • the expectations (the result on the console)


def plus1(n):
    """In a doc
    First test
    >>> plus1(1)
    Second test that must throw an exception
    >>> plus1(n)
    Traceback (most recent call last):
    NameError: name 'n' is not defined
    return n + 1

if __name__ == "__main__":
    import doctest

2 - Environment

2.1 - Tox

tox is a virtualenv management and test command line tool you can use to test you code against multiple version of Python.

3 - Project Definition

3.1 -

The test command of build package and run a unittest suite. test --help
Options for 'test' command:
  --test-module (-m)  Run 'test_suite' in specified module
  --test-suite (-s)   Run single test, case or suite (e.g.
  --test-runner (-r)  Test runner to use

It runs a project’s unit tests without actually deploying it:

  • by temporarily putting the project’s source on sys.path,
  • after first running build_ext -i and egg_info to ensure that any C extensions and project metadata are up-to-date.

The project’s tests must be wrapped in a unittest test suite by either:

  • a function,
  • a TestCase class
  • or method,
  • or a module
  • or package containing TestCase classes.

If the named suite is:

  • a module, and the module has an additional_tests() function, it is called and the result (which must be a unittest.TestSuite) is added to the tests to be run.
  • a package, any submodules and subpackages are recursively added to the overall test suite with the default test_loader

Test systems should support wrapping their non-unittest tests in TestSuite objects (including doctest).


    # ...


Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap