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调试器命令行之前,它会在内部禁用捕获.
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)
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()
我不熟悉 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
与 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 中运行。