DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Python Unit Test with pytest


pytest is much flexible than unittest. Install it with conda install -c anaconda pytest.

In any Python file whose name matches test_*.py or *_test.py, any test_ prefixed test functions or methods outside of class, or test_ prefixed test functions or methods inside Test prefixed test classes (without an init method), will be collected as a test case and run by pytest.

See Conventions for Python test discovery for details.

Here is a minimal demo:

$ cat << EOF > test_demo.py
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 4
EOF

$ python -m pytest
$ python -m pytest -k demo
$ python -m pytest test_demo.py::test_answer

So run one or a group pytest testcase(s) with:

  • python -m pytest my_test.py

  • python -m pytest my_test.py::TestClass::test_func

  • python -m pytest -k 'the_keyword'

The keyword method (the last item of above list) is especially effective. The keyword can be part of the module name, test function or test class name.

Debuging a test

Go into debugger pdb when a exception raised by adding option --pdb: pytest --pdb test_module.py.

Starting the debugging process in the beginning with option --trace. For example: pytest -k 'the_keyword' --trace.

Now you're in a pdb shell. Use b to add breakpoint, n or c to proceed, and display to add variable watch.

IPython Integration

使用 pytest 结合 IPython console 写测试用例比 unittest 方便, unittest 使用的是类架构,变量要写成 self.var1,放到 IPython 里需要改成 var1, 从 IPython 里转到测试用例里时,又要为所有变量加上 self.,反反复复很麻烦, 而 pytest 可以写函数,避免了这个问题。

从 pytest 文件中提取代码到 IPython console 中,避开函数声明即可: load -r10:18,20 test_stations.py

Print to console

By default pytest captures the std.err. So writing print() in a pytest funcation, you can't see the output in the console.

pytest can disable this feature by add the -s option: pytest -s test_app.py.

Ref:

How can I see normal print output created during pytest run?

Setup vs Fixture

pytest uses fixtures instead of traditional setup/teardown style.

A fixture is a function with arbitrary name returns a object. The test function uses this fixture as parameter, and get data from it.



Published

Nov 27, 2018

Last Updated

Dec 16, 2018

Category

Tech

Tags

  • pytest 1
  • python 136
  • unit test 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor