I've been working on some code to practice unit testing. The original is supposed to get all file names in a directory, and list the number of files with the same extension. When I run the same function using unittest, the test appends a None
at the end, breaking the test.
#!/usr/local/bin/python3
import os
from glob import glob
from collections import Counter
directory = os.getcwd()
filetype = "*.*"
def lookUp(directory, filetype):
"""Returns filename in the current directory"""
files = [os.path.basename(i) for i in
glob(os.path.join(directory,filetype))]
countExt = Counter([os.path.splitext(i)[1] for i in files])
for i in countExt:
print("There are %d file(s) with the %s extension" %
(countExt[i], i))
returns this output:
There are 3 file(s) with the .html extension
There are 1 file(s) with the .txt extension
There are 2 file(s) with the .py extension
There are 3 file(s) with the .doc extension
and my unittest code:
#!/usr/local/bin/python3
import unittest
import FileHandling
import os
import tempfile
from glob import glob
class TestFileHandling(unittest.TestCase): #Defines TestHandling class
def setUp(self): # define seUp function
self.testdir = os.getcwd()
#self.testdir = tempfile.mkdtemp("testdir") # creates a test directory
os.chdir(self.testdir) # changes to test directory
self.file_names = ["file1.txt", "file1.doc", "file2.doc", "file3.doc", "file1.html", "file2.html", "file3.html"] # name seven filenames
for fn in self.file_names: # creates files
joinedfile = os.path.join(self.testdir, fn) #joins the filename with the temp directory name
f = open(joinedfile, "w") # create the file
f.close() # close the file from writing
def test_lookUp_text(self): # test function for lookUp
print(FileHandling.lookUp(self.testdir, "*.*"))
#print(os.getcwd())
#self.assertEqual(files, expected,)
def tearDown(self):
for fn in self.file_names:
os.remove(joinedfile)
if __name__ == "__main__":
unittest.main()
returns this output:
There are 2 file(s) with the .py extension
There are 3 file(s) with the .doc extension
There are 1 file(s) with the .txt extension
There are 3 file(s) with the .html extension
None
.
----------------------------------------------------------------------
Ran 1 test in 0.016s
OK
Why is there an additional None
output at the end of the unittest output?