PyTest: Auto delete temporary directory created with tmpdir_factory

不想你离开。 提交于 2020-08-05 05:35:19

问题


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.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".

How can I automatically delete the temporary directory "data" after the pytest tests finish? The tmpdir argument creates temporary directory that is removed but it doesn't have a name and it only has function scope.


回答1:


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


来源:https://stackoverflow.com/questions/51593595/pytest-auto-delete-temporary-directory-created-with-tmpdir-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!