Skip to content

Instantly share code, notes, and snippets.

@odyniec
Last active August 29, 2024 17:19
An example Python unittest test case that creates a temporary directory before a test is run and removes it when it's done.
import shutil, tempfile
from os import path
import unittest
class TestExample(unittest.TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def test_something(self):
# Create a file in the temporary directory
f = open(path.join(self.test_dir, 'test.txt'), 'w')
# Write something to it
f.write('The owls are not what they seem')
# Reopen the file and check if what we read back is the same
f = open(path.join(self.test_dir, 'test.txt'))
self.assertEqual(f.read(), 'The owls are not what they seem')
if __name__ == '__main__':
unittest.main
@bregman-arie
Copy link

unittest.main()*

@mcouthon
Copy link

You should probably close f between writing and reading.
with open(... should serve you well here.

@eamanu
Copy link

eamanu commented Mar 6, 2019

if you use context you can avoid close file. But for now, you must close

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment