2012-07-25 32 views
16

我想用cProfile模塊來分析我的單元測試。但是,當我運行爲什麼cProfile模塊不能使用unittest?

python -mcProfile mytest.py 

我得到'冉0測試在0.000s'。這裏是mytest.py的源代碼

import unittest 

class TestBasic(unittest.TestCase): 
    def testFoo(self): 
     assert True == True 

if __name__ == '__main__': 
    unittest.main() 

我已經測試過其他更復雜的unittests以及。如果我用cProfile運行它,總是得到'Ran 0 tests'。請幫忙。

更新:我的操作系統是帶有內置python 2.7的MacOS 10.7。相同的代碼在Ubuntu上正常工作。

+0

適用於我在Ubuntu下 - python2.6/2.7 :)你有沒有試過'Profile'模塊? – 2012-07-25 08:14:11

+1

謝謝,朱利安。只是在Ubuntu上測試過,它工作。看起來像是一個平臺特定的問題。它不適用於內置python 2.7的MacOS 10.7。 – 2012-07-25 09:24:28

+0

我想你從來沒有找到一種方法使它在Mac OS X上工作? – jgritty 2013-01-10 06:26:22

回答

8

您必須初始化測試的構造函數的cProfiler,並在析構函數中使用的配置文件數據 - 我使用它像:

from pstats import Stats 
import unittest 

class TestSplayTree(unittest.TestCase): 
    """a simple test""" 

def setUp(self): 
    """init each test""" 
    self.testtree = SplayTree (1000000) 
    self.pr = cProfile.Profile() 
    self.pr.enable() 
    print "\n<<<---" 

def tearDown(self): 
    """finish any test""" 
    p = Stats (self.pr) 
    p.strip_dirs() 
    p.sort_stats ('cumtime') 
    p.print_stats() 
    print "\n--->>>" 
def xtest1 (self): 
    pass 

在的情況下測試等待輸入時,需要在該呼叫之前呼叫self.pr.disable(),然後重新啓用它。

+0

當我想使用瓶子測試客戶端時,仍然沒有爲我工作。 – 2014-04-08 12:20:02

+2

僅供參考,Stats類可通過'from pstats import Stats'獲得[ – 2015-06-12 17:37:10

+0

'self.testtree = SplayTree(1000000)'必需在這裏嗎? – industryworker3595112 2015-10-15 06:04:58