如何从调用方法的函数中修补参数?

您好,我是单元测试的新手,因此我遇到了unittest.mock的大问题。 我的项目包含不同的模块。 我的第一个模块是常规:

general.py


def do_something(item,collection): 
    # some more code that i want to test
    try:
        collection.insert_one(item)
    except:
        print("did not work")

我的第二个模块ist my_module.py

mymodule.py

import general
from pymongo import MongoClient

client = MongoClient("localhost",27017)
db = client['db']
collection = db['col']

item = 
  {
    "id": 1
  }



def method:
    general.do_something(item,collection)

现在,我想从general.py测试do_something(item,collection)方法,因此我想模拟collection.insert_one(item)。我没有找到可能的解决方案。 我用patch尝试过,但是我的问题是参数集合(这是pymongo集合)是调用函数的参数。我现在如何设法模拟collection.insert_one?

我的目标是提取collection.insert_one并将其设置为MagicMock。而且此Magic Mock应该有可能崩溃以检查其他部分是否工作,或者没有崩溃以检查try部分是否工作。

TestGeneral.py
import unnittest

class TestGeneral(unittest.TestCase):

    @patch()
    def test_general():





先谢谢您! :)

syz12589 回答:如何从调用方法的函数中修补参数?

这里实际上不需要模拟,您只需创建一个具有类似功能的类即可。

TestGeneral.py
import unnittest

class TestGeneral(unittest.TestCase):

    def test_general_success():
        assert general.do_something(collection(),None)

    def test_general_failure():
        with self.assertRaises(Exception): 
            general.do_something(collection(fail=True),None))

class collection:
    def __init__(self,fail=False):
        self.fail = fail

    def insert_one(self,item):
        if self.fail:
            raise Exception
        return True

然后,您还可以检查标准输出,以确保成功使用打印件

,

如果由于某种原因必须使用模拟,则此方法可以工作

TestGeneral.py 导入unnittest

class TestGeneral(unittest.TestCase):

    @mock.patch('{your path}.my_module.MongoClient')
    def test_general_success(mock_mongo):
        mock_mongo.return_value = {'db': None,'col': collection()}
        assert general.do_something(None,None)  # None here since the collection is mocked anyway

    @mock.patch('{your path}.my_module.MongoClient')
    def test_general_failure(mock_mongo):
        mock_mongo.return_value = {'db': None,'col': collection(fail=True)}
        with self.assertRaises(Exception): 
            general.do_something(None,item):
        if self.fail:
            raise Exception
        return True

缺点是您现在已经模拟了整个MongoDB,这意味着它的任何其他用途(即客户端)也将被模拟

本文链接:https://www.f2er.com/3137112.html

大家都在问