亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Pythonmonkeypatch.setattr() 在模塊范圍內帶有 pytest 固定裝置

Pythonmonkeypatch.setattr() 在模塊范圍內帶有 pytest 固定裝置

慕桂英546537 2021-09-28 14:58:00
首先,我的項目目錄的相關部分如下所示:└── my_package    ├── my_subpackage    │   ├── my_module.py    |   └── other_module.py    └── tests        └── my_subpackage            └── unit_test.py我正在編寫一些測試unit_test.py,需要在模塊級別模擬外部資源。我想使用pytest fixture模塊級范圍并pytest monkeypatch完成此操作。這是我嘗試過的片段unit_test.py:import unittest.mock as mockimport pytestfrom my_package.my_subpackage.my_module import [email protected](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.'一切正常。但是當我嘗試將第 8 行從 更改@pytest.fixture(scope='function')為 時@pytest.fixture(scope='module'),出現以下錯誤。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()有誰知道如何使用模塊級范圍進行monkeypatch?如果有人想知道,這也是這兩個模塊的樣子。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.'
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 277 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號