【问题标题】:How can I handle variable errors in python's doctest?如何处理 python doctest 中的变量错误?
【发布时间】:2012-03-05 13:27:39
【问题描述】:

我有一个文档测试,当找不到文件时会出现 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( 作为结果的一部分。

如何制作文档字符串测试变量的结果?

【问题讨论】:

  • 为什么要对磁盘上不存在的文件进行单元测试?你有什么理由怀疑文件系统的正确性吗?

标签: python testing doctest


【解决方案1】:

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

>>> 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多