py.test #run all tests below current dir
py.test test_mod.py #run tests in module
py.test somepath #run all tests below somepath
py.test -k stringexpr #only run tests with names that match the
#the "string expression", e.g. "MyClass and not method"
#will select TestMyClass.test_something
#but not TestMyClass.test_method_simple
py.test test_mod.py::test_func #only run tests that match the "node ID",
#e.g "test_mod.py::test_func" will select
#only test_func in test_mod.py
6、测试报告
pytest可以方便的生成测试报告,即可以生成HTML的测试报告,也可以生成XML格式的测试报告用来与持续集成工具集成。
生成txt格式报告:
py.test --resultlog=path/log.txt
生成XML格式的报告:
py.test --junitxml=path/log.xml
将测试报告发送到pastebin服务器,执行下面的命令会生成报告的网址
py.test test_report.py --pastebin=all
只发送失败的报告
py.test test_report.py --pastebin=failed
生成Html格式报告
这个需要安装pytest的第三方插件pytest-html:
pip install pytest-html
py.test test_report.py--html=path/log.html
7、如何获取帮助信息
py.test --version # shows where pytest was imported from
py.test--fixtures # show available builtin functionarguments
py.test-h | --help # show help on command line and config file options
与Python自带的unitest测试框架中的setup、teardown类似,pytest提供了fixture函数用以在测试执行前和执行后进行必要的准备和清理工作。但是fixture函数对setup和teardown进行了很大的改进。
fixture函数可以使用在测试函数中,测试类中,测试文件中以及整个测试工程中。
fixture支持模块化,fixture可以相互嵌套
fixture支持参数化
fixture支持unittest类型的setup和teardown
setup完成测试前的初始化工作,teardown实现测试完成后的垃圾回首工作。如果测试的程序使用jdbc连接数据库,那么setUpBeforeClass()方法中就可以写上初始化数据库连接的一些代码,tearDownAfterClass()方法中就可以写上关闭数据库连接的一些代码。
8、最佳实践
其实对于测试而言,特别是在持续集成环境中,我们的所有测试最好是在虚拟环境中。这样不同的虚拟环境中的测试不会相互干扰的。
由于我们的实际工作中,在同一个Jekins中,运行了好多种不同项目册的测试,因此,各个测试项目运行在各自的虚拟环境中。
将pytest安装在虚拟环境中:
1、将当前目录创建为虚拟环境
virtualenv . # create a virtualenv directory inthe current directory
source bin/activate # on unix
2、在虚拟环境中安装pytest:
pip install pytest
9、断言的使用
①正常断言
#子签名类,忽略中间打印的过程,直接表示出错的原因#assert value == 0, "value was odd, should be even"#等于、不等、小于、大于
assert func(2)==3
②异常断言
使用pytest.raise方法(需import pytest)
断言1除以0,将产生一个ZeroDivisionError类型的异常。
importpytestdeftest_zero_division():
with pytest.raises(ZeroDivisionError):1 / 0
有的时候,我们可能需要在测试中用到产生的异常中的某些信息,比如异常的类型type,异常的值value等等。下面我们修改下上面的测试
importpytestdeftest_recursion_depth():
with pytest.raises(ZeroDivisionError) as excinfo:1/0assert excinfo.type == 'RuntimeError'
因为该测试断言产生的异常类型是RuntimeError,而实际上产生的异常类型是ZeroDivisionError,所以测试失败了。在测试结果中,可以看到assert子表达式excinfo.type的值。