AttributeError:“ Config”对象没有属性“ test_system”

时间:2019-08-27 20:33:56

标签: python pytest xdist

timestamp null,

所有测试在不使用“ -n”选项的情况下运行良好。我打印了config的属性,并且它确实包含test_system,我也不知道为什么它会失败。

1 个答案:

答案 0 :(得分:2)

使用xdist分发测试时,在主节点和工作节点之间共享数据的通常方法是实现pytest_configure_node钩子,然后以下列方式访问数据:

if hasattr(request.config, 'slaveinput'):
    ...  # we are in worker node
else:
    ...  # we are in master

以下是我尝试绑定到您发布的异常回溯的示例:

class TestSystem:
    def __init__(self):
        self.build_configuration = dict()


def pytest_configure(config):
    if hasattr(config, 'slaveinput'):  # slave
        return
    # we are on master node
    # create test system object, attach to config
    s = TestSystem()
    s.build_configuration['foo'] = 'bar'
    config.test_system = s


def pytest_configure_node(node):
    # this is the pendant of pytest_configure hook, but for worker nodes only
    # store serializable stuff from test system object in slaveinput
    node.slaveinput['test_system_serialized'] = node.config.test_system.build_configuration


def pytest_generate_tests(metafunc):
    if hasattr(metafunc.config, 'slaveinput'):  # we are in worker node
        # restore test system object using serialized data
        s = TestSystem()
        s.build_configuration = metafunc.config.slaveinput['test_system_serialized']
    else:  # master
        # simply get test system instance from config
        s = metafunc.config.test_system

    # generate tests    
    if 'test_system' in metafunc.fixturenames:
        metafunc.parametrize('test_system', [s])

请注意,您不能在主服务器和工作服务器之间共享TestSystem实例,而只能共享原始数据类型(字符串,数字,列表,字典等)。这就是为什么仅将build_configuration字典存储在slaveinput中,并且每个工作程序都从共享数据中重新创建自己的TestSystem对象的原因。

示例测试:

import time
import pytest


@pytest.mark.parametrize('n', range(1, 5))
def test_eggs(n, test_system):
    time.sleep(1)
    assert test_system.build_configuration['foo'] == 'bar'

依次运行测试会得出:

$ pytest -v
...
test_spam.py::test_eggs[test_system0-1] PASSED
test_spam.py::test_eggs[test_system0-2] PASSED
test_spam.py::test_eggs[test_system0-3] PASSED
test_spam.py::test_eggs[test_system0-4] PASSED

以分布式模式运行测试:

$ pytest -v -n4
...
scheduling tests via LoadScheduling

test_spam.py::test_eggs[test_system0-1] 
test_spam.py::test_eggs[test_system0-2] 
test_spam.py::test_eggs[test_system0-4] 
test_spam.py::test_eggs[test_system0-3] 
[gw1] [ 25%] PASSED test_spam.py::test_eggs[test_system0-2] 
[gw2] [ 50%] PASSED test_spam.py::test_eggs[test_system0-3] 
[gw0] [ 75%] PASSED test_spam.py::test_eggs[test_system0-1] 
[gw3] [100%] PASSED test_spam.py::test_eggs[test_system0-4]