Issue
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
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}')
Answered By - a_guest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.