简体   繁体   中英

Python unittest for testing contents of a folder

I have a projects where I need to write a module containing a function to examine the contents of the current working directory and print out a count of how many files have each extension (".txt", ".doc", etc.)

Then I need to write a separate module to verify by testing that the function gives correct results.

import os
from collections import Counter

filenames = {}
extensions = []
file_counts = {}
extensions2 = {}

def examine(): 

    for filename in filenames:
        f = open(filename, "w")
        f.write("Some text\n")
        f.close()
        name, extension = filename.split('.')
        extensions.append(extension)

    extensions2 = dict(Counter(extensions))

    return extensions2

And this is the test:

import unittest
import tempfile
import os
import shutil
import examine_directory as examdir

class TestExamine(unittest.TestCase):
    def setUp(self):
        self.origdir = os.getcwd()
        self.dirname = tempfile.mkdtemp("testdir")
        os.chdir(self.dirname)

    examdir.filenames = {"this.txt", "that.txt", "the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}

def test_dirs(self):
    expected = {'pdf': 2, 'txt': 4, 'doc': 2}
    self.assertEqual(examdir.extensions2, expected, "Creation of files not possible")

def tearDown(self):
    os.chdir(self.origdir)
    shutil.rmtree(self.dirname) 

if __name__ == "__main__":
    unittest.main()

I'm stuck and I need some help. I'm getting an assertEqual error.

Thanks in advance.

You are getting the assertEqual error because examdir.extensions2 is not the same as expected , that should be your first clue. Try printing out the values of both before the assert call to verify this.

Second, I assume the first file you've listed here is called examine_directory ? Looking at that file, I see that extensions2 is initialized to an empty dictionary {} . The examine function returns the value of a local variable called extensions2 but:

  1. It does not assign it to your global dictionary (I think that's the behaviour you're expecting)
  2. examine() does not get called from your test script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM