常用命令选项
pytest --help 显示全部选项
pytest --collect-only 给定配置下显示那些用例会运行
pytest -k "asdict or defaults" --collect-only 筛选用例
pytest -x 遇到失败后停止测试
pytest --tb=no 关闭错误信息回溯argument --tb: (choose from 'short', 'no', 'line')
pytest --maxfail=2 --tb=no 明确指定失败几次后停止
pytest -s(pytest --capture=no) 信息捕获方法pytest --capture=sys和pytest --capture=fd
pytest -l(pytest --showlocals) 避免一些不必要的print语句
pytest -lf --tb=no 定位到最后一个失败的用例
pytest -ff --tb=no 定位到第一个失败的用例,ff会运行完剩余的用例
pytest -v --ff --tb=no 每个用例占一行(之前是每个文件占一行)
pytest -q 简化输出信息
pytest -l 打印本地变量
pytest --duration=3 显示耗时最长的三个阶段
pytest --version 查看pytest版本及安装目录
– collect-only
–collect-only 选项可以展示在给定的配置下哪些测试用例会被运行
pytest --collect-only
-s选项
用-s运行显示内部的打印信息
-k选项
-k 使用表达式匹配到指定希望运行的测试用例,查询测试名包含‘study’的用例
pytest --collect-only -k 'study'
执行执行某文件/某类/某方法的测试用例
pytest -v 文件路径::测试类 #执行某个测试类中的测试用例
-v选项
使用-v/–verbose选项,输出的信息会更详细。最明显的区别就是每个文件中的每个测试用例都占一行,测试的名字和结果都会显示出来
pytest -v
-m 选项
标记(marker)用于标记并分组,甚至都不在同一个文件里,如果你喜欢同时选中它们,那么可以预先标记。
使用什么标记名由你自己决定,例如 run_there_please 则可以使用@pytest.mark.run_there_please这样的装饰器(decorator)来做标记
#a.py文件
@pytest.mark,run_there_please
def test_replace():
pass
#b.py文件
@pytest.mark,run_there_please
def test_member_access():
pass
pytest -m 'run_there_please '
多个标记表达式:
-m ‘mark1 and mark2’ 可以同时选中带有这两个标记的所有测试用例,
-m ‘maek1 and not mark2’ 则会选中有Mark1的测试用例,过滤有mark2的测试用例 ,
-m 'mark1 and mark2’则带有Mark1 和mark2的所有测试用例
-x选项
正常情况下,pytest会运行每一个搜索到测试用例,如果某个测试断言失败或者异常,该条测试用例就对到此为止,继续执行其他的测试用例,使用 -x 后遇到失败会直接停止使用,主要用于debug
pytest -x
–maxfail==num选项
-x选项的特点是, 一旦遇到测试失败,就会全局停止。
如设置–maxfail=2,则需要遇到2次错误才会停止,这样前面只存在一个失败测试的就会全都被执行
pytest --maxfail==2
–lf(–last-failed)选项
执行将上一次执行失败的用例
pytest --lf
–ff(–failed-first)选项
先执行上一次执行失败的用例,再继续重新执行所有用例
pytest --ff
–nf(–failed-first)选项
先执行新增的用例,再执行其他其他全部用例
pytest --nf