Pytest进阶使用( 二 )

addopts = -v -s --alluredir=./results
指定/忽略执行目录;设置执行得路径;testpaths = bilibili baidu;忽略某些文件夹/目录norecursedirs = result logs datas test_demo*插件开发
  • pytest插件分类
    • 外部插件:pip install 安装的插件
    • 本地插件:pytest自动模块发现机制(conftest.py存放的)
    • 内置插件:代码内部的_pytest目录加载(hook函数)
官网:https://pypi.org/
常用插件
Pytest进阶使用

文章插图
每一种测试框架收集测试用例的顺序是不一样的
pytest执行顺序控制
  • 场景:
对于集成测试,经常会有上下文依赖关系的测试用例 。如十个步骤 , 拆分成十个case , 这时候能知道到底执行到哪步报错 。
用例默认执行顺序:自上而下执行
  • 解决:
可以通过setup,teardown和fixture来解决,也可以使用pytest-ordering插件来解决
  • 安装:pip install pytest-ordering
  • 用法:@pytest.mark.run(order=2)
  • 注意:多个插件装饰器(>2)的时候,有可能会发生冲突
并行与分布式并发执行(xdist)场景1:
  • 测试用例1000条,一个用例执行1分钟,一个测试人员需要1000分钟,通常我们会用人力成本换取时间成本,加几个人一起执行,时间就会缩短 。这就是一种分布式场景 。
场景2:
  • 假设有个报名系统,对报名总数进行统计,数据同时进行修改操作的时候有可能出现问题,需要模拟这个场景,需要多用户并发请求数据
解决:
  • 使用分布式并发执行测试用例 , 分布式插件:pytest-xdist
  • 安装:pip install pytest-xdist
  • 注意:用例多的时候效果明显,多进程并发执行,同时支持allure
hook函数1. 介绍
  • 是个函数,在系统消息触发时被系统调用
  • 自动触发机制
  • Hook函数的名称是确定的
  • pytest有非常多的hook函数
  • 使用时直接编写函数体
  • 执行是有先后顺序的
  • 可以在不同阶段实现不同的功能
pytest执行过程
Pytest进阶使用

文章插图
执行顺序:
  • 介绍:https://ceshiren.com/t/topic/8807
  • 简洁版:

Pytest进阶使用

文章插图
pytest编写插件1-修改默认编码pytest_collection_modifyitems收集上来的测试用例实现定制化功能
解决问题:
  • 自定义用例的执行顺序
  • 解决编码问题(中文的测试用例名称)
  • 自动添加标签
from typing import List# 修改编码的hook函数def pytest_collection_modifyitems(session: "Session", config: "Config", items: List["Item"]) -> None:# items里的name是测试用例的名字 , nodeid是测试用例的路径print(items)for item in items:# 如果想改变unicode编码格式的话,需要先encode成utf-8格式的,再decode成unicode-escape就可以了item.name = item.name.encode('utf-8').decode('unicode-escape')item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')编写插件2-添加命令行参数# 定义命令行参数的hook函数def pytest_addoption(parser):# group 将下面所有的option都展示在这个group组下mygroup = parser.getgroup('hogwarts')mygroup.addoption('--env',# 注册一个命令行选项default='test',# 参数的默认值dest='env',# 存储的变量 , 为属性命令,可以使用option对象访问到这个值help='set your run env')# 帮助提示,参数的描述信息@pytest.fixture(scope='session')def cmd_option(request):# request获取命令行的参数,config拿到pytest相关配置,getoption拿到命令行参数return request.config.getoption('--env')
Pytest进阶使用

文章插图
打包发布打包项目构成:
  • 源码包
  • setup.py
  • 测试包
from setuptools import setup, find_packagessetup(name='pytest_encode',url='',version='1.0',# 版本author='joker',# 作者author_email='',# 邮箱description='set your encoding and logger',# 描述用法long_description='Show Chinese for you mark.parametrize().',# 完整描述classifiers=[# 分类索引,pip所属包的分类,方便在pip官网中搜索'Framework :: Pytest','Programming Language :: Python','Topic :: Software Development :: Testing','Programming Language :: Python :: 3.8',],license='proprietary',# 程序授权信息packages=find_packages(),# 通过导入的方式发现当前项目下所有的包keywords=[# 便于pip进行分类'pytest', 'py.test', 'pytest_encode'],# 需要安装的依赖install_requires=['pytest'],# 入口模块,或者入口函数(最重要的)entry_points={'pytest11': ['pytest_encode = pytest_encode.main']},zip_safe=False# 针对win系统,不设置成false会出错)

推荐阅读