【发布时间】:2014-03-31 07:34:08
【问题描述】:
我的 flask+python 应用通过第三方模块 nativelib 从本机二进制文件中提取 json。
基本上,我的函数看起来像这样
def list_users():
return nativelib.all_users()
然而,对这个第三方模块的强烈依赖和庞大的原生组件被证明是快速开发的巨大障碍。
我想做的是模拟我的list_users 函数的返回值。
此外,我应该能够通过简单地切换一些布尔值来切换回“真实数据”。
这个布尔值可以是代码中的某个属性或某个命令行参数。
我目前设计的解决方案如下所示:
@mockable('users_list')
def list_users():
return nativelib.all_users()
我已经将上述mockable 实现为一个类:
class mockable:
mock = False
# A dictionary that contains a mapping between the api method
# ..and the file which contains corresponding the mock json response
__mock_json_resps = {'users_list':'/var/mock/list_user.json', 'user_by_id': '/var/mock/user_1.json'}
def __init__(self, api_method):
self.api_method = api_method
def __call__(self, fn):
@wraps(fn)
def wrapper():
if mock:
# If mocking is enabled,read mock data from json file
mock_resp = __mock_json_resps[self.api_method]
with open(mock_resp) as json_file:
return json.load(json_file)
else:
return self.fn()
return wrapper
在我的入口点模块中,我可以使用
mockable.mock = True
现在虽然这可能有效,但我很想知道这是否是“pythonic”的做法。
如果没有,实现这一目标的最佳方法是什么?
【问题讨论】:
-
有人建议使用
unitest.mock,但我不确定是否要引入对unittest的依赖。此外,这将如何让我在我的开发环境中快速打开或关闭模拟?
标签: python python-3.x python-decorators