修补视图中使用的类方法

问题描述

鉴于AWS的某些响应,我正在尝试测试我的视图。为此,我想修补我编写的类以在运行测试时返回某些内容。

 @patch.object(CognitoInterface,"get_user_tokens",return_value=mocked_get_user_tokens_return)


class TestLogin(TestCase):

    def test_login(self,mocked_get_user_tokens):
        print(CognitoInterface().get_user_tokens("blah","blah")) # Works,it prints the patched return value

        login_data = {"email": "whatever@example.com","password": "password"}
        response = self.client.post(reverse("my_app:login"),data=login_data)

在“ my_app:login”视图中,我呼叫...

CognitoInterface().get_user_tokens(email,password)

但是这一次,它使用了真正的方法。我也希望它在这里使用修补后的收益。

看来我的补丁仅适用于测试文件。在测试过程中如何使补丁适用于所有代码?

编辑:从未弄清楚为什么@ patch.object无法正常工作。我只是使用@patch(“ path.to.file.from.project.root.ClassName.method_to_patch”)。

另外,请参见:http://bhfsteve.blogspot.com/2012/06/patching-tip-using-mocks-in-python-unit.html

解决方法

CognitoInterface最有可能在猴子修补发生之前被导入views.py中。您可以通过以下方式进行检查:在导入print()的视图中添加CognitoInterface(或声明,从此处的代码量中看不出来),然后在Monkeypatching旁边添加另一个print()

如果猴子修补发生在后期,则必须延迟导入,或者在最坏的情况下都要在两个地方进行猴子修补。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...