Python doctest预期以十六进制表示,不带自定义OutputChecker

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

我通常使用字节和十六进制,并且有一堆用于处理这些数字的辅助方法。

我正在将doctest添加到我的文档字符串中,以帮助确保它们起作用。请参见以下示例:

from typing import Tuple


def get_hi_low_bytes(hex_val: int) -> Tuple[int, int]:
    """Separate four hex chars into high and low bytes.

    For example: 0x0424 becomes 0x04, 0x24.

    Preconditions:
        hex_val <= 0xFFFF

    Examples:
        >>> get_hi_low_bytes(0x0424)
        (4, 36)

    How can I make output be:
        (0x04, 0x24)

    """
    return divmod(hex_val, 0x100)

当前,我无法弄清楚如何获得doctest来解释预期(输出)中的十六进制表示法。我通过doctest调用pytest integration

问题(pytest integration)正是我所寻找的。不幸的是,答案是创建一个自定义Specify expected outcome in a docstring as hexadecimal?,它基本上将doctest.OutputChecker转换为doctest.OutputChecker

[我想知道,是否有一些我可以传递给want的标志,使它能够解释十六进制表示法,而无需自定义int

python unit-testing pytest docstring doctest
1个回答
1
投票

doctest全部是关于再现Python交互式输出的。它具有一些配置选项,主要涉及可能难以匹配的输出,但是由于您无法将Python配置为始终输出十六进制值而不是数字的十进制值,因此doctest没有理由提供这种选项。

但是,您可以在doctest集成中使用自定义OutputChecker,如doctest中所述,例如,将其添加到OutputChecker中:

pytest.ini

Specify expected outcome in a docstring as hexadecimal?

conftest.py

conftest.py

test_doc.py

[pytest]
addopts = --doctest-modules

正在运行from doctest import OutputChecker from unittest import mock import pytest class HexOutputChecker(OutputChecker): def check_output(self, want, got, optionflags): if want.startswith('0x'): want_str = str(int(want, 16)) + '\n' return OutputChecker.check_output(self, want_str, got, optionflags) else: return OutputChecker.check_output(self, want, got, optionflags) @pytest.fixture(autouse=True) def hex_out(): with mock.patch('doctest.OutputChecker', HexOutputChecker): yield 给出:

def doc():
    """
    >>> 5 * 5
    0x19
    """
    pass
© www.soinside.com 2019 - 2024. All rights reserved.