你只需要使用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.stderr
和sys.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)
也許你可以展示的單元測試代碼的例子,你想回到什麼? –
好吧,我編輯它,並添加了一個例子 – jononomo
我在Eclipse中使用Pydev插件,我使用Pyunittest和調試測試... –