Python Mock Patch在__attrs_post_init__中调用的函数不生效问题
解决Mock Patch拦截__attrs_post_init__中函数调用失效的问题
问题出在你patch的路径不对。PhraseController类通过from utils.auth import get_access_token直接导入了函数,此时类里调用的get_access_token是该类所在模块内的副本,而非utils.auth模块中的原函数,所以你对utils.auth.get_access_token的patch无法影响到这里。
正确的做法是patch函数被实际调用的位置——也就是PhraseController所在模块中导入的get_access_token引用。
假设PhraseController位于your_module.phrase_controller模块下,修改后的Mock代码如下:
with mock.patch('your_module.phrase_controller.get_access_token', return_value=self.mock_access_token) as mock_get_access_token: self.phraseController = PhraseController( cognito_client_id=self.cognito_client_id, cognito_client_secret=self.cognito_client_secret, raw_object_key=self.raw_object_key, backend_url=self.backend_url, cdn_url= self.cdn_url, tagging_version=self.tagging_version, output_dir= self.output_dir, event_time= self.event_time, output_bucket=self.output_bucket, s3_endpoint_url = self.s3_endpoint_url )
核心原则:当使用from 模块 import 函数的方式导入时,函数会成为当前模块的一个变量,此时必须patch这个变量所在的模块路径,而非原函数的定义路径。
内容的提问来源于stack exchange,提问作者Steven Staley
相关产品推荐
相关产品推荐

