|
| 1 | +import io |
1 | 2 | import pathlib |
2 | 3 | import tempfile |
| 4 | +from contextlib import redirect_stdout |
3 | 5 | from unittest.mock import patch |
4 | 6 |
|
5 | 7 | import pytest |
@@ -40,3 +42,56 @@ def mock_input(prompt): |
40 | 42 | with patch("builtins.print") as patched, patch("builtins.input", mock_input): |
41 | 43 | parse.interactive() |
42 | 44 | patched.assert_called() |
| 45 | + |
| 46 | + |
| 47 | +def test_main_no_args_is_interactive(): |
| 48 | + with patch("markdown_it.cli.parse.interactive") as mock_interactive: |
| 49 | + assert parse.main([]) == 0 |
| 50 | + mock_interactive.assert_called_once() |
| 51 | + |
| 52 | + |
| 53 | +def test_parse_output(): |
| 54 | + with tempfile.TemporaryDirectory() as tempdir: |
| 55 | + path = pathlib.Path(tempdir).joinpath("test.md") |
| 56 | + path.write_text("# a b c") |
| 57 | + string_io = io.StringIO() |
| 58 | + with redirect_stdout(string_io): |
| 59 | + assert parse.main([str(path)]) == 0 |
| 60 | + assert string_io.getvalue() == "<h1>a b c</h1>\n" |
| 61 | + |
| 62 | + |
| 63 | +def test_stdin(): |
| 64 | + with patch("sys.stdin", io.StringIO("# a b c")): |
| 65 | + string_io = io.StringIO() |
| 66 | + with redirect_stdout(string_io): |
| 67 | + assert parse.main(["--stdin"]) == 0 |
| 68 | + assert string_io.getvalue() == "<h1>a b c</h1>\n" |
| 69 | + |
| 70 | + |
| 71 | +def test_multiple_files(): |
| 72 | + with tempfile.TemporaryDirectory() as tempdir: |
| 73 | + path1 = pathlib.Path(tempdir).joinpath("test1.md") |
| 74 | + path1.write_text("# file 1") |
| 75 | + path2 = pathlib.Path(tempdir).joinpath("test2.md") |
| 76 | + path2.write_text("* file 2") |
| 77 | + string_io = io.StringIO() |
| 78 | + with redirect_stdout(string_io): |
| 79 | + assert parse.main([str(path1), str(path2)]) == 0 |
| 80 | + assert string_io.getvalue() == "<h1>file 1</h1>\n<ul>\n<li>file 2</li>\n</ul>\n" |
| 81 | + |
| 82 | + |
| 83 | +def test_interactive_render(): |
| 84 | + # Simulate user typing '# hello', pressing Ctrl-D (renders), then Ctrl-C (exits) |
| 85 | + # This is needed to break the infinite loop in interactive mode on EOF. |
| 86 | + mock_input = patch( |
| 87 | + "builtins.input", side_effect=["# hello", EOFError, KeyboardInterrupt] |
| 88 | + ) |
| 89 | + string_io = io.StringIO() |
| 90 | + with redirect_stdout(string_io), mock_input: |
| 91 | + parse.interactive() |
| 92 | + |
| 93 | + output = string_io.getvalue() |
| 94 | + assert "markdown-it-py" in output # from print_heading |
| 95 | + # The rendered output is prefixed by a newline |
| 96 | + assert "\n<h1>hello</h1>\n" in output |
| 97 | + assert "Exiting" in output |
0 commit comments