如何在 doctest 中插入尾随空格,以便即使实际结果和预期结果看起来相同也不会失败?

How to insert trailing spaces in a doctest, so that it doesn't fail even when actual and expected result look the same?

我正在尝试进行博士测试。 'Expected' 和 'Got' 结果相同,但我的 doctest 仍然失败。它失败了,因为打印输出中 x-axis y-axis 后有尾随空格,我没有包含在我的文档字符串中。我该如何包含它?当我手动插入空格并进行测试时,只要我将光标保持在那里,它 运行s 就会成功。

x轴y-axis______________________[光标在这里]

但是,如果我 运行 将光标放在其他地方进行测试,则尾随空格将被删除并且测试失败。

我知道这听起来很奇怪,但事实就是如此!

这是代码:

import pandas as pd
import doctest


class NewDataStructure(pd.DataFrame):
    """
    >>> arrays = [[1, 1, 2, 2], [10, 20, 10, 20]]
    >>> index = pd.MultiIndex.from_arrays(arrays, names=('x-axis', 'y-axis'))
    >>> data_input = {"Pressure (Pa)": [1+1j, 2+2j, 3+3j, 4+4j],
    ...               "Temperature": [1, 2, 3, 4]}
    >>> new_data_variable = NewDataStructure(data=data_input, index=index, title="Pressures and temperatures")
    >>> print new_data_variable
    New Data Structure Pressures and temperatures:
                   Pressure (Pa)  Temperature
    x-axis y-axis                            
    1      10             (1+1j)            1
           20             (2+2j)            2
    2      10             (3+3j)            3
           20             (4+4j)            4

    """
    def __init__(self, data, index, title):
        super(NewDataStructure, self).__init__(data=data, index=index)
        self.title = title

    def __str__(self):
        return "New Data Structure {}:\n{}".format(self.title, super(NewDataStructure, self).__str__())

doctest.testmod()

下面是我失败时的结果。即使在这里,您也应该能够 select x-axis y-axis 之后的区域并检测是否有尾随空格。

Failed example:
    print new_data_variable
Expected:
    New Data Structure Pressures and temperatures:
                   Pressure (Pa)  Temperature
    x-axis y-axis
    1      10             (1+1j)            1
           20             (2+2j)            2
    2      10             (3+3j)            3
           20             (4+4j)            4
Got:
    New Data Structure Pressures and temperatures:
                   Pressure (Pa)  Temperature
    x-axis y-axis                            
    1      10             (1+1j)            1
           20             (2+2j)            2
    2      10             (3+3j)            3
           20             (4+4j)            4

我找到了一个解决方案,使用 normalize white space flag

将它放在 doctest 中作为

    >>> print new_data_variable # doctest: +NORMALIZE_WHITESPACE

或调用 doctest 时

doctest.testmod( optionflags= doctest.NORMALIZE_WHITESPACE )