我通常使用字节和十六进制,并且有一堆用于处理这些数字的辅助方法。
我正在将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
?
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