【pytest】基础部分

pytest介绍:

  pytest是一个非常成熟的全功能的Python测试框架,主要特点有以下几点:

  • 简单灵活,容易上手;
  • 支持参数化;
  • 能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);
  • pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)、allure-pytest(生成测试报告)等;
  • 测试用例的skip和xfail处理;
  • 可以很好的和jenkins集成;
  • pytest默认执行顺序是按照case顺序位置先后执行的;
  • pytest.ini和conftest.py文件要放在执行的同级目录(根目录)
  • 识别case的规则:
    • 如果pytest命令行有指定目录,则从该目录中开始查找测试用例文件,如果没有指定,则从当前运行目录开始查找文件。注意,该查找是递归查找,子目录中的文件也会被查找到
    • 并不是能够查找到目录下的所有文件,只有符合命名规则的文件才会被查找。默认规则是以test_开头或者以_test结尾的.py文件
    • 在测试文件中查找Test开头的类,以及类中以test_开头的方法,查找测试文件中test_开头的函数。
  • 模块级(setup_module/teardown_module)开始于模块始末调用,全局的
  • 函数级(setup_function/teardown_function)只对函数用例生效,在函数始末调用(不在类中,在类外部)
  • 类级(setup_class/teardown_class)在类始末调用
  • 方法级(setup_method/teardown_method)在方法始末调用(在类中)
  • 方法级(setup/teardown)在方法始末调用(在类中
  • yield:yield前相当于setup,yield后相当于teardown,scpoe="module"与yield组合,相当于setup_module和teardown_module
    注意调用顺序:setup_module>setup_class>setup_method>setup>teardown>teardown_method>teardown_class>teardown_module

安装

pip install pytest

插件合集

pip install pytest-html #生成html报告
pytest --html=path/to/html/report.html;如果不添加–self-contained-html参数,生成报告的css文件是独立的,分享的时候容易数据丢失
pip install pytest-rerunfailures # 失败后重跑
命令行参数:

  • pytest – reruns 重试次数 (–reruns-delay 次数之间间隔)
  • pytest --reruns 2 运行失败的用例可以执行2次
  • pytest --reruns 2 --reruns-delay 5 运行失败的用例可以执行2次,每次间隔5秒
  • pytest.main([“-v”,“-m”,“demo”,“–reruns”,“2”,“–reruns-delay”,“5”])

pip install flaky # 只对部分用例使用重新运行机制
@pytest.mark.flaky(reruns=5, reruns_delay=2)
reruns=5, reruns_delay=2:最多失败重跑5次 & 如果失败则延迟1秒后重跑(可以不传)
@flaky(max_runs=3, min_passes=2):第一次执行失败了,将会再次重复执行它3次,如果这3次中有2次成功了,则认为这个测试通过了。

pip install allure-pytest #通过allure生成报告
pip install pytest-xdist #多个cpu并行执行用例,需要在pytest后添加参数-n,如果参数为auto,则会自动检测系统cpu个数。如果参数为数字,则指定运行测试用例的处理器进程数
demo:
pytest -n auto
pytest -n [num]
pip install PyYAML # 把测试数据放在yaml文件
此外还有很多很好的第三方插件,到 https://pypi.python.org/pypi?%3Aaction=search&term=pytest-&submit=search 查找