如何在Django中模拟函数?

2024-05-15 11:55:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望下面对which_user的调用返回self.user,不管传递给它的是什么,但它的行为好像根本没有被模仿

def test_user_can_retrieve_favs_using_impersonation(self):
        with mock.patch('impersonate.helpers.which_user', return_value=self.user):
            user = which_user(self.user2)

我做错了什么?我像这样导入了which_userfrom impersonate.helpers import which_user,如果这样有帮助的话


Tags: testselfwhichdefwithmockcanhelpers
1条回答
网友
1楼 · 发布于 2024-05-15 11:55:21

您需要根据函数的导入路径来模拟函数。 例如,您在myapp的视图中使用您的函数。因此,您需要按照以下方式进行操作:

with mock.patch('myapp.views.which_user', return_value=self.user):
        user = which_user(self.user2)

这是因为它只修补可测试模块中定义的变量,而不修补系统或venv中的原始库和包

相关问题 更多 >