以某种方式使用py.test时,我可以使用python调试器进行调试吗?

Joe*_*oel 64 python unit-testing pdb

我正在使用py.test对我的python程序进行单元测试.我希望用python调试器以正常的方式调试我的测试代码(我的意思是代码中的pdb.set_trace())但是我无法使它工作.

将pdb.set_trace()放入代码中不起作用(引发IOError:在捕获输出时从stdin读取).我也尝试使用选项--pdb运行py.test但是如果我想探索在断言之前发生的事情,那似乎并不起作用.当断言失败时它会中断,从该行继续前进意味着终止程序.

有没有人知道一种方法来调试,或者调试和py.test只是不想在一起?

hpk*_*k42 92

这很简单:assert 0在你的代码中放置一个你想要开始调试的地方并运行你的测试:

py.test --pdb 
Run Code Online (Sandbox Code Playgroud)

完了:)

或者,如果您使用的是pytest-2.0.1或更高版本,那么pytest.set_trace()您还可以在测试代码中的任何位置放置帮助程序.这是文档.在将您发送到pdb调试器命令行之前,它会在内部禁用捕获.

  • 嘿杰森 我刚刚添加了py.test.set_trace(),请参阅http://bitbucket.org/hpk42/py-trunk/changeset/1d7b0838917f,您可以安装开发版本,例如"pip install URL",其中URL是这里的zip文件:http://hudson.testrun.org/view/pytest/job/py-trunk-sdist/(抱歉,似乎StackOverflow严重截断了URL,因此无法粘贴完整的URL) (4认同)
  • [我可以使用ipdb而不是pdb吗?](http://stackoverflow.com/q/39162569/232794) (2认同)

Jas*_*mbs 35

我发现我可以在禁用捕获的情况下运行py.test,然后像往常一样使用pdb.set_trace().

> py.test --capture=no
============================= test session starts ==============================
platform linux2 -- Python 2.5.2 -- pytest-1.3.3
test path 1: project/lib/test/test_facet.py

project/lib/test/test_facet.py ...> /home/jaraco/projects/project/lib/functions.py(158)do_something()
-> code_about_to_run('')
(Pdb)
Run Code Online (Sandbox Code Playgroud)

  • 这正是我设置pdb(而不是--pdb)的方式.注意:您可以使用"-s"而不是"--capture = no" (3认同)

Rac*_*ach 18

最简单的方法是使用py.test机制来创建断点

http://pytest.org/latest/usage.html#setting-a-breakpoint-aka-set-trace

import pytest
def test_function():
    ...
    pytest.set_trace()    # invoke PDB debugger and tracing
Run Code Online (Sandbox Code Playgroud)

或者如果你想将pytest调试器作为一个单行程序,请将import pdb; pdb.set_trace()其更改为import pytest; pytest.set_trace()


Pet*_*ons 5

我不熟悉 py.test,但对于 unittest,您可以执行以下操作。也许 py.test 是类似的:

在您的测试模块(mytestmodule.py)中:

if __name__ == "__main__":
    unittest.main(module="mytestmodule")
Run Code Online (Sandbox Code Playgroud)

然后运行测试

python -m pdb mytestmodule.py
Run Code Online (Sandbox Code Playgroud)

您将获得一个交互式 pdb shell。

查看文档,看起来 py.test 有一个--pdb命令行选项:

https://docs.pytest.org/en/7.2.x/reference/reference.html#command-line-flags

  • 这不是 py.test 的工作原理。py.test 的小但有效的测试代码: def test_arithmetic: assert 2+2==4 这足以进行单元测试。没有“main”例程,只是一个以“test_”开头的函数。如果使用普通 python 运行它,它只会定义 test_arithmetic,而不运行它。但是 py.test 找到以 test_ 开头的函数并为我运行它们,处理失败的断言等。 (2认同)

GSP*_*GSP 5

与 Peter Lyon 的答案类似,但使用 pytest 所需的确切代码,您可以将以下内容添加到 pytest 模块 (my_test_module.py) 的底部:

if __name__ == "__main__":
    pytest.main(["my_test_module.py", "-s"])
Run Code Online (Sandbox Code Playgroud)

然后您可以从命令行调用调试器:

pdb3 my_test_module.py
Run Code Online (Sandbox Code Playgroud)

繁荣。您位于调试器中并且能够输入调试器命令。此方法使您的测试代码不会充斥着 set_trace() 调用,并且将“正常”在 pytest 中运行。