简体   繁体   English

蟒蛇。 Pytest夹具碰撞

[英]Python. Pytest fixture collision

I'm trying use pytest yield-fixture with the default scope multiple times in one test. 我正在尝试在一次测试中多次使用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

I have a collision. 我发生了碰撞。 The first fixture doesn't clean - temp_file_1 doesn't remove, while the second file removed well. 第一个夹具不清理 - temp_file_1没有删除,而第二个文件删除得很好。 Is is possible to use fixture many times correct? 有可能多次使用夹具正确吗?

PS: I know about tmpdir - standart pytest fixture. PS:我知道tmpdir - standart pytest fixture。 This is just an example. 这只是一个例子。

Fixture yeilds a function in this example. Fixture在这个例子中提供了一个函数。 I think that the straight way is to accumulate passed args: 我认为直接的方法是积累传递的args:

@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)

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

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