1

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

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

4

1 回答 1

2

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

>>> 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
于 2012-03-05T14:06:32.347 回答