如何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

