【问题标题】:Python. Pytest fixture collisionPython。 Pytest 夹具碰撞
【发布时间】:2016-09-12 14:15:03
【问题描述】:

我正在尝试在一个测试中多次使用 pytest yield-fixture 和默认范围。

@pytest.fixture
def create_temp_file():
    nonlocal_maker_data = {'path': None}  # nonlocal for python2

    def maker(path, data):
        nonlocal_maker_data['path'] = path
        with open(path, 'wb') as out:
            out.write(data)
    try:
        yield maker
    finally:
        path = nonlocal_maker_data['path']
        if os.path.exists(path):
            os.remove(path)


def test_two_call_of_fixture(create_temp_file):
    create_temp_file('temp_file_1', data='data1')
    create_temp_file('temp_file_2', data='data2')

    with open('temp_file_1') as f:
        assert f.read() == 'data1'

    with open('temp_file_2') as f:
        assert f.read() == 'data2'

    assert False
    # temp_file_2 removed
    # temp_file_1 doesn't removed

我发生了碰撞。第一个夹具没有清理 - temp_file_1 没有删除,而第二个文件删除得很好。 是否可以多次正确使用夹具?

PS:我知道 tmpdir - 标准 pytest 夹具。这只是一个例子。

【问题讨论】:

  • 当然,在这个例子中可以将所有创建的文件累积到非本地列表中并删除它们。但我想了解最常见的方式。

标签: python pytest yield fixture


【解决方案1】:

Fixture 在这个例子中产生了一个函数。我认为直接的方法是累积传递的参数:

@pytest.fixture
def create_temp_file():
    nonlocal_maker_data = set()  # nonlocal for python2

    def maker(path, data):
        with open(path, 'wb') as out:
            out.write(data)
        nonlocal_maker_data.add(path)
    try:
        yield maker
    finally:
        for path in nonlocal_maker_data:
            if os.path.exists(path):
                os.remove(path)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多