首页 > 解决方案 > 单元测试柯里化函数

问题描述

我试图弄清楚思考这个问题的正确方法是什么。我正在尝试在 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_twoadd_three

在我看来,这是一个实现细节,add_oneaddadd.

让我们将其扩展一分钟,并将其扩展到更现实的系统。

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吗?我是否认为柯里化只是实现细节并将其留给集成测试?

我对此感到有些迷茫,因为在面向对象的世界中,我知道如何使用模拟对其中的一些链接进行单元测试,但它似乎是倒退的,并且违背了一些功能范式以及我正在积极尝试通过玩弄来避免的事情它。

我现在的直觉是,柯里化函数是集成测试,只要对所有内容进行单独测试,显示组件工作,而不是链,我就可以离开进行集成测试,我可以证明整个系统可以工作。

标签: pythonunit-testingfunctional-programming

解决方案


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.


推荐阅读