【问题标题】:Python mock aggregate function of MongoDB in PymongoPymongo中MongoDB的Python模拟聚合函数
【发布时间】:2019-12-13 21:50:48
【问题描述】:

我想模拟PyMongo提供的aggregate函数用于以下代码:

client = MongoClient(host="localhost", port=27017,username="Harsha", password="Harsha", authSource="admin")
db_obj = client["DB name"]
mongo_result = db_obj[collection_name].aggregate(pipeline)

我想模拟 aggregate 函数。

谁能帮我模拟一下聚合函数?

我尝试了以下代码 sn-p 来模拟聚合函数:

试用 1:

from pymongo import collection
collection_obj = collection.Collection(client["DB name"], "collection_name")

def mock_get(self, *args):
    return "Result I want"

@mock.patch(collection_obj.Collection.aggregate, side_effect=mock_get)
def test_demo(self):
    .
    .
    .
    .

这不起作用,因为 @mock.patch 需要字符串完整路径参数。

所以我也尝试给出aggregation函数的完整路径

试用 2:

class BasicTest(unittest.TestCase):

    def mock_get(self, *args):
        return "Result I want"

    @mock.patch('pymongo.collection.Collection.aggregate', side_effect=mock_get)
    def test_demo(self):
        .
        .
        .
        .

这是给我的:

TypeError: test_demo() takes 1 positional argument but 2 were given

【问题讨论】:

    标签: python unit-testing mocking pymongo


    【解决方案1】:

    patch 将模拟对象作为额外参数传递给装饰函数,以便您可以对其进行断言。像这样更改您的代码:

    @mock.patch('pymongo.collection.Collection.aggregate', side_effect=mock_get)
    def test_demo(self, mock_object):
         .
         .
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2014-03-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      相关资源
      最近更新 更多