简介
pytest 给我们开放了大量的 hook 函数,可以编写插件。
pytest 插件类型
pytest 可以识别到三种插件:
内置插件:从 pytest 内部 _pytest 目录加载的插件
外部插件:通过 pip 安装的插件(比如: pip install pytest-ordering )。
conftest.py 插件:测试目录中的 conftest.py 加载
pytest hook 函数
pytest hook 链接: #hooks
pytest hook 函数也叫钩子函数,pytest 提供了大量的钩子函数,可以在用例的不同生命周期自动调用。 比如,在测试用例收集阶段,可利用 hook 函数修改测试用例名称的编码。
PYTEST 改写用例名称编码的插件
通常我们会把 hook 函数编写在项目的 conftest.py 文件中。
def pytest_collection_modifyitems(
session: "Session", config: "Config", items: List["Item"]
) -> None:
for item in items:
item.name = item.name.encode('utf-8').decode('unicode-escape')
item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')
创建测试用例:
@pytest.mark.parametrize("name",["哈利","赫敏"])
def test_encode(name):
print(name)
运行结果:
...
test_demo.py::test_encode[赫敏] 赫敏
PASSED
test_demo.py::test_encode[哈利] 哈利
PASSED
...
运行时,pytest 会优先加载 conftest.py 文件,然后再执行测试用例,这个 hook 函数 pytest_collection_modifyitems 是负责修改收集上来的测试用例的,也就是我们可以将收集上来的 测试用例重新改写它的编码规范,当然也可以修改它的执行顺序。下面我们来看一下 pytest 提供了哪些 hook 函数。
PYTEST HOOK 函数执行顺序
pytest 提供了大量的 hook 函数,执行过程中几乎所有的行为都是可以定制的。那么,pytest 可以改写哪 些行为呢? 文字版 pytest hook 执行顺序:
root
└── pytest_cmdline_main
├── pytest_plugin_registered
├── pytest_configure
│ └── pytest_plugin_registered
├── pytest_sessionstart
│ ├── pytest_plugin_registered
│ └── pytest_report_header
├── pytest_collection
│ ├── pytest_collectstart
│ ├── pytest_make_collect_report
│ │ ├── pytest_collect_file
│ │ │ └── pytest_pycollect_makemodule
│ │ └── pytest_pycollect_makeitem
│ │ └── pytest_generate_tests
│ │ └── pytest_make_parametrize_id
│ ├── pytest_collectreport
│ ├── pytest_itemcollected
│ ├── pytest_collection_modifyitems
│ └── pytest_collection_finish
│ └── pytest_report_collectionfinish
├── pytest_runtestloop
│ └── pytest_runtest_protocol
│ ├── pytest_runtest_logstart
│ ├── pytest_runtest_setup
│ │ └── pytest_fixture_setup
│ ├── pytest_runtest_makereport
│ ├── pytest_runtest_logreport
│ │ └── pytest_report_teststatus
│ ├── pytest_runtest_call
│ │ └── pytest_pyfunc_call
│ ├── pytest_runtest_teardown
│ │ └── pytest_fixture_post_finalizer
│ └── pytest_runtest_logfinish
├── pytest_sessionfinish
│ └── pytest_terminal_summary
└── pytest_unconfigure
可以利用 pytest hook 强大的功能开发出自己的插件。
pytest 编写插件
大家在运行测试用例的时候,可能会遇到编码的问题,比如路径里有中文,展示的时候,可能会出现乱 码。 测试代码如下:
@pytest.mark.parametrize("name",["哈利","赫敏"])
def test_encode(name):
print(name)
上面的代码实现了 pytest 参数化的功能,由于测试数据有中文,生成的结果会以 unicode 编码格式展示 出来,无法展示中文。命令行执行结果如下:
test_code.py::test_encode[u54c8u5229] 哈利
PASSED
test_code.py::test_encode[u8d6bu654f] 赫敏
PASSED
下面我们来开发一个小插件,插件实现的功能就是将上面的 [u54c8u5229] unicode 编码改成支持中 文的编码格式。 创建目录结构如下:
pytest-changcode
├── pytest_changecode
│ └── __init__.py
└── tests
└── test_code.py
创建插件包 pytest_changecode ,创建测试包 tests
在 tests/test_code.py 文件中添加测试代码,如下:
@pytest.mark.parametrize("name",["哈利","赫敏"])
def test_encode(name):
print(name)
在pytest_changecode/__init__.py 文件中添加改写编码的内容,代码如下:
def pytest_collection_modifyitems(items):
for item in items:
item.name = item.name.encode('utf-8').decode('unicode_escape')
item._nodeid = item._nodeid.encode('utf-8').decode('unicode_escape')
从源码 site_packages/_pytest/hookspec.py 中查看 pytest_collection_modifyitems hook 函 数的源码:
def pytest_collection_modifyitems(session, config, items):
""" called after collection has been performed, may filter or re-order
the items in-place.
:param _pytest.main.Session session: the pytest session object
:param _pytest.config.Config config: pytest config object
:param List[_pytest.nodes.Item] items: list of item objects
"""
是在用例收集完毕之后被调用,可以过滤或者调整测试用例执行顺序。 里面需要传递三个参数,其中 items 是测试的用例对象列表。可以通过遍历 items,然后对每个测试用例的名字重新编码,实现改写编 码的效果。
pytest 插件打包及发布
场景:一般来说,我们需要用到的功能 pytest 大部分都已经提供,即使 pytest 官网没有提供,第三方插 件的功能也很丰富了。但不同的项目,有特殊的项目需求,比如上面的编码问题,就没有解决这个问题 的第三方插件。或者项目里有个特殊的功能需求,需要在项目组内使用。就可以通过 pytest 打包的方 式,将这个特殊功能安装布署到其它环境下。
上面已经实现了重新编码的插件,下面我们将这个插件打包成一个可安装包,发布到 http://pypi.org/ 上面。 参照官方网址: 从官网说明可以看出, setup.py 文件是打包时必不可少的一部分。
SETUP.PY 介绍
setup.py 是 Python 的发布工具的增强工具(适用于 Python 2.3.5 以上的版本,64 位平台则适用于 Python 2.4 以上的版本),可以让程序员更方便的创建和发布 Python 包,特别是那些对其它包具有依赖 性的状况。
创建 setup.py 文件到项目 pytest-changecode 根目录下。
pytest-changcode
├── pytest_changecode
│ └── __init__.py
├── tests
│ └── test_code.py
└── setup.py
setup.py文件配置:
"""
__author__ = 'hogwarts'
"""
from setuptools import setup
setup(
name='pytest_changecode',
url='https://github.com/xxx/pytest-changecode',
version='1.0',
author="hogwarts",
author_email='xxxxxxxx@qq.com',
description='set your encoding',
long_description='Show Chinese for your mark.parametrize(). ',
classifiers=[# 分类索引 ,pip 对所属包的分类
'Framework :: Pytest',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3.8',
],
license='proprietary',
packages=['pytest_changecode'],
keywords=[
'pytest', 'py.test', 'pytest_changecode',
],
# 需要安装的依赖
install_requires=[
'pytest'
],
# 入口模块 或者入口函数
entry_points={
'pytest11': [
'pytest-changecode = pytest_changecode',
]
},
)
参数解析:
注意:如果您想让您的插件在外部可用,您可以为您的发行版定义一个所谓的入口点,以便 pytest 找到 您的插件模块。入口点是由 setuptools 提供的功能。pytest 查找 pytest11 入口点以发现其插件(冒 号后面是模块的名称,冒号前面是为模块起个别名)。
安装依赖库
打包需要依赖两个第三方库 setuptools 和 wheel 。
安装依赖库:
pip install setuptools
pip install wheel
解释:
setuptools 是 Python distutils 增强版的集合,它可以帮助我们更简单的创建和分发 Python 包,尤其是拥有依赖关系的包。
wheel 是新的 Python disribution ,用于替代 Python 传统的 .egg 文件。目前有超过一半的库 文件有对应的 wheel 文件。 *.whl 文件有一点与 *.egg 文件相似。实际上它们都是伪装的 *.zip 文件。如果你将 *.whl 文件名扩展改为 *.zip ,你就可以使用你的 zip 应用程序打开它,并且可 以查看它包含的文件夹和文件。
大包
命令行进入到 setup.py 文件路径下,执行打包命令:
python setup.py sdist bdist_wheel
执行完命令,会在当前项目下,生成三个文件夹 build , dist , pytest_change.egg-info 。
其中 dist 里有个 pytest_changecode-1.0-py3-none-any.whl 和 pytest_changecode-1.0.tar.gz ,其中 .whl 文件是安装包,可以使用 pip 安装到 python 环境 中。 .tar.gz 是源码包。
可以使用 python setup.py install 进行源码安装。
使用 pip install pytest_changecode-1.0-py3-none-any.whl 完成插件的安装。
这时使用 pytest 解释器再次运行 tests/test_code.py 文件,运行结果:
test_code.py::test_encode[哈利] 哈利
PASSED
test_code.py::test_encode[赫敏] 赫敏
PASSED
这时编码已经成功转成中文,说明我们的插件已经成功安装到 python 环境中。
发布
现在可以将你打包的插件上传到 上面,供别人下载使用了。
参照官方说明:
1、注册帐号
注册一个 pypi 的帐号
2、创建 TOKEN
去 #api-tokens 创建一个新的 API token。不要将其范 围限制到特定的项目,因为您正在创建一个新项目。
注意:
关闭页面前一定要复制这个 token,因为这个 token 只展示一次。
创建文件 $HOME/.pypirc
[testpypi]
username = __token__
password = pypi-AgENdGVzdC5weXBpLm9yZwIkMW
FhMzU5ZjctMzY0MC00Yzk1LWEyZWItM
jA1NDBlZmNiN2I4AAIleyJwZXJtaXNza
W9ucyI6ICJ1c2VyIiwgInZlcnNpb24iOi
AxfQAABiBD5Ky7MnQujzV-Ey8RIzJO
3OCopmxUqjNMJz5CNficQA
3、上传包到 PYPI 上
twine 是开发人员向 pypi 上传包的工具,安装 twine:
python3 -m pip install –user –upgrade twine
运行上传命令:
python3 -m twine upload –repository testpypi dist/*
系统将提示您输入用户名和密码。 对于用户名,请使用 __token__ 。 对于密码,使用令牌值,包括 pypi- 前缀。 命令完成后,您将看到类似以下内容的输出:
Uploading distributions to https://test.pypi.org/legacy/
Enter your username: [your username]
Enter your password:
Uploading pytest_changecode-1.0-py3-none-any.whl
100%|█████████████████████| 4.65k/4.65k [00:01<00:00, 2.88kB/s]
Uploading pytest_changecode-1.0.tar.gz
100%|█████████████████████| 4.25k/4.25k [00:01<00:00, 3.05kB/s]
上传后,你的包应该可以在 上查看,例如, 。
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: lzxmw777