在 Python 中测试一个合并文件的函数,returns 什么都没有

Test a function in Python which merges files and returns nothing

我的任务是为以下函数编写测试:

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())

我的问题是我不知道为它编写测试。我对测试和思考很陌生,我不会真正从文件系统中读取任何内容,而是模拟文件的预期输出。我可以这样做,但是因为我没有 return 值,所以我也无法检查它。

有谁知道如何对这些功能进行测试?

编辑:文件将是 requirements.txtrequirements-dev.txt

您可以通过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}')