简体   繁体   English

如何在测试函数之外访问 Pytest 项目

[英]How to access Pytest item outside a test function

I want to retrive pytest current running test item and then append my function running data into item.user_properties .我想检索 pytest 当前正在运行的测试项目,然后将我的函数运行数据附加到item.user_properties中。

I tried to create dummy plugin and impl pytest_runtest_protocol , update running item in side the hook, then access item from plugin from _pytest.config import get_plugin_manager , plugin_manager.get_plugin('dummy').current_running_item but it does not work, get_plugin('dummy') return None我尝试创建dummy插件并实现pytest_runtest_protocol ,更新钩子中的运行项目,然后从插件访问项目from _pytest.config import get_plugin_managerplugin_manager.get_plugin('dummy').current_running_item但它不起作用, get_plugin('dummy')返回None

How can I achive this or is there a better way?我怎样才能做到这一点,或者有更好的方法吗?

# my_package/utl.py
from _pytest.config import get_plugin_manager
def my_requester(url):
    ...
    ...
    manager = get_plugin_manager()
    dummy = manager.get_plugin('dummy')
    item = dummy.current_item
    item.user_properties.append(('requested_url',url))

# conftest.py
import pytest
class Dummy:
    def __init__():
        self.current_item = None
    def pytest_runtest_protocol(self, item, nextitem):
        self.current_item = item

def pytest_configure(config):
    dummy_plugin = Dummy()
    config.pluginmanager.register(dummy_plugin,'dummy')
      
# test_demo.py
import pytest
from my_package.utl import my_requester


def test_a():
    ...
    my_requester('xxxx')

def test_b():
    ...
    my_requester('yyy')

找到了一个解决方案,只需使用单例模式,将测试项设置为单例对象属性,并将函数运行数据附加到该属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM