如何编写跨平台单元测试操作系统路径?

2024-04-25 04:03:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用os.path.basename编写一个简单的单元测试

示例

def test(path):
    return os.path.basename(os.path.normpath(title))

...

result = test('/path/foo')
assert result == 'foo'

result = test(r'c:\Users\Foo\Documents\foo')
assert result == 'foo'

问题

在linux上运行第二个测试(windows路径)失败。
我想第一个测试在windows上会失败。
这实际上很有意义,因为存在不同的os.path模块

Python Documentation

Since different operating systems have different path name conventions, there are several versions of this module in the standard library.

问题

有没有方法可以导入os.path的特定版本?
我已经尝试将sys.platform设置为win32

当然,我可以检查当前的平台,只运行两个测试中的一个——但我想知道是否有一种方法可以同时运行这两个测试。在


Tags: path方法test示例returnfoooswindows
1条回答
网友
1楼 · 发布于 2024-04-25 04:03:18

您应该始终使用/作为路径分隔符。Python会将其转换为适合您平台的正确分隔符。在

\用于启动转义序列。使用/可以避免使用原始字符串来禁用\转义序列(如您文章中的第二个字符串所示)。在

在原始字符串中使用\也可能导致os.path方法的行为异常(并且只适用于Windows平台)。在

相关问题 更多 >