首先,我的項(xiàng)目目錄的相關(guān)部分如下所示:└── my_package ├── my_subpackage │ ├── my_module.py | └── other_module.py └── tests └── my_subpackage └── unit_test.py我正在編寫一些測(cè)試unit_test.py,需要在模塊級(jí)別模擬外部資源。我想使用pytest fixture模塊級(jí)范圍并pytest monkeypatch完成此操作。這是我嘗試過(guò)的片段unit_test.py:import unittest.mock as mockimport pytestfrom my_package.my_subpackage.my_module import MyClass@pytest.fixture(scope='function')def external_access(monkeypatch): external_access = mock.MagicMock() external_access.get_something = mock.MagicMock( return_value='Mock was used.') monkeypatch.setattr( 'my_package.my_subpackage.my_module.ExternalAccess.get_something', external_access.get_something)def test_get_something(external_access): instance = MyClass() instance.get_something() assert instance.data == 'Mock was used.'一切正常。但是當(dāng)我嘗試將第 8 行從 更改@pytest.fixture(scope='function')為 時(shí)@pytest.fixture(scope='module'),出現(xiàn)以下錯(cuò)誤。ScopeMismatch: You tried to access the 'function' scoped fixture 'monkeypatch' with a 'module' scoped request object, involved factoriesmy_package\tests\unit_test.py:7: def external_access(monkeypatch)..\..\Anaconda3\envs\py37\lib\site-packages\_pytest\monkeypatch.py:20: def monkeypatch()有誰(shuí)知道如何使用模塊級(jí)范圍進(jìn)行monkeypatch?如果有人想知道,這也是這兩個(gè)模塊的樣子。my_module.pyfrom my_package.my_subpackage.other_module import ExternalAccessclass MyClass(object): def __init__(self): self.external_access = ExternalAccess() self.data = None def get_something(self): self.data = self.external_access.get_something()other_module.pyclass ExternalAccess(object): def get_something(self): return 'Call to external resource.'
添加回答
舉報(bào)
0/150
提交
取消