有没有办法在 docstring 中指定预期的整数结果?用十六进制表示法?
def identity(val):
"""
>>> identity(243)
243
>>> identity(243)
0xf3
"""
return val
if __name__ == "__main__":
import doctest
doctest.testmod()
Doctest 不解释十六进制符号,导致失败:
**********************************************************************
File "hextest.py", line 5, in __main__.identity
Failed example:
identity(243)
Expected:
0xf3
Got:
243
**********************************************************************
1 items had failures:
1 of 2 in __main__.identity
***Test Failed*** 1 failures.
我知道我可以破解文档字符串:
def identity(val):
"""
>>> hex(identity(243))
'0xf3'
"""
return val
但是让 doctest 理解似乎很自然 literal integers以 8 为基数,小数点后为 16。
最佳答案
当然,你可以自己写OutputChecker类来处理你想要的数字:
def identity(val):
"""
>>> identity(243)
0xf3
>>> identity(243)
243
"""
return val
if __name__ == "__main__":
import doctest
OutputChecker = doctest.OutputChecker
class HexOutputChecker(OutputChecker):
def check_output(self, want, got, optionflags):
if want.startswith('0x'):
want_str = str(int(want, 16)) + '\n'
return super().check_output(want_str, got, optionflags)
else:
return super().check_output(want, got, optionflags)
doctest.OutputChecker = HexOutputChecker
doctest.testmod(verbose=True)
关于python - 将文档字符串中的预期结果指定为十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56392330/