澄清
Doctests 因其简单性而具有吸引力,但这是一种误导性的简单性。您希望测试行代表一个表达式, doctest 将根据最后一个表达式的结果进行评估,但事实并非如此;它实际上只是做一个简单的基本字符串比较。
#doctesttest.py
"""
>>> "test"
"test"
python -m doctest doctesttest.py
给予
...
Expected:
"test"
Got:
'test'
虽然 - 在 python 术语中 - "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”中的“\”会被转换成“\”。
我们正在寻找一个简单的字符串匹配,所以我们需要寻找一个容易匹配的结果string。你不关心分隔符,所以要么消除它,要么替换它,或者围绕它进行测试:
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)