有没有办法让 doctest 以文件路径作为输出,无论它在什么操作系统上运行都会成功?

例如,在 Windows 上这将起作用:

r""" 
>>> import foo 
>>> relative_path = foo.getRelativePath() 
>>> print relative_path  
'bar\\foobar' 
""" 
if __name__ == '__main__': 
    from doctest import testmod 
    print testmod() 

但当然会在 Linux 上失败并产生类似于以下内容的错误:
Failed example: 
    print relative_path  
Expected: 
    'bar\\foobar' 
Got: 
    'bar/foobar' 

如何在任何操作系统上进行上述工作?

编辑

我知道我可以做这样的事情:
>>> relative_path == os.path.join('bar', 'foobar') 
True 

但我想知道是否有不同的更好的方法来做到这一点。

请您参考如下方法:

澄清

Doctests 因其简单而引人入胜,但它是一种误导性的简单。您希望测试行表示一个表达式,该表达式 doctest 将根据最后一个表达式的结果进行评估,但事实并非如此;它实际上只是做一个简单的、基本的字符串比较。

#doctesttest.py 
""" 
>>> "test" 
"test" 
 
python -m doctest doctesttest.py 


... 
Expected: 
    "test" 
Got: 
    'test' 

虽然 - 在 Pythonic 术语中 - "test" == 'test' ,甚至 "test" is 'test' , str(""" 'test' """)不匹配 str(""" "test" """) .

以这种意识武装...

解决方案

以下将在所有系统上失败:
def unique_paths(path_list): 
    """ Returns a list of normalized-unique paths based on path_list 
    >>> unique_paths(["first/path", ".\\first/path", "second/path"]) 
    ['first/path', 'second/path'] 
    """ 
 
    return set(os.path.normpath(p) for p in path_list) 
  • 我们得到了一个集合,而不是一个列表,
  • 将集合转换为列表需要提供一致的顺序,
  • doctest 使用 eval 因此“.\first”中的“\”将被转换为“\”。

  • 我们正在寻找一个简单的字符串匹配,所以我们需要寻找一个容易匹配的结果字符串。你不关心分隔符,所以要么消除它,要么替换它,或者围绕它进行测试:
    def unique_paths(path_list): 
        """ Returns a list of normalized-unique paths based on path_list 
        >>> paths = unique_paths(["first/path", ".\\\\first/path", "second/path"]) 
        >>> len(paths) 
        2 
        >>> [os.path.split(path) for path in sorted(list(paths))] 
        [('first', 'path'), ('second', 'path')] 
        # or heck, even 
        >>> sorted(list(paths[0])).replace('\\\\', '/') 
        'first/path' 
        """ 
        return set(os.path.normpath(p) for p in path_list) 
    


    评论关闭
    IT干货网

    微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!