将文档字符串中的预期结果指定为十六进制? [英] Specify expected outcome in a docstring as hexadecimal?

查看:84
本文介绍了将文档字符串中的预期结果指定为十六进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在 docstring 中指定期望的整数结果十六进制表示法?

Is there a way to specify expected integer outcomes in a docstring in hex notation?

def identity(val):
    """
    >>> identity(243)
    243
    >>> identity(243)
    0xf3
    """
    return val

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Doctest无法解释十六进制表示法,从而导致失败:

Doctest doesn't interpret the hex notation, resulting in a failure:

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

我知道我可以搏击文档字符串:

I'm aware that I could wrestle the docstring:

def identity(val):
    """
    >>> hex(identity(243))
    '0xf3'
    """
    return val

但是让doctest理解字面整数似乎很自然以小数点后的8、16为底数.

But it'd seem natural to have doctest understand literal integers in bases 8, 16 next to decimal.

推荐答案

当然,您可以编写自己的

Sure, you can write your own OutputChecker class to handle numbers however you want:

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)

这篇关于将文档字符串中的预期结果指定为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆