我知道如何使用# doctest: +SKIP
跳过doctest,但我无法根据运行时条件弄清楚如何跳过测试有时。例如:
>>> if os.path.isfile("foo"):
... open("foo").readlines()
... else:
... pass # doctest: +SKIP
['hello', 'world']
这就是我想要做的事情。我也接受运行测试的解决方案,但如果条件不满足,则将预期结果更改为带有回溯的异常(即无条件地运行测试但修改预期结果)。
答案 0 :(得分:4)
如果您不想测试输出,则可以返回一个特殊值。让我们将_skip
称为这个特殊值:
_skip
,那么无论预期如何,测试都是成功的您需要自定义OutputChecker
:
_skip = object()
COND_SKIP = doctest.register_optionflag('COND_SKIP')
class CondSkipChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
if optionflags & COND_SKIP and got.strip() == str(_skip):
return True
else:
return super(CondSkipChecker, self).check_output(want, got, optionflags)
这是一个概念证明(doctest API有点麻烦:一个人喜欢将testmod̀
与checker
参数一起使用)
"""
>>> 1 if True else _skip
2
>>> 1 if False else _skip
2
>>> 1 if True else _skip # doctest: +COND_SKIP
2
>>> 1 if False else _skip # doctest: +COND_SKIP
2
"""
import doctest, sys
_skip = object()
COND_SKIP = doctest.register_optionflag('COND_SKIP')
class CondSkipChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
if optionflags & COND_SKIP and got.strip() == str(_skip):
return True
else:
return super(CondSkipChecker, self).check_output(want, got, optionflags)
finder = doctest.DocTestFinder()
runner = doctest.DocTestRunner(CondSkipChecker())
m = sys.modules.get('__main__')
for test in finder.find(m, m.__name__):
runner.run(test)
print(runner.summarize())
输出:
**********************************************************************
File "temp.py", line 2, in __main__
Failed example:
1 if True else _skip
Expected:
2
Got:
1
**********************************************************************
File "temp.py", line 4, in __main__
Failed example:
1 if False else _skip
Expected:
2
Got:
<object object at 0x0033B8A8>
**********************************************************************
File "temp.py", line 6, in __main__
Failed example:
1 if True else _skip # doctest: +COND_SKIP
Expected:
2
Got:
1
**********************************************************************
1 items had failures:
3 of 4 in __main__
***Test Failed*** 3 failures.
TestResults(failed=3, attempted=4)
两个没有doctest批注的测试均按预期失败。注意:如果使用_skip
且没有COND_SKIP
标志,则可以轻松添加警告。
第三个测试失败(获得了1
与预期的2
),但是第四个测试却成功了(获得了̀ {_skip
+ COND_SKIP
,一切正常。