【发布时间】:2022-01-07 08:34:54
【问题描述】:
我的任务是为以下函数编写测试:
def merge_files(cwd: Path, source: str, target: str):
"""[Merges the content of two files of the same data type]
Parameters
----------
cwd : Path
[Path of the the current work directory]
source : str
[File used to merge with target, lives in app subfolder]
target : str
[File used to merge with source]
"""
with open(os.path.join(cwd, "app", target), "a") as requirements_tool:
with open(os.path.join(cwd, source), "r") as requirements_user:
requirements_tool.write(requirements_user.read())
我的问题是我没有为它编写测试的线索。我对测试很陌生,并且考虑过测试我不会真正从文件系统中读取任何内容,而是模拟文件的预期输出。我可以这样做,但由于我没有返回值,我也无法检查。
有谁知道如何对这些功能进行测试?
编辑:文件将是 requirements.txt 和 requirements-dev.txt
【问题讨论】:
-
创建 2 个输入文件和 1 个预期输出文件。将预期输出文件与实际输出文件进行比较。
-
你可以使用真实的文件A、B和C,其中C是A和B的预先确定的合并。然后运行函数合并A和B,看看你是否得到相同的内容作为 C。在测试结束时,删除您的临时输出文件。
-
@drum:你能告诉我怎么做吗?我必须使用真实文件还是使用模拟?
-
我认为阅读真实文件没有问题。测试脚本本身就是一个文件,因此没有理由不将要合并的文件和预期的输出存储在测试旁边。
标签: python pytest python-unittest python-unittest.mock