python - 单元测试柯里化函数
问题描述
我试图弄清楚思考这个问题的正确方法是什么。我正在尝试在 python 中使用一些函数式编程范例。我知道它不是功能语言,但概念可以翻译。
可以说我有一组功能,例如:
def add(x: int, y: int) -> int:
return x + y
add_one = partial(add, y=1)
add_two = partial(add, y=2)
add_three = partial(add, y=3)
fut = lambda x: add_three(add_one(add_two(x)))
问题是,我是否对被测函数(fut
)进行单元测试?我会进行单元测试add_one
吗?add_two
add_three
在我看来,这是一个实现细节,add_one
它add
是add
.
让我们将其扩展一分钟,并将其扩展到更现实的系统。
class Save(Protocol):
def __call__(self, x: int): ...
def save_to_disk(x: int, file_name:str) -> None:
"""
Implementation of saving something to a disk
"""
...
save: Save = partial(save_to_disk, file_name="random_file")
def add(x: int, y: int) -> int:
return x + y
add_one = partial(add, y=1)
fut: Save = lambda x: save(add_one(x))
我现在有一个处理 IO 的函数和一些生成要保存的数据的工作。我在这里进行单元测试fut
吗?我是否认为柯里化只是实现细节并将其留给集成测试?
我对此感到有些迷茫,因为在面向对象的世界中,我知道如何使用模拟对其中的一些链接进行单元测试,但它似乎是倒退的,并且违背了一些功能范式以及我正在积极尝试通过玩弄来避免的事情它。
我现在的直觉是,柯里化函数是集成测试,只要对所有内容进行单独测试,显示组件工作,而不是链,我就可以离开进行集成测试,我可以证明整个系统可以工作。
解决方案
If add
has been tested then I don't think each partial application needs it's own unit test. However, I would unit test fut
by mocking or spying on add_one
, add_two
, and add_three
(this shouldn't be difficult with a decent testing framework) and making sure that they are called with the correct arguments.
So, my unit test would expect that add_two
is called with whatever fut
is called with, add_one
is called with whatever add_two
returns, and add_three
is called with whatever add_two
returns.
推荐阅读
- google-sheets - 如何动态同步数据谷歌表数据?
- c# - 在跨域的 IIS 上的 C# 应用程序中运行 Powershell cmdlet
- c# - 将指向数组的指针从 C# 传递到 c DLL
- r - 通过在 R 中建立索引来寻找循环
- css - 内联块中输入字段的全宽不起作用
- python - 来自响应请求python的图像中的标记框
- r - scatter3d(): chol.default(shape) 错误: 前导次要顺序不是正定的
- python - 无法使用 mongoengine 删除文档对象
- macos - 执行脚本时 AppleScript 使用哪个用户
- spring-boot - 如何在yaml中将多个包定义为受信任的包