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

blu*_*e13 17 python doctest code-coverage

我正在尝试做doctest.'预期'和'得到'结果是相同的,但我的doctest仍然失败.它失败了,因为x-axis y-axis在打印输出之后有一些尾随空格我没有包含在我的文档字符串中.我怎么包括它呢?当我手动插入空格并进行测试时,只要我将光标保持在那里,它就会成功运行.

x轴y轴______________________ [光标在这里]

但是,如果我使用我的光标在其他地方运行测试,则会删除尾随空格并且测试失败.

我知道这听起来很奇怪,但它就是它!

这是代码:

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()
Run Code Online (Sandbox Code Playgroud)

以下是失败时的结果.即使在这里你也应该能够选择之后的区域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
Run Code Online (Sandbox Code Playgroud)

Cop*_*eld 15

我找到了一个使用normalize white space标志的解决方案

把它放在doctest中

    >>> print new_data_variable # doctest: +NORMALIZE_WHITESPACE
Run Code Online (Sandbox Code Playgroud)

或者在调用doctest时

doctest.testmod( optionflags= doctest.NORMALIZE_WHITESPACE ) 
Run Code Online (Sandbox Code Playgroud)