简体   繁体   English

PyTest:自动删除使用tmpdir_factory创建的临时目录

[英]PyTest: Auto delete temporary directory created with tmpdir_factory

I'm trying to create a temporary directory with a specific name (eg, "data") for all tests within a module using PyTest's tmpdir_factory similar to the tutorial : 我正在尝试使用类似于教程的 PyTest的tmpdir_factory为模块内的所有测试创建一个具有特定名称(例如,“数据”)的临时目录:

@pytest.fixture(scope='module')
def project_file(self, tmpdir_factory):
    return tmpdir_factory.mktemp("data")

I'm using the temporary directory in some tests within the module successfully. 我在模块内的某些测试中成功使用了临时目录。 However, the directory still exists after running the tests and when I run them again, I get a failure because I cannot create a new temporary directory with name "data". 但是,该目录在运行测试后仍然存在,并且当我再次运行它们时,由于无法创建名称为“ data”的新临时目录而失败。

How can I automatically delete the temporary directory "data" after the pytest tests finish? pytest测试完成后,如何自动删除临时目录“ data”? The tmpdir argument creates temporary directory that is removed but it doesn't have a name and it only has function scope. tmpdir参数创建一个临时目录,该目录已删除,但没有名称,仅具有函数作用域。

You can cleanup after the fixture is done like: 夹具完成后,您可以进行清理,例如:

@pytest.fixture(scope='module')
def project_file(self, tmpdir_factory):
    my_tmpdir = tmpdir_factory.mktemp("data")
    yield my_tmpdir 
    shutil.rmtree(str(my_tmpdir))

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

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