功能伪造者
functionfaker的Python项目详细描述
功能伪造者
轻量级Decorator to cache (memoize) function calls和重播响应,用于昂贵的计算和API请求
Pip installable通过pip install functionfaker
FunctionFaker提供轻量级且易于理解的函数(和方法)缓存,类似于Joblib包的某些功能。函数响应记录一次,然后从缓存中重放这允许使用api调用对应用程序进行单元测试,而不必实际调用api。它还可以加速计算成本高昂的代码的原型化FunctionFaker由简单的代码组成,并为函数和方法提供一个装饰器,如下面的“Hello World”示例所示。
from functionfaker import response_player
import os
将response_player
decorator添加到名为add
的示例函数:
@response_player()
def add(x, y):
return x + y
然后通过设置环境变量来设置记录模式:
# enter record mode, to record function responses.
os.environ['RECORD'] = "record"
多次调用add
函数:
# Clear the stored function responses
if os.path.exists('responses.p'):
os.remove('responses.p')
# call the add function to record some responses.
add(1,2)
add(1,y=3)
add(1,3)
add(2,1)
Recording response function "add" Recording response function "add" Recording response function "add"
通过环境变量设置replay
模式:
# enter replay mode, so that function will not run, but return stored values instead.
os.environ['RECORD'] = "replay"
再次调用add
函数,使用它已经看到的参数:
result = add(1,2)
print("The saved result of adding 1 and 2 using function 'add' is %d"%result)
Faking function "add". Response found
The saved result of adding 1 and 2 using function 'add' is 3
这些输入(1,2)的输出现在从缓存中读取
某些函数参数可能不相关或难以序列化。要忽略这些参数,请将args2ignore
参数作为整数列表提供给response_player
装饰器,其中整数表示参数列表中的索引。
默认函数响应存储在一个简单的Pickle文件responses.p
中要使用自己的存储系统,请使用update
和get_response
方法提供从BaseStore
类派生的类然后,这个类的一个对象作为store
参数提供给response_player
装饰器。