2
\$\begingroup\$

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?
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Why do you create named temporary files within your named temporary directory? The whole directory (including its contents) will be deleted as soon as the context ends.

So, just create a fixed (or random if you want to) number of zero byte files in that directory:

import os
import tempfile

...

with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary directory\n', tmpdirname)
    n = 34 # create 34 files
    for i in range(n):
        open(os.path.join(tmpdirname, str(i)), "w").close() # create the empty file
    print('created', n, 'files')
    self.assertEqual(n, f.count_files(tmpdirname))
\$\endgroup\$
1
  • 1
    \$\begingroup\$ this is perfect thank you. I think the problem owed to my lack of knowledge with the tempfile module. I was using the Path module before, so I was hung up on deleting the files before you were able to delete the directory. Thanks again! \$\endgroup\$
    – BigAl1992
    Nov 1, 2018 at 3:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.