繁体   English   中英

为什么 cProfile 模块不适用于单元测试?

[英]Why cProfile module doesn't work with unittest?

我会使用 cProfile 模块来分析我的单元测试。 但是当我跑

python -mcProfile mytest.py

我得到了“在 0.000 秒内进行了 0 次测试”。 这是 mytest.py 的源代码

import unittest

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

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

我也测试过其他更复杂的单元测试。 如果我使用 cProfile 运行它,总是得到“运行 0 次测试”。 请帮忙。

更新:我的操作系统是带有内置 python 2.7 的 MacOS 10.7。 相同的代码在 ubuntu 上可以正常工作。

您必须在测试的构造函数中初始化 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() ,然后重新启用它。

如果您更喜欢pytest ,则方法名称会有所不同:

import cProfile
import time

class TestProfile:
    """ test to illustrate cProfile usage """

    def setup_class(self):
        self.pr = cProfile.Profile()
        self.pr.enable()

    def teardown_class(self):
        self.pr.disable()
        self.pr.print_stats(sort="tottime")

    def test_sleep(self):
        time.sleep(2)

指定模块明确地为我解决了这个问题。 也就是说,更换...

    unittest.main()

...(它试图自动发现它应该运行哪些测试)与...

    unittest.main(module='mytest')  # if in 'mytest.py', or as appropriate for your filename/module

...允许正确分析python -m cProfile mytest.py

我不确定为什么,但显式创建和运行测试套件似乎可行。 我添加了time.sleep(2)以在统计数据中显示确定的内容。

import time
import unittest

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

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestBasic)
    unittest.TextTestRunner(verbosity=2).run(suite)

在 bash 中运行,只保留前 10 行,我们可以看到{time.sleep}是运行时间最长的调用:

~ $ python -m cProfile -s tottime so.py | head -n10
testFoo (__main__.TestBasic) ... ok

----------------------------------------------------------------------
Ran 1 test in 2.003s

OK
         1084 function calls (1072 primitive calls) in 2.015 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    2.003    2.003    2.003    2.003 {time.sleep}
        1    0.002    0.002    0.003    0.003 case.py:1(<module>)
        1    0.002    0.002    0.003    0.003 collections.py:11(<module>)
        1    0.001    0.001    2.015    2.015 so.py:1(<module>)
        1    0.001    0.001    0.010    0.010 __init__.py:45(<module>)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM