Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Test a function in Python which merges files and returns nothing

I have the task to write a Test for the following function:

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

My Problem is that I have no clue to write a test for it. I am quite new to testing and thought for tests I shall not really read anything from a filesystem, but rather mock the expected output of a file. I could do this, but since I have no return value, I can also not check against that.

Does anyone know how to implement a test for these kind of functions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: The files will be requirements.txt and requirements-dev.txt

>Solution :

You can create a temporary directory via tempfile.TemporaryDirectory. Then you can create all content that is required for the test to run inside that directory and then call your merge function. For example:

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}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading