测试功能在单元测试结束时附加NONE

时间:2015-08-09 18:41:09

标签: python unit-testing python-3.x

我一直在研究一些代码来练习单元测试。原始文件应该在目录中获取所有文件名,并列出具有相同扩展名的文件数。当我使用unittest运行相同的函数时,测试会在最后添加None,从而破坏测试。

#!/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))

返回此输出:

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

和我的unittest代码:

#!/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()

返回此输出:

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

为什么在unittest输出结束时会有额外的None输出?

1 个答案:

答案 0 :(得分:0)

您的函数不使用return语句,因此Python返回None(默认值)。您正在打印该值。请注意,您的测试不会被它破坏,您的测试实际上没有测试任何东西,只运行代码。

只需删除print()来电:

def test_lookUp_text(self):
    FileHandling.lookUp(self.testdir, "*.*")

您应该考虑将您的功能更改为返回要打印的报告而不是直接打印,然后您可以更轻松地进行单元测试,从而产生关于正确输出的断言。

你还应该考虑学习unittest.mock library如何在这里帮助你;您可以模拟os.listdir()调用,这样您实际上就不必创建测试文件,而是将其留给您的模拟os.listdir()调用以返回预先确定的字符串列表。