2

我正在尝试调试一个使用 tox 进行单元测试的 python 代码库。由于弄清楚,其中一个失败的测试证明很困难,我想使用 pudb 来逐步执行代码。

乍一看,会想到刚才pip install pudb在单元测试代码中添加import pudband pudb.settrace()。但这会导致 ModuleNotFoundError:

>       import pudb
>E       ModuleNotFoundError: No module named 'pudb'
>tests/mytest.py:130: ModuleNotFoundError
> ERROR: InvocationError for command '/Users/me/myproject/.tox/py3/bin/pytest tests' (exited with code 1)

注意到 .tox 项目文件夹会让人意识到在 tox 中有一个 site-packages 文件夹,这是有道理的,因为 tox 的目的是管理不同 virtualenv 场景下的测试。这也意味着有一个 tox.ini 配置文件,其中的 deps 部分可能如下所示:

[tox]
envlist = lint, py3

[testenv]
deps =
    pytest
commands = pytest tests

添加pudb到 deps 列表应该可以解决 ModuleNotFoundError,但会导致另一个错误:

self = <_pytest.capture.DontReadFromInput object at 0x103bd2b00>

    def fileno(self):
>       raise UnsupportedOperation("redirected stdin is pseudofile, "
                                   "has no fileno()")
E       io.UnsupportedOperation: redirected stdin is pseudofile, has no fileno()

.tox/py3/lib/python3.6/site-packages/_pytest/capture.py:583: UnsupportedOperation

所以,我被困在这一点上。不能在 Tox 中使用 pudb 代替 pdb 吗?

4

2 回答 2

6

有一个名为的包pytest-pudb覆盖自动化测试环境(如 tox)中的 pudb 入口点,以成功跳转到调试器。

要使用它,只需让您的 tox.ini 文件在其 testenv 依赖项中同时包含pudbpytest-pudb条目,类似于以下内容:

[tox]
envlist = lint, py3

[testenv]
deps =
    pytest
    pudb
    pytest-pudb
commands = pytest tests
于 2018-05-18T21:52:27.200 回答
3

使用原始 PDB(不是 PUDB)也可以。至少它适用于 Django 和 Nose 测试人员。在不更改 tox.ini 的情况下,只需在需要的地方添加一个 pdb 断点,使用:

import pdb; pdb.set_trace()

然后,当它到达该断点时,您可以使用常规 PDB 命令:

  • w - 打印堆栈跟踪
  • s - 进入
  • n - 越过
  • c - 继续
  • p - 打印参数值
  • a - 当前函数的打印参数
于 2020-01-20T06:40:01.040 回答