gpt4 book ai didi

python - 如何处理 python 的 doctest 中的变量错误?

转载 作者:行者123 更新时间:2023-11-28 20:33:00 28 4
gpt4 key购买 nike

我有一个 doctest,它期望在找不到文件时出现 IOError。

>>> configParser('conffig.ini') # should not exist
Traceback (most recent call last):
...
IOError: No such file: /homes/ndeklein/workspace/MS/PyMS/conffig.ini

但是,如果我想从另一台电脑上测试它,或者其他人想测试它,路径不会是/homes/ndeklein/workspace/MS/PyMS/。我想做

>>> configParser('conffig.ini') # should not exist
Traceback (most recent call last):
...
IOError: No such file: os.path.abspath(conffig.ini)

但是因为它在文档字符串中,所以它看到 os.path.abspath( 作为结果的一部分。

如何生成docstring测试变量的结果?

最佳答案

您真的需要匹配路径名吗?如果不是,则只需使用省略号跳过输出的那部分:

>>> configParser('conffig.ini') # should not exist
Traceback (most recent call last):
...
IOError: No such file: ...

如果这样做,则需要捕获错误并手动测试值。像这样的东西:

>>> try:
... configParser('conffig.ini') # should not exist
... except IOError as e:
... print('ok' if str(e).endswith(os.path.abspath('conffig.ini')) else 'fail')
ok

关于python - 如何处理 python 的 doctest 中的变量错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9567437/

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