pytest:将测试变量或测试文件var传递给@ pytest.hookimpl(tryfirst = True,hookwrapper = True)

时间:2019-06-22 02:04:40

标签: python pytest

我正在为pytest开发多个自定义记录器,以改善测试结果在执行时的表示形式。目前,对于测试的每个迭代,我都能捕获测试名称,状态和参数化的Blob。为了能够按需使用自定义记录器,我希望能够针对每个测试文件,每个测试或从cli全局打开它。

目前,当我查看%timeit df.groupby('Item').sum() 中的数据时,似乎无法访问测试文件变量或测试变量。

是否可以将特定的变量从测试文件,特定的测试文件传递到测试文件或从cli全局传递到@pytest.hookimpl(tryfirst=True, hookwrapper=True),例如:@pytest.hookimpl(tryfirst=True, hookwrapper=True)

conftest.py

(log_suite or log_test or cli_log) and log_file

test_file.py

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    setattr(item, "rep_" + rep.when, rep) # for later use

    if rep.when == 'call':
        data = {'when': rep.when, 'outcome': rep.outcome, 'nodeid':rep.nodeid}

        # the reason loggin is here, as I would like to log every test permutation result as its happening.
        if (log_suite or log_test or cli_log) and log_file: # somehow to get those
            # log logic

1 个答案:

答案 0 :(得分:1)

您可以通过item.module访问钩子中的模块级变量,例如

def pytest_runtest_makereport(item, call):
    yield
    log_file = item.module.log_file
    log_suite = item.module.log_suite
    ...

等但是,您将无法从函数局部作用域访问变量,到那时它们已经不存在了。您可以自己将它们分配给模块,例如到pytest

def test_permutations(t_params):
    pytest.log_test = True

def pytest_runtest_makereport(item, call):
    yield
    log_test = pytest.log_test

或您当前的测试模块:

def test_permutations(t_params):
    globals()['log_test'] = True

def pytest_runtest_makereport(item, call):
    yield
    log_test = item.module.log_test

或使用全局定义的任何内容,例如缓存:

def test_permutations(t_params, request):
    log_test = True
    request.config.cache.set('log_test', log_test)

def pytest_runtest_makereport(item, call):
    yield
    log_test = item.session.config.cache.get('log_test', None)

顺便说一句,没有pytest_runtest_logger这样的钩子,请仔细检查该名称,否则测试将无法运行。这是reference of all hooks available

相关问题