简体   繁体   English

我如何在用pytest测试的模块中模拟依赖项的类?

[英]How can I mock a dependency's class in a module I test with pytest?

I have a test module, test_roles.py which is trying to test the module roles.py . 我有一个测试模块test_roles.py ,它正在尝试测试模块roles.py I want to mock out the use of MongoClient from pymongo within the roles module, so that my unit tests do not rely on an external service. 我想在role模块中从pymongo模拟出MongoClient的使用,以便我的单元测试不依赖外部服务。 The following is a simplified example of what I'm doing that isn't working for me. 以下是我正在做的对我不起作用的简化示例。 How do I get this to work so that I can fake out MongoClient everywhere? 我如何使它工作,以便可以在MongoClient地方伪造MongoClient

In roles.py : roles.py

from pymongo import MongoClient
client = MongoClient(...)

In test_roles.py : test_roles.py

import roles
def test_mock():
    assert type(roles.client).__name__ == 'FakeMongoClient'

In conftest.py : conftest.py

import pytest
import pymongo

@pytest.fixture(autouse=True)
def fake_mongo(monkeypatch):
    class FakeMongoClient():
         pass
    monkeypatch.setattr(pymongo, 'MongoClient', FakeMongoClient)

I don't believe the question identified as a duplicate is asking the same thing. 我不认为被确定为重复的问题在问同样的事情。 Editing a module's global variable after-the-fact is different from modifying the dependency such that the actions that occur during import use the mocked dependency. 事后编辑模块的全局变量不同于修改依赖关系,以便在导入期间发生的操作使用模拟的依赖关系。 In this example, unless the MongoClient initialization uses lazy connections, failing to mock before first import means we get a failure during import of roles. 在此示例中,除非MongoClient初始化使用惰性连接,否则在首次导入之前无法模拟就意味着我们在角色导入期间会失败。

roles.py uses roles.MongoClient , not pymongo.MongoClient , to define roles.client , due to how you imported the name. 由于您是如何导入名称的,所以roles.py使用roles.MongoClient而非pymongo.MongoClient来定义roles.client You need to patch the same: 您需要打补丁:

monkeypatch.setattr(roles, 'MongoClient', FakeMongoClient)

Your original patch should work if roles.py looked like 如果roles.py看起来像您的原始补丁应该工作

import pymongo
client = pymongo.MongoClient()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM