7

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.

stefanbschneider
  • 5,460
  • 8
  • 50
  • 88

1 Answers1

12

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))
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 1
    I changed to `yield` and added `shutil.rmtree()`, but the "temporary" directory still exists after the tests finish. Either the `rmtree` call is never reached or it doesn't work. As in the tutorial, I use the `project_file` as an argument for one of my test functions. – stefanbschneider Jul 30 '18 at 12:34
  • 1
    Using `shutil.rmtree('data')` instead of `shutil.rmtree(my_tmpdir)` solved the problem. Once the answer is adjusted, I'll accept it. – stefanbschneider Jul 30 '18 at 13:24
  • Actually, `str(my_tmpdir)` also doesn't work. Only with `"data"` as parameter it did. – stefanbschneider Jul 30 '18 at 14:13
  • 1
    @CGFoX, if you are passing just the string `"data"` to rmtree, then something else is wrong with your code. How are you using the `project_file` fixture? – Stephen Rauch Jul 30 '18 at 14:13
  • You're right. I wasn't even properly using the tmpdir (which was created somewhere in my user's temp directory). Instead I was just creating a "data" directory indpendent of the tempdir_factory... – stefanbschneider Jul 30 '18 at 14:26