将文档字符串中的预期结果指定为十六进制吗?

问题描述 投票:3回答:1

是否可以用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用小数点后的8、16为基数来理解literal integers似乎很自然。

python integer literals docstring doctest
1个回答
0
投票

当然,您可以根据需要编写自己的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)
© www.soinside.com 2019 - 2024. All rights reserved.