文章目录
2.14 如何使用插件
pip install pytest-NAME
pip uninstall pytest-NAME
这里是一些流行插件的插件列表:
- pytest-django: 为django应用程序编写测试,使用小测试的集成
- pytest-twisted: 为应用程序编写测试,启动反应器和处理测试功能
- pytest-cov: 覆盖范围报告,与分布式测试相兼容
- pytest-xdist: 将测试分发到cpu和远程主机,在盒装模式下运行,允许避免分段故障,在循环失败模式下运行,自动对文件更改重新运行失败的测试
- pytest-instafail: 在进行测试运行时报告失败
- pytest-bdd: 要使用行为驱动的测试来编写测试
- pytest-timeout: 到基于函数标记或全局定义的超时测试
- pytest-pep8: 启用PEP8符合性检查
- pytest-flakes: 用 flakes 检查源代码。
2.14.1需要/加载插件 在测试模块或测试文件中
pytest_plugins = ("myapp.testsupport.myplugin",)
2.14.2查找哪些插件是活动的
如果你想知道哪些插件是活跃的,你可以键入 pytest --trace-config
2.14.3按名称停用/注销一个插件
pytest -p no:NAME
[pytest]
addopts = -p no:NAME
2.15 写插件【不深入】
2.16 写钩子函数
2.16.1 钩子功能的验证和执行
def pytest_collection_modifyitems(config, items):
# called after collection is completed
# you can modify the ``items`` list
...
2.16.2 第一个结果:在没有结果时候停止【不深入】
2.16.3 钩子包装器:围绕其他钩子执行
@pytest.hookimpl(hookwrapper=True)
def pytest_pyfunc_call(pyfuncitem):
do_something_before_next_hook_executes()
outcome = yield
# outcome.excinfo may be None or a (cls, val, tb) tuple
res = outcome.get_result() # will raise if outcome was exception
post_process_result(res)
outcome.force_result(new_res) # to override the return value to the plugin system
# 用例执行失败后,会把失败截图放到allure报告中
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""获取常规钩子方法的调用结果,返回一个result对象
:param item:测试用例对象
:param call:测试用例的测试步骤
执行完常规钩子函数返回的report报告有个属性叫report.when
先执行when=’setup’ 返回setup 的执行结果
然后执行when=’call’ 返回call 的执行结果
最后执行when=’teardown’返回teardown 的执行结果
:return:
"""
outcome = yield
report = outcome.get_result()
if report.when == "call" and report.failed:
mode = "a" if os.path.exists("failures") else "w" # 就是判断括号里的文件是否存在的意思,括号内的可以是文件路径。
with open("failures", mode) as f: # 打开这个文件
if "tmpir" in item.fixturenames:
extra = " (%s)" % item.funcargs["tmpdir"]
else:
extra = ""
f.write(report.nodeid + extra + "\n")
with allure.step('添加失败截图...'): # 添加1个测试测试步骤为了防截图
allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG) # 插入截图的详细信息
2.16.4 Hook函数示例 排序/调用
import pytest
# Plugin 1
@pytest.hookimpl(tryfirst=True)
def pytest_collection_modifyitems(items):
# 测试用例之前执行
...
# Plugin 2
@pytest.hookimpl(trylast=True)
def pytest_collection_modifyitems(items):
# 测试用例之后执行
...
# Plugin 3
@pytest.hookimpl(hookwrapper=True)
def pytest_collection_modifyitems(items):
# 在上面的 tryfirst 之前执行!
outcome = yield
# 在 all non-hookwrappers 执行后执行
2.16.5 声明新钩子
让我们假设这段代码在sample_hook.py模块中
def pytest_my_hook(config):
"""
Receives the pytest config and does things with it
"""
要用pytest注册钩子,它们需要在自己的模块或类中进行结构化。
然后,可以使用pytest_addhooks函数(该函数本身是一个由pytest公开的钩子)将这个类或模块传递给插件管理器。
def pytest_addhooks(pluginmanager):
""" This example assumes the hooks are grouped in the 'sample_hook' module. """
from my_app.tests import sample_hook
pluginmanager.add_hookspecs(sample_hook)