import contextlib import io import pathlib import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure from markdown_section import main TOOL = pathlib.Path(__file__).resolve().parents[1] / "markdown-section" DOCUMENT = """# Title Intro. ## Alpha Alpha text. ### Alpha detail Detail text. ## Beta Gamma Beta text. ``` ## Not a heading ``` ## Delta Delta text. """ class Section(unittest.TestCase): def test_a_section_runs_to_the_next_heading_of_its_level_or_a_higher_one(self): cases = { "a sub-section stops at a higher level heading": ("alpha detail", "### Alpha detail\n\nDetail text.\n"), "the text under a heading isn't a heading": ("alpha text", Failure("no heading holds 'alpha text'")), "the last section runs to the end of the file": ("delta", "## Delta\n\nDelta text.\n"), "a level one heading holds the rest of the document": ("title", DOCUMENT), "a fenced line that looks like a heading doesn't end it": ("beta", "## Beta Gamma\n\nBeta text.\n\n```\n## Not a heading\n```\n"), } for name, (fragment, expected) in cases.items(): with self.subTest(name): self.assertEqual(main.section(DOCUMENT, fragment), expected) def test_the_fragment_matches_any_part_of_the_heading_text_in_any_case(self): for fragment in ("gamma", "BETA g", " beta gamma "): with self.subTest(fragment): self.assertEqual(str(main.section(DOCUMENT, fragment)).splitlines()[0], "## Beta Gamma") self.assertEqual(main.section(DOCUMENT, "## beta"), Failure("no heading holds '## beta'")) def test_a_heading_whose_text_is_the_fragment_wins_over_longer_ones(self): self.assertEqual(main.section(DOCUMENT, "Alpha"), "## Alpha\n\nAlpha text.\n\n### Alpha detail\n\nDetail text.\n") self.assertEqual(main.section("## Plan\n\na\n\n## Plan b\n", "PLAN"), "## Plan\n\na\n") def test_several_matching_headings_fail_listing_each_with_its_line(self): listed = main.section("## Plan one\n\ntext\n\n## Plan two\n", "plan") self.assertEqual(listed, Failure("2 headings hold 'plan', so use more of one:\n1: ## Plan one\n5: ## Plan two")) def test_what_counts_as_a_heading_or_a_fence(self): cases = { "a hash with no space after it is no heading": ("#hashtag\n\n## Real\n", "hashtag", Failure("no heading holds 'hashtag'")), "a fence with an info string closes on a bare fence": ("```python\n## In\n```\n## Out\n\ntext\n", "out", "## Out\n\ntext\n"), "a fence of four backticks holds a line of three": ("````\n```\n## In\n````\n## Out\n", "out", "## Out\n"), "a tilde fence holds a heading": ("~~~\n## In\n~~~\n## Out\n", "in", Failure("no heading holds 'in'")), "an indented fence holds a heading": (" ```\n## In\n ```\n", "in", Failure("no heading holds 'in'")), "an unclosed fence holds the rest": ("## A\n\n```\n## In\n", "a", "## A\n\n```\n## In\n"), } for name, (text, fragment, expected) in cases.items(): with self.subTest(name): self.assertEqual(main.section(text, fragment), expected) def test_only_blank_lines_are_cut_from_the_end_of_a_section(self): self.assertEqual(main.section("## A\n\nends in X\n\n\n## B\n", "a"), "## A\n\nends in X\n") self.assertEqual(main.section("## A\n\ncode \n\n", "a"), "## A\n\ncode \n") def test_no_heading_is_a_failure(self): self.assertEqual(main.section(DOCUMENT, "zeta"), Failure("no heading holds 'zeta'")) class Main(unittest.TestCase): def setUp(self) -> None: self.file = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "notes.md" self.file.write_text(DOCUMENT) def run_main(self, *args: str) -> tuple[int, str, str]: out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(list(args)) return code, out.getvalue(), err.getvalue() def test_prints_the_section(self): self.assertEqual(self.run_main(str(self.file), "delta"), (0, "## Delta\n\nDelta text.\n", "")) def test_a_failure_is_printed_to_stderr_with_exit_1(self): self.assertEqual(self.run_main(str(self.file), "zeta"), (1, "", "markdown-section: no heading holds 'zeta'\n")) def test_a_file_that_cant_be_read_exits_1_naming_it(self): self.file.write_bytes(b"\xff\xfe## A\n") missing = self.file.with_name("missing.md") for unreadable, reason in ((missing, "missing.md"), (self.file, "decode")): with self.subTest(reason): code, out, err = self.run_main(str(unreadable), "a") self.assertEqual((code, out), (1, "")) self.assertRegex(err, rf"^markdown-section: .*{reason}") def test_wrong_arguments_exit_2_with_the_usage(self): for args in ((), (str(self.file),), (str(self.file), "a", "b"), (str(self.file), " ")): with self.subTest(args): self.assertEqual(self.run_main(*args), (2, "", "usage: markdown-section \n")) def test_help_prints_the_usage_and_exits_0_whatever_follows_it(self): for args in (("-h",), ("--help",), ("--help", "x")): with self.subTest(args): code, out, err = self.run_main(*args) self.assertEqual((code, err), (0, "")) self.assertTrue(out.startswith("Print one section of a markdown file")) class Launcher(unittest.TestCase): def test_the_launcher_runs_the_tool(self): file = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "notes.md" file.write_text(DOCUMENT) ran = subprocess.run([sys.executable, str(TOOL), str(file), "delta"], capture_output=True, text=True) self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, "## Delta\n\nDelta text.\n", "")) if __name__ == "__main__": unittest.main()