Skip to content

Instantly share code, notes, and snippets.

@samaddico
Forked from odyniec/test_temp_directory.py
Created February 2, 2020 04:00
Show Gist options
  • Save samaddico/8b6304836b5da4db2ca39f446d15c6b9 to your computer and use it in GitHub Desktop.
Save samaddico/8b6304836b5da4db2ca39f446d15c6b9 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment