AttributeError:使用pytest的monkeypatch时

Dae*_*esi 5 python monkeypatching pytest

src/mainDir/mainFile.py

mainFile.py 的内容

import src.tempDir.tempFile as temp

data = 'someData'
def foo(self):
    ans = temp.boo(data)
    return ans
Run Code Online (Sandbox Code Playgroud)

src/tempDir/tempFile.py

def boo(data):

   ans = data
   return ans
Run Code Online (Sandbox Code Playgroud)

现在我想测试foo()并在方法中src/tests/test_mainFile.py模拟temp.boo(data)方法foo()

 import src.mainDir.mainFile as mainFunc

  testData = 'testData'
  def test_foo(monkeypatch):
     monkeypatch.setattr('src.tempDir.tempFile', 'boo', testData)
     ans = mainFunc.foo()
     assert ans == testData
Run Code Online (Sandbox Code Playgroud)

但我收到错误

属性错误:“src.tempDir.tempFile”没有属性“boo”

我期望 ans = testData.

我想知道我是否正确地模拟了我的 tempDir.boo() 方法,或者我应该使用 pytest 的模拟程序而不是 Monkeypatch。

The*_*ler 3

您告诉 Monkeypatch 修补boo您传入的字符串对象的属性。

您要么需要传入一个模块,例如monkeypatch.setattr(tempFile, 'boo', testData),或者也将属性作为字符串传递(使用两个参数形式),例如monkeypatch.setattr('src.tempDir.tempFile.boo', testData)