我有以下方法:
class Controls:
def check_os(self) -> None:
if os.name != "posix":
raise OSError
我正在尝试像这样测试它:import pytest
@pytest.fixture
def name_mock(mocker):
return mocker.patch("path_to_module.controls.os.name", return_value="posix")
def test_check_os_fail(name_mock):
controls = Controls()
controls.check_os()
但是随后引发了以下错误:platform win32 -- Python 3.9.0, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
plugins: cov-2.11.1, mock-3.5.1
collected 57 items / 56 deselected / 1 selected
tests\test_controls.py
INTERNALERROR> Traceback (most recent call last):
...
NotImplementedError: cannot instantiate 'PosixPath' on your system
究竟发生了什么?
最佳答案
这里发生的是pytest
内部使用 pathlib.Path
对象,在初始化时要求 os.name
定义哪个 Path
使用的实现。 Path
有两个内部实现, PosixPath
和 WindowsPath
,仅在相应系统下可用。当您通过修补来伪造 Posix 系统时 os.name
,它尝试实例化一个 PosixPath
Windows 下 undefined object 。
在这种情况下你可以做的是包装 os.name
在您自己的功能中,例如就像是:
import os
def os_name():
return os.name
class Controls:
def check_os(self) -> None:
if os_name != "posix":
raise OSError
并在您的测试中修补该功能:@pytest.fixture
def name_mock(mocker):
return mocker.patch("path_to_module.controls.os_name", return_value="posix")
这样你只修补你应该修补的调用,而不会影响其他也使用 os.name
的代码。 .
关于python - 无法在 Windows 上使用 Python 模拟操作系统名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67251495/