2013-01-09 57 views
1

我有一些運行一堆測試的unittest代碼。以前,當每次測試運行時,一些信息會打印到stdout。如果測試失敗,這些信息將大大有助於調試。現在我想編寫一個更復雜的程序來調用unittest並以編程方式捕獲測試結果。看起來unittest提供了一個名爲TestResult的對象,它意味着包含測試的輸出。它包含所有錯誤的列表,所有失敗的列表等。我還想將我的調試輸出添加到此對象,以便稍後以編程方式訪問它。這可能嗎?Python單元測試 - 如何將調試信息添加到TestResult對象?

編輯:下面是一個例子:

import unittest2 

class DemoTest(unittest2.TestCase): 
    def test_one(self): 
     print "'grimelsome' attribute of 'smoxy' was set to 'blimpy'" 
     self.assertTrue(True) 

    def test_two(self): 
     print "'smithereen' attribute of 'brouhaha' was set to 'False'" 
     self.assertTrue(True) 

if __name__ == '__main__': 
    suite = unittest2.TestLoader().loadTestsFromTestCase(DemoTest) 
    result = unittest2.TextTestRunner(verbosity=2).run(suite) 

    # this is what I'd like to be able to do: 
    for fail in result.failures: 
     print what_would_have_gone_to_stdout 
+0

也許你可以展示的單元測試代碼的例子,你想回到什麼? –

+0

好吧,我編輯它,並添加了一個例子 – jononomo

+0

我在Eclipse中使用Pydev插件,我使用Pyunittest和調試測試... –

回答

0

你只需要使用TextTestRunner緩衝選項:

import unittest2 

class DemoTest(unittest2.TestCase): 
    def test_one(self): 
     print "'grimelsome' attribute of 'smoxy' was set to 'blimpy'" 
     self.assertTrue(True) 

    def test_two(self): 
     print "'smithereen' attribute of 'brouhaha' was set to 'False'" 
     self.assertTrue(False) 

if __name__ == '__main__': 
    suite = unittest2.TestLoader().loadTestsFromTestCase(DemoTest) 
    result = unittest2.TextTestRunner(verbosity=2, buffer=True).run(suite) 

每個測試,TextTestResult,由運動員使用之前,將取代sys.stderrsys.stdout有自己的流,只有在測試失敗或丟棄時纔將內容發送到原始流。

請注意,由於假冒sys.std*流在每次測試後發生更改,如果您想要對日誌輸出執行相同的操作,則必須在sys.sdt *流被替換之前添加日誌處理程序,測試或實施你自己的處理程序。

下面是一個例子繼承logging.StreamHandler

import logging 
import sys 
import unittest2 


class DemoTest(unittest2.TestCase): 
    logger = logging.getLogger('DemoTest') 

    def setUp(self): 
     self.logger.debug("setting up stuff and logging it...") 

    def teardown(self): 
     self.logger.debug("You won't see me") 
     print "me neither" 

    def test_one(self): 
     self.logger.debug("'grimelsome' attribute of 'smoxy' was set to 'blimpy'") 
     self.assertTrue(True) 

    def test_two(self): 
     self.logger.debug("'smithereen' attribute of 'brouhaha' was set to 'False'") 
     self.assertTrue(False) 


class TestHandler(logging.StreamHandler): 

    def __init__(self): 
     logging.Handler.__init__(self) 

    @property 
    def stream(self): 
     """Use which ever stream sys.stderr is referencing.""" 
     return sys.stderr 


if __name__ == '__main__': 
    formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') 
    logger_handler = TestHandler() 
    logger_handler.setFormatter(formatter) 
    logger = logging.getLogger() 
    logger.setLevel(logging.DEBUG) 
    logger.addHandler(logger_handler) 

    suite = unittest2.TestLoader().loadTestsFromTestCase(DemoTest) 
    result = unittest2.TextTestRunner(
     verbosity=2, buffer=True, resultclass=TestResult 
    ).run(suite)