如何模拟像os.pathsep这样的Python系统属性



我正在尝试修改一个测试以同时处理Linux和Windows。正在测试的代码使用os.pathsep。示例:

def path_split(pth):
if os.pathsep in pth:
return pth.split(os.pathsep)
else:
return [pth]

如果我在Linux上使用冒号运行以下测试,它会起作用:

class PathsepTest(TestCase):
def test_path_split(self):
result = path_split("foo:bar")
assert result == ["foo", "bar"]

但是,如果我尝试模拟os.pathsep以返回Windows路径分隔符(;(

class PathsepTest(TestCase):
def test_path_split(self):
windows_pathsep = ";"
with patch.object(os, "pathsep", return_value=windows_pathsep):
result = path_split("foo;bar")
assert result == ["foo", "bar"]

失败

def path_split(pth):
>       if os.pathsep in pth:
E       TypeError: 'in <string>' requires string as left operand, not MagicMock

对于更简单的功能

def get_pathsep():
return os.pathsep

如果我进行,则相应的测试失败

def test_get_pathsep(self):
windows_pathsep = ";"
with patch.object(os, "pathsep", return_value=windows_pathsep):
result = get_pathsep()
assert result == windows_pathsep

但如果我做就通过了

assert result.return_value == windows_pathsep

欢迎提出任何建议。

mock.patch用另一个对象替换一个对象,默认情况下用MagicMock替换。

所以patch.object(os, "pathsep", return_value=":"),用MagicMock替换os.pathsep。然后return_value指定调用mock对象(即os.pathsep.__call__(时的行为

>>> with mock.patch("os.pathsep", return_value=";"):
...     print(os.pathsep())   # os.pathsep has been replaced by a callable
... 
;

但是os.pathsep不是一个可调用的对象,它是str。根据文档,您可以简单地用new参数替换原始对象:

>>> with mock.patch("os.pathsep", new=";"):
...     print(os.pathsep)
... 
;

最新更新