如何使用pdb调试器调试单元测试?

时间:2014-03-14 17:56:02

标签: python python-unittest pudb

我在尝试通过pudb debugger调试某些单元测试时遇到了一些麻烦。

使用python进行的测试运行良好,但我没有运气使用pudb运行它们。

我解决了问题,转到以下示例代码:

class Math:
    def pow(self, x, y):
        return x ** y

import unittest

class MathTest(unittest.TestCase):
    def testPow23(self):
        self.assertEquals(8, Math().pow(2, 3))
    def testPow24(self):
        self.assertEquals(16, Math().pow(2, 4))

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

测试运行良好:

$ python amodule.py 
.
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

但如果在pudb中运行,它会给我输出结果:

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

我尝试使用pudb amodule.pypython -m pudb.run amodule.py运行,但它没有任何区别 - 没有测试以一种或另一种方式运行。

我是否应该使用pudb进行不同的调试单元测试?

3 个答案:

答案 0 :(得分:9)

尝试在代码中的有用行上放置断点:

from pudb import set_trace; set_trace()

您尝试启动它的方式可能会干扰测试发现和/或不会使用__name__ '__main__'运行您的脚本。

答案 1 :(得分:2)

您可以通过以下方式更轻松地设置断点:

import pudb; pu.db

答案 2 :(得分:1)

由于这是一个很受欢迎的问题,我觉得我还应该提一下,大多数测试运行工具都需要你传入一个开关,以防止它捕获标准输出和输入(通常是-s)。 / p>

因此,请记住在使用Pytest时运行pytest -s,对于Nose运行nosetests -s,对于Django测试运行python manage.py test -s,或者查看测试运行工具的文档。