为什么在调用pdb.set_trace()时此测试会崩溃?

时间:2016-02-03 20:16:44

标签: python python-3.x pdb

下面简单的单位测试。

如果我运行它(例如,python -m unittest module_name)而没有' test'作为一个论点,它通过。如果我用' test'作为一个参数,我得到" TypeError:内置操作的错误参数类型"。为什么呢?

from io import StringIO
import sys
from unittest import TestCase

class TestSimple(TestCase):
    def test_simple(self):
        old_stdout = sys.stdout
        buf = StringIO()
        try:
            sys.stdout = buf
            print('hi')
        finally:
            import pdb
            if 'test' in sys.argv:
                pdb.set_trace()
            sys.stdout = old_stdout

contextlib.redirect_stdout版本:

from contextlib import redirect_stdout
from io import StringIO
import pdb
import sys
from unittest import TestCase

class TestSimple(TestCase):
    def test_simple(self):
        buf = StringIO()
        with redirect_stdout(buf):
            print('hi')
            pdb.set_trace()
        print('finis')

提前致谢。

修改 原始程序在Debian和Windows 7中都在Python 3.4中进行了测试。

类似的东西(使用环境标志而不是命令行参数)似乎在Python 2中挂起,但按c允许它完成,所以我猜测它可能只是pdb的UI已经虽然一位同事在Mac OS上对3.4进行了测试并看到了#34;挂起并且#34;但是已经重定向了。但Python 3版本的行为初始描述(崩溃)。行为。

1 个答案:

答案 0 :(得分:4)

您需要pdb原始stdout

pdb.Pdb(stdout=sys.__stdout__).set_trace()
相关问题