如何模拟python中的链接函数调用? [英] How to mock chained function calls in python?

查看:143
本文介绍了如何模拟python中的链接函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用由Michael Foord撰写的 mock 图书,以帮助我测试一个django应用程序。

I'm using the mock library written by Michael Foord to help with my testing on a django application.

我想测试我正确设置我的查询,但我不认为我需要实际打数据库,所以我试图嘲笑查询。

I'd like to test that I'm setting up my query properly, but I don't think I need to actually hit the database, so I'm trying to mock out the query.

我可以嘲笑查询的第一部分,但是我没有得到我的结果就像我链接附加的东西一样。

I can mock out the first part of the query just fine, but I am not getting the results I'd like when I chain additional things on.

功能:


    @staticmethod
    def get_policies(policy_holder, current_user):
        if current_user.agency:
            return Policy.objects.filter(policy_holder=policy_holder, version__agency=current_user.agency).distinct()
        else:
            return Policy.objects.filter(policy_holder=policy_holder)

和我的测试:第一个断言通过,第二个一个失败。

and my test: The first assertion passes, the second one fails.


    def should_get_policies_for_agent__user(self):
        with mock.patch.object(policy_models.Policy, "objects") as query_mock:
            user_mock = mock.Mock()
            user_mock.agency = "1234"
            policy_models.Policy.get_policies("policy_holder", user_mock)
            self.assertEqual(query_mock.method_calls, [("filter", (), {
                'policy_holder': "policy_holder",
                'version__agency': user_mock.agency,
            })])
            self.assertTrue(query_mock.distinct.called)

我很确定问题是,调用了.filter()之后,初始的query_mock返回一个新的模拟,但是我不知道如何捕获这个新的模拟确保已经调用了.distinct()。

I'm pretty sure the issue is that the initial query_mock is returning a new mock after the .filter() is called, but I don't know how to capture that new mock and make sure .distinct() was called on it.

有没有更好的方法来测试我想要得到的东西?我试图确保正确的查询被调用。

Is there a better way to be testing what I am trying to get at? I'm trying to make sure that the proper query is being called.

推荐答案

每个模拟对象都保持在模拟对象上当它被调用时返回。您可以使用您的模拟对象的return_value属性来保留它。

Each mock object holds onto the mock object that it returned when it is called. You can get a hold of it using your mock object's return_value property.

对于您的示例,

self.assertTrue(query_mock.distinct.called)

distinct不是调用你的模拟,它被称为你的模拟的过滤器的返回值,所以你可以断言通过这样做来调用distinct:

distinct wasn't called on your mock, it was called on the return value of the filter method of your mock, so you can assert that distinct was called by doing this:

self.assertTrue(query_mock.filter.return_value.distinct.called)

这篇关于如何模拟python中的链接函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆