You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何Mock Python系统属性os.pathsep以实现跨平台测试?

Got it, let's break down what's going wrong here and how to fix it.

The Core Issue: Mocking Attributes vs. Callables

The problem comes down to how you're mocking os.pathsep. os.pathsep is a string attribute, not a callable function/method. When you use return_value in patch.object, you're treating it like a function that returns a value—but since it's an attribute, this replaces it with a MagicMock object instead of the actual string you want. That's why you get errors like TypeError: 'in <string>' requires string as left operand, not MagicMock.

Fix for Your path_split Test

Instead of return_value, use the new parameter to directly set the attribute value to your Windows path separator. Here's the corrected test:

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

Fix for Your get_pathsep Test

Same logic applies here—replace return_value with new to set the attribute directly. Now your original assertion will work without needing to access return_value on the result:

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

Extra Note: Alternative Mock Syntax

If you prefer, you can also use patch directly on the attribute path instead of patch.object, which works the same way:

with patch('os.pathsep', new=windows_pathsep):
    # Your test code here

Remember: return_value is for mocking what a callable returns. For attributes that hold static values, use new to replace the attribute itself.

内容的提问来源于stack exchange,提问作者Gord Thompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:33:11