1

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?

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

Data Mastery
  • 1,555
  • 4
  • 18
  • 60
  • create 2 input files and 1 expected output file. Compare the expected output file to the actual output file. – drum Nov 30 '21 at 16:19
  • You could use real files A, B, and C where C is the pre-determined merge of A and B. Then run the function to merge A and B, and see if you get the same contents as C. At the end of the test, delete your temporary output file. – jarmod Nov 30 '21 at 16:20
  • @drum: Can you show me how? Do I have to use real files or use mocks for that? – Data Mastery Nov 30 '21 at 16:21
  • I see no problem with reading real files. The test script is a file itself, so no reason not to store the files to be merged and the expected output along side of the test. – Jason Cook Nov 30 '21 at 16:36

1 Answers1

0

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}')
a_guest
  • 34,165
  • 12
  • 64
  • 118