【问题标题】:Test a function in Python which merges files and returns nothing在 Python 中测试一个合并文件并且不返回任何内容的函数
【发布时间】: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.txtrequirements-dev.txt

【问题讨论】:

  • 创建 2 个输入文件和 1 个预期输出文件。将预期输出文件与实际输出文件进行比较。
  • 你可以使用真实的文件A、B和C,其中C是A和B的预先确定的合并。然后运行函数合并A和B,看看你是否得到相同的内容作为 C。在测试结束时,删除您的临时输出文件。
  • @drum:你能告诉我怎么做吗?我必须使用真实文件还是使用模拟?
  • 我认为阅读真实文件没有问题。测试脚本本身就是一个文件,因此没有理由不将要合并的文件和预期的输出存储在测试旁边。

标签: python pytest python-unittest python-unittest.mock


【解决方案1】:

您可以通过tempfile.TemporaryDirectory 创建一个临时目录。然后,您可以创建在该目录中运行测试所需的所有内容,然后调用您的合并函数。例如:

from pathlib import Path
from tempfile import TemporaryDirectory

def test_merge_files():
    with TemporaryDirectory() as td:
        td = Path(td)
        f_target = td / 'app' / 'target'
        f_source = td / 'source'
        example_content_target = 'foo'
        example_content_source = 'bar'
        f_target.parent.mkdir()
        f_target.write_text(example_content_target)
        f_source.write_text(example_content_source)
        merge_files(td, source=f_source, target=f_target)
        assert f_target.read_text() == f'{example_content_target}{example_content_source}')

【讨论】:

  • 谢谢你,真的很好!我不知道临时目录!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 2020-03-28
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
相关资源
最近更新 更多