Python - Test

> Procedural Languages > Python > Python - Test

1 - Test Runner

Test Runner in Python

1.1 - Unittest

From the standard library: https://docs.python.org/3/library/unittest.html

Example:

tests/test_main.py
import unittest
import mypackage
 
 
class TestMain(unittest.TestCase):
 
    def test_main(self):
        mypackage.main()
 
 
if __name__ == '__main__':
    unittest.main()
Advertising

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)

Syntax:

def plus1(n):
    """In a doc
 
    First test
    >>> plus1(1)
    2
 
    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
    doctest.testmod()

https://docs.python.org/3/library/doctest.html

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.

Advertising

3 - Project Definition

3.1 - setup.py

The test command of setup.py build package and run a unittest suite.

setup.py 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.
                      'module.test_suite')
  --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).

Example:

setup.py
setup(
    # ...
    test_suite="my_package.tests.test_all"
)

Doc

Advertising
lang/python/test/test.txt · Last modified: 2019/09/08 16:22 by gerardnico