简体   繁体   English

如何使用os.path编写跨平台单元测试?

[英]How to write cross-platform unit tests with os.path?

I want to write a simple unit test with os.path.basename 我想用os.path.basename写一个简单的单元测试

Example

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'

Problem 问题

Running on linux the second test (windows path) is failing. 在Linux上运行的第二个测试(Windows路径)失败。
I guess the first test will fail on windows. 我想第一次测试将在Windows上失败。
This actually makes pretty much sense since there are different os.path modules 实际上这是非常有意义的,因为存在不同的os.path模块

Python Documentation Python文档

Since different operating systems have different path name conventions, there are several versions of this module in the standard library. 由于不同的操作系统具有不同的路径名约定,因此标准库中有该模块的多个版本。

Question

Is there a way to import a specific version of os.path ? 有没有办法导入特定版本的os.path
I already tried to set sys.platform to win32 我已经尝试将sys.platform设置为win32

Of course I could check the current platform and just run one of both tests - but I was wondering if there is a way to run both tests. 当然,我可以检查当前平台并只运行两个测试之一,但是我想知道是否有一种方法可以运行两个测试。

You should always use / as the path separator. 您应该始终使用/作为路径分隔符。 Python will translate it to the correct separator for your platform. Python将其转换为适合您平台的正确分隔符。

\\ is used to start escape sequences. \\用于启动转义序列。 Using / will avoid having to use raw strings to disable \\ escape sequences (as in the second string in your post). 使用/可以避免必须使用原始字符串来禁用\\转义序列(如您帖子中的第二个字符串一样)。

Using \\ in raw strings may also cause os.path methods to behave oddly (and will only work on Windows platforms). 在原始字符串中使用\\可能还会导致os.path方法的行为异常(仅在Windows平台上有效)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM