Pytest 拆解夹具

Pytest Teardown Fixture

我需要删除一些为测试而创建的文件夹。 在主测试文件夹中,我创建了一个包含以下内容的文件 test_teardown.py

import shutil
import pytest


@pytest.fixture(scope="session")
def teardown():
    yield
    shutil.rmtree('tmp')

然而,tmp 文件夹在测试会话完成后并没有被删除。我是不是用错了夹具?

文件结构

+-- Project folder
|   +-- tests
|   |   +-- __init__.py
|   |   +-- test_teardown.py
|   |   +-- Unit
|   |   |   +-- __init__.py
|   |   |   +-- test_moretests.py    

感谢@MrBean Bremen

autouse=True 添加到包装器可确保它自动参与。 请确保您的 test_teardown.py 包含在使用的测试文件夹中。

包装器:

@pytest.fixture(scope='session', autouse=True)
def teardown():
    yield
    shutil.rmtree('tmp')