Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 41 additions & 6 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,47 @@ def test_cli_invalid_format():

def test_cli_explicit_format(input_file):
fmt = input_file.suffix.lstrip(".")
with input_file.open() as fp, \
mock.patch("pathlib.Path.open", return_value=fp), \
mock.patch("builtins.print") as print_:
main(["-f", fmt, "no-file.invalid"])
print_.assert_called_once()
(result,), _ = print_.call_args

# The explicit-format tests present a number of technical challenges.
#
# 1. The filename must not have a recognized extension
# to ensure that the renderer is honoring the `-f` argument.
# Therefore, patching is used so the input filename can be faked.
#
# 2. docutils must be able to open stylesheet files during RST-to-HTML rendering.
# Therefore, patching must be limited to readme-renderer's usage.
#
# The strategy used here is to patch `pathlib.Path.open()` until it is first called,
# since the first call occurs when readme-renderer reads the input file's content.
# After that, the patch is disabled. However, this presents additional challenges:
#
# 3. On Python <=3.11, `patch.__exit__()` cannot be called more than once.
# 4. `patch.stop()` cannot sufficiently undo a patch if `.__enter__()` was called.
#
# Therefore, the patch cannot be used as a context manager.
# It must be manually started and stopped.

fp = input_file.open()

def stop_open_patch_after_one_call():
open_patch.stop()
return fp

open_patch = mock.patch(
"pathlib.Path.open",
side_effect=stop_open_patch_after_one_call,
)

open_patch.start()

try:
with fp, mock.patch("builtins.print") as print_:
main(["-f", fmt, "no-file.invalid"])
print_.assert_called_once()
(result,), _ = print_.call_args
finally:
# Stop the patch regardless of the test result.
open_patch.stop()

with input_file.with_suffix(".html").open() as fp:
assert result.strip() == fp.read().strip()
Expand Down
Loading