Pytest进阶使用( 三 )

  • 解决编码问题(中文的测试用例名称)
  • 自动添加标签
  • 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会出错)打包命令依赖包安装:
    • pip install setuptoolspython的包管理工具,负责安装和发布,尤其是安装拥有依赖关系的包
    • pip install wheel生成 *.whl格式的安装包,本质上也是一个压缩包
    打包命令:(切到setup.py所在的目录下执行)
    python setup.py sdist bdist_wheel
    dist目录下.whl的文件,可以通过pip install 下载
    发布命令
    • python3 -m pip install --user --upgrade twine## 安装twine工具
    • python3 -m twine upload --repository testpypi dist/*## 上传代码
    【Pytest进阶使用】

    经验总结扩展阅读