[英]How to mock import inside a method in python
这是一个非常简单的问题。 如果我在方法中有导入,如何模拟该特定导入? 例如:
def myFunction(self):
auth_token_path = self.authTokenPath()
import json
if os.path.exists(auth_token_path):
auth_token = json.load(open(auth_token_path, 'r'))
return auth_token
我该如何模拟这个“导入json”? 有什么办法可以解决这个问题? 我试图将其导入测试函数中,但我认为这不是正确的方法(并且也不起作用)。
模拟此功能
def myFunction(self):
auth_token_path = self.authTokenPath()
import json
if os.path.exists(auth_token_path):
auth_token = json.load(open(auth_token_path, 'r'))
return auth_token
我们需要做的就是添加与需要模拟的导入功能相关的装饰器PATCH():
@patch('json.load')
def myFunction(self,json):
auth_token_path = self.authTokenPath()
import json
if os.path.exists(auth_token_path):
auth_token = json.load(open(auth_token_path, 'r'))
return auth_token
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.