gpt4 book ai didi

python - 为什么我的 doctest 测试用例放在单独的文件中时会失败?

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:02 25 4
gpt4 key购买 nike

我已经编写了一个 Python 模块,我正在使用 doctest 对其进行测试。我将测试嵌入到模块本身中,我正在调用 doctest

if __name__ == '__main__':
import doctest
doctest.testmod()

所有测试都通过(或失败)了我所期望的。这种方法的唯一问题是随着测试用例数量的增加,很难遵循代码。我读过 doctest 将允许您在单独的文件中进行测试,所以我正在尝试这样做。我发现当我将它们放入另一个文件时,在我的模块中运行良好的测试失败了。

这是一个示例测试文件。

>>> from modbusServer import ModbusServer
>>> s = ModbusServer('/dev/ttyUSB0')
>>> s.server # doctest: +ELLIPSIS
<modbus_tk.modbus_rtu.RtuServer instance at 0x...>

这是我运行该测试时发生的情况

test@testpc ~/code/newmodbus $ python -m doctest test.txt 
**********************************************************************
File "test.txt", line 3, in test.txt
Failed example:
s.server # doctest: +ELLIPSIS
Expected:
<modbus_tk.modbus_rtu.RtuServer instance at 0x...>
Got:
<modbus_tk.modbus_rtu.RtuServer instance at 0xa37adec>

当我从我的模块调用 doctest 时,这个测试工作正常,但现在失败了。关于我的测试文件中需要更改的内容有什么想法吗?

最佳答案

这还不是答案,但在评论中看起来会很难看。以下对我有用,你能在你的环境中检查一下吗:

(test)alko@work:~$ cd /tmp
(test)alko@work:/tmp$ cat test.txt
>>> from collections import deque
>>> deque().__init__ # doctest: +ELLIPSIS
<method-wrapper '__init__' of collections.deque object at 0x...>
(test)alko@work:/tmp$ python -m doctest test.txt
(test)alko@work:/tmp$

根据评论更新

由于此代码对您来说一切正常,因此您的 doctest 模块和 ELLIPSIS 指令都正常。正如您提到的文件源自 Windows,很明显,问题在于行尾。 Doctest 尝试匹配 0xa37adec>\r\n 与表达式 0x...>\n 使用 ... 变量 a37adec 部分,就在 > 符号之前,并且在回车符上失败。

您可能想要运行 fromdos适用于所有 Windows 源文件的实用程序。

或者你可以(我建议这样做)使用 git管理您的开发,它很乐意为您替换行尾。

关于python - 为什么我的 doctest 测试用例放在单独的文件中时会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19979535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com