1. 安装pytest

pip install -U pytest  

2. 验证安装的版本

py.test --version  

3. 如何编写pytest测试样例

通过上面2个实例,我们发现编写pytest测试样例非常简单,只需要按照下面的规则:

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 __init__ 方法
  • 测试函数以test_开头
  • 断言使用基本的assert即可

4. 执行测试样例的方法很多种,上面第一个实例是直接执行py.test,第二个实例是传递了测试文件给py.test。其实py.test有好多种方法执行测试:

[python] view plain copy

  1. py.test               # run all tests below current dir  
  2. py.test test_mod.py   # run tests in module  
  3. py.test somepath      # run all tests below somepath  
  4. py.test -k stringexpr # only run tests with names that match the  
  5.                       # the "string expression", e.g. "MyClass and not method"  
  6.                       # will select TestMyClass.test_something  
  7.                       # but not TestMyClass.test_method_simple  
  8. py.test test_mod.py::test_func # only run tests that match the "node ID",  
  9.                    # e.g "test_mod.py::test_func" will select  
  10. 10.                                # only test_func in test_mod.py  
  11. 测试报告

生成HTML格式报告:

[python] view plain copy

  1. py.test --resultlog=path  

生成XML格式的报告:

[python] view plain copy

  1. py.test --junitxml=path  
  2. 如何获取帮助信息

[python] view plain copy

  1. py.test --version # shows where pytest was imported from  
  2. py.test --fixtures # show available builtin function arguments  
  3. py.test -h | --help # show help on command line and config file options