Last active
August 29, 2024 17:19
-
-
Save odyniec/d4ea0959d4e0ba17a980 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
You should probably close
f
between writing and reading.with open(...
should serve you well here.