I have a function that simply counts the number of files in a directory. To test this function I am using temporary files which are great in the respect that they are deleted upon creating. However, when I want to test my function to count multiple file it can become quite tedious. The below code works but you can probably guess there will be many lines in my test case if i wanted to count say 100 files.
#myfunction
class FileHandler:
def count_files(output_file_dir):
return len([f for f in listdir(output_file_dir) if isfile(join(output_file_dir, f))])
#test_myfunction
class FileHandlerTests(unittest.TestCase):
def test_if_files_exist_return_count_of_those_files(self):
f= FileHandler
#test with 1 file
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory\n', tmpdirname)
with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file:
print('created temporary file\n', test_file.name)
self.assertEqual(1,f.count_files(tmpdirname))
#test with 2 file
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory\n', tmpdirname)
with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file1:
print('created temporary file\n', test_file1.name)
with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file2:
print('created temporary file\n', test_file2.name)
self.assertEqual(2,f.count_files(tmpdirname))
#test with 34 file
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory\n', tmpdirname)
#loop to create 34 temp files?