2012-09-20 158 views
0

我有一個項目,我需要編寫一個模塊,其中包含一個函數來檢查當前工作目錄的內容並打印出每個擴展名有多少文件的計數(「.txt 「,」.doc「等)用於測試文件夾內容的Python單元測試

然後,我需要編寫一個單獨的模塊,通過測試來驗證該函數是否提供了正確的結果。

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 

這是測試:

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() 

我堅持,我需要一些幫助。我得到一個assertEqual錯誤。

在此先感謝。

+0

您的代碼中列出了當前目錄的內容? – ecatmur

回答

1

您正在收到assertEqual錯誤,因爲examdir.extensions2expected不一樣,應該是您的第一個線索。嘗試在斷言調用之前打印出兩者的值以驗證這一點。

二,我假設你在這裏列出的第一個文件叫做examine_directory?看看那個文件,我看到extensions2被初始化爲一個空的字典{}。該檢查函數返回一個本地變量稱爲extensions2的價值,但:

  1. 它不把它分配給您的全局字典(我認爲這是你期待的 行爲)
  2. 檢查()不沒有從您的 測試腳本中調用