- Published: September 2, 2018
Some Python projects need to work with files and directories, to check if the contents are written to a file or that the contents are written as expected.
To easily unit test creating, deleting and checking their contents, we can create a temporal folder that will contain all of the above generated files and work with them.
In our test code, we use the
This module creates temporary files and directories.
We can choose between high-level and lower-level interfaces depending on the type of test we want, main difference is that the former one handles all directories and its content removal as soon as the completion of the context or the destruction of the temporary directory object.
tempfile.TemporaryDirectory to create a temporal directory (or
tempfile.TemporaryFile for files)
before each method:
import tempfile class TestExample(unittest.TestCase): def setUp(self): # Create a temporary directory self.test_dir = tempfile.TemporaryFile() def tearDown(self): # Close the file, the directory will be removed after the test self.test_dir.close() if __name__ == '__main__': unittest.main()
Using in single test
Create a temporary directory using the context manager:
import tempfile class TestExample(unittest.TestCase): def test_example(self): with tempfile.TemporaryDirectory() as tmpdirname: print('created temporary directory', tmpdirname) if __name__ == '__main__': unittest.main()