opensheaf-literate

The tests

The tests, run with pytest, write small literate documents into a temporary folder and look at what the tools make of them: the rules of the syntax, one by one, the mistakes they report, the notices, the configuration, the command line and, when Markdown and Pygments are installed, the website. They are tangled, like everything else, into tests/.

The bootstrap of the previous chapter is the other test: it checks that the tools, run on these documents, make exactly the files of the repository.

A project to test on

Every test runs in a project of its own, an empty temporary folder that is made the current one, with a folder literate/ for its documents. The fixture project writes a document there, given its lines; the code lines of the documents are written with their four spaces, as they would be in a real document.

A line of a test document that is a reference must not be a line of this chapter that is only a reference, or the tangler would expand it while tangling the tests: written as a string in a list of lines, between quotes, it is not.

from pathlib import Path

import pytest


def lines(*lines):
    return "\n".join(lines) + "\n"


@pytest.fixture
def project(tmp_path, monkeypatch):
    """A function writing a document of a new project, in the current folder."""
    monkeypatch.chdir(tmp_path)
    (tmp_path / "literate").mkdir()

    def write(name, *text):
        path = Path("literate") / name
        path.write_text(lines(*text), encoding="utf-8")
        return path
    return write

The syntax

The tests of the tangler import the functions of its module, and the command line, which runs in the current folder.

import json
import os
from pathlib import Path

import pytest

from literate.cli import main
from literate.config import Config, load
from literate.tangle import (Error, blocks, documents, file_names, read_chunks, tangle, unused,
                             update, where)

NOTICE = "Generated from literate/index.md by opensheaf-literate: edit the document, not this file."


def files():
    """The text of every file of the project, by name, without notices."""
    chunks = read_chunks(documents())
    return {name: tangle(chunks, name, {})[0] for name in file_names(chunks)}


⟨the tests of the tangler⟩

A header is a comment of any language: what comes before in and after the colon is punctuation, whatever it is.

def test_headers_in_the_comments_of_every_language(project):
    doc = project("index.md",
                  "Prose.", "",
                  "    # in a.py:", "    x = 1", "",
                  "Prose.", "",
                  "    // in b.js:", "    let x;", "",
                  "Prose.", "",
                  "    <!-- in c.html: -->", "    <p>", "",
                  "Prose.", "",
                  "    /* in d.css: */", "    p {}")
    found = blocks(doc)
    assert [b.name for b in found] == ["a.py", "b.js", "c.html", "d.css"]
    assert [b.lines for b in found] == [["x = 1"], ["let x;"], ["<p>"], ["p {}"]]

A block without a header continues the chunk before it, and its first program line is its first line; a document cannot begin with such a block.

def test_a_block_without_header_continues_the_chunk_before(project):
    doc = project("index.md", "    # in a chunk:", "    one", "", "Prose.", "", "    two")
    found = blocks(doc)
    assert [(b.name, b.header, b.lines, b.first) for b in found] == [
        ("a chunk", True, ["one"], 2), ("a chunk", False, ["two"], 6)]


def test_a_code_block_before_the_first_chunk_name(project):
    doc = project("index.md", "Prose.", "", "    orphan")
    with pytest.raises(Error, match="index.md:3: a code block before the first chunk name"):
        blocks(doc)

A code block is indented by four spaces after a blank line, outside a fence; the blank lines inside it are part of it, those at its end are not; an indented line just after prose continues the paragraph, as in Markdown.

def test_what_is_a_code_block(project):
    doc = project("index.md",
                  "```", "    # in fenced.py:", "    x = 1", "```", "",
                  "Prose", "    # in lazy.py:", "",
                  "    # in a.txt:", "    one", "", "    two", "", "", "Prose.")
    found = blocks(doc)
    assert [b.name for b in found] == ["a.txt"]
    assert found[0].lines == ["one", "", "two"]
    assert (found[0].start, found[0].end) == (8, 12)

A reference is replaced by its chunk, indented as the reference is, and references inside it add their indentation to it.

def test_references_are_indented_as_they_are(project):
    project("index.md",
            "    # in a.py:", "    def f():", "        <<body>>", "",
            "Prose.", "",
            "    # in body:", "    if x:", "        <<inner>>", "    return 1", "",
            "Prose.", "",
            "    # in inner:", "    pass")
    assert files()["a.py"] == "def f():\n    if x:\n        pass\n    return 1\n"

The fragments of a chunk follow one another in the order of the documents, index.md first, separated by a blank line, or by two at the left margin of a Python file.

def test_the_fragments_of_a_chunk_in_the_order_of_the_documents(project):
    for name, word in [("20-b.md", "b"), ("10-a.md", "a"), ("index.md", "i")]:
        project(name, "    # in x.txt:", f"    {word}")
    assert files()["x.txt"] == "i\n\na\n\nb\n"


def test_two_blank_lines_between_fragments_at_the_top_level_of_python(project):
    project("index.md",
            "    # in a.py:", "    <<definitions>>", "",
            "Prose.", "",
            "    # in b.py:", "    class C:", "        <<definitions>>", "",
            "Prose.", "",
            "    # in c.txt:", "    <<definitions>>", "",
            "Prose.", "",
            "    # in definitions:", "    def f(): pass", "",
            "Prose.", "",
            "    # in definitions:", "    def g(): pass")
    made = files()
    assert made["a.py"] == "def f(): pass\n\n\ndef g(): pass\n"
    assert made["b.py"] == "class C:\n    def f(): pass\n\n    def g(): pass\n"
    assert made["c.txt"] == "def f(): pass\n\ndef g(): pass\n"

Mistakes

A header right after a blank line inside a block is program text, and probably a mistake: it is reported, at its line, and tangling goes on.

def test_a_header_inside_a_block_is_reported(project, capsys):
    doc = project("index.md", "    # in a.txt:", "    one", "", "    # in b.txt:", "    two")
    assert [b.name for b in blocks(doc)] == ["a.txt"]
    assert "index.md:4: a header inside a code block" in capsys.readouterr().err

A chunk neither used nor a file is reported; a reference to a chunk that does not exist, and a chunk that includes itself, stop the tangling, with the place of the reference.

def test_unused_chunks(project, capsys):
    project("index.md", "    # in a.txt:", "    <<used>>", "",
            "Prose.", "", "    # in used:", "    x", "",
            "Prose.", "", "    # in forgotten:", "    y")
    assert unused(read_chunks(documents())) == ["forgotten"]
    assert main(["tangle"]) == 0
    assert "index.md:11: <<forgotten>> is never used" in capsys.readouterr().err


def test_undefined_references(project):
    project("index.md", "    # in a.txt:", "    <<missing>>")
    with pytest.raises(Error, match="index.md:2: <<missing>> is never defined"):
        files()


def test_chunks_that_include_themselves(project):
    project("index.md", "    # in a.txt:", "    <<x>>", "",
            "Prose.", "", "    # in x:", "    <<y>>", "",
            "Prose.", "", "    # in y:", "    <<x>>")
    with pytest.raises(Error, match="index.md:12: <<x>> includes itself: a.txt > x > y > x"):
        files()

Notices and where lines come from

Every file takes the notice in its own comments, after the #! line of a script; HTML, CSS and JSON take none.

def test_notices_by_suffix(project):
    names = ["a.py", "tools/run", "b.sh", "c.toml", "d.yml", "e.yaml", "f.js", "g.mjs", "h.cjs",
             "i.html", "j.css", "k.json"]
    text = []
    for name in names:
        script = ["    #!/bin/sh"] if name == "tools/run" else []
        text += [f"    # in {name}:", *script, "    x", "", "Prose.", ""]
    project("index.md", *text)
    chunks = read_chunks(documents())
    first = {name: tangle(chunks, name)[0].split("\n")[:2] for name in names}
    for name in ["a.py", "b.sh", "c.toml", "d.yml", "e.yaml"]:
        assert first[name] == [f"# {NOTICE}", "x"]
    for name in ["f.js", "g.mjs", "h.cjs"]:
        assert first[name] == [f"// {NOTICE}", "x"]
    for name in ["i.html", "j.css", "k.json"]:
        assert first[name] == ["x", ""]
    assert first["tools/run"] == ["#!/bin/sh", f"# {NOTICE}"]

The project changes the patterns in its configuration: here it gives HTML a notice and takes Python's away.

def test_notices_from_the_configuration(project):
    project("index.md", "    # in a.py:", "    x", "", "Prose.", "", "    <!-- in b.html: -->", "    <p>")
    Path("literate.json").write_text(json.dumps({"comments": {".html": "<!-- {} -->", ".py": None}}))
    notices, chunks = load().notices, read_chunks(documents())
    assert tangle(chunks, "a.py", notices)[0] == "x\n"
    assert tangle(chunks, "b.html", notices)[0] == f"<!-- {NOTICE} -->\n<p>\n"

--where follows a line of a file back to its document, through the notice and the references.

def test_where_a_line_comes_from(project):
    project("index.md", "    # in a.py:", "    import sys", "    <<more>>", "",
            "Prose.", "", "    # in more:", "    x = 1")
    chunks = read_chunks(documents())
    assert where(chunks, "a.py", 1) is None
    assert where(chunks, "a.py", 2) == "literate/index.md:2"
    assert where(chunks, "a.py", 3) == "literate/index.md:8"
    with pytest.raises(Error, match="has 3 lines"):
        where(chunks, "a.py", 4)
    with pytest.raises(Error, match="not made by the documents"):
        where(chunks, "more", 1)

Writing the files

Checking writes nothing; writing writes what differs, and only that; a script is made executable.

def test_writing_and_checking_the_files(project):
    project("index.md", "    # in tools/run:", "    #!/bin/sh", "    echo", "",
            "Prose.", "", "    # in src/a.py:", "    x = 1")
    chunks = read_chunks(documents())
    assert update(chunks, check=True) == ["tools/run", "src/a.py"]
    assert not Path("tools").exists()
    assert update(chunks) == ["tools/run", "src/a.py"]
    assert os.access("tools/run", os.X_OK)
    assert update(chunks, check=True) == []
    Path("src/a.py").write_text("x = 2\n")
    assert update(chunks, check=True) == ["src/a.py"]

The configuration

Without a file, the defaults, with the name of the folder; a key that is not known, a pattern without its place for the notice, or a file that is not JSON, are errors.

def test_the_configuration(project, tmp_path):
    config = load()
    assert (config.name, config.documents, config.site, config.branch) == (
        tmp_path.name, "literate", "site", "main")
    assert config.notices[".py"] == "# {}"
    for text, error in [('{"nmae": "x"}', "unknown keys nmae"),
                        ('{"comments": {".c": "//"}}', "has no {}"),
                        ("{", "literate.json"), ("[]", "not a JSON object")]:
        Path("literate.json").write_text(text)
        with pytest.raises(Error, match=error):
            load()
    Path("literate.json").write_text('{"name": "x", "documents": "docs"}')
    assert load() == Config(name="x", documents="docs")

The command line

The command line tangles, checks, lists and locates, and reports mistakes with status 1.

def test_the_command_line(project, capsys):
    project("index.md", "    # in a.py:", "    x = 1", "", "Prose.", "", "    # in a chunk:", "    y")
    project("10-more.md", "    # in a.py:", "    <<a chunk>>")
    assert main(["tangle", "--check"]) == 1
    assert "not as the documents say (run literate tangle): a.py" in capsys.readouterr().err
    assert main(["tangle"]) == 0
    assert "wrote a.py" in capsys.readouterr().out
    assert main(["tangle", "--check"]) == 0
    assert main(["tangle", "--list"]) == 0
    assert capsys.readouterr().out == "a.py  (literate/index.md)\n\n<<a chunk>>  index.md:6\n"
    assert main(["tangle", "--where", "a.py:5"]) == 0
    assert capsys.readouterr().out == "literate/index.md:7\n"
    assert main(["tangle", "--where", "a.py:1"]) == 0
    assert capsys.readouterr().out == "a line added by the tangler\n"
    assert main(["tangle", "--where", "a.py"]) == 1
    assert main(["tangle", "--out", "elsewhere"]) == 0
    assert Path("elsewhere/a.py").read_text() == Path("a.py").read_text()

The website

The tests of the weaver need Markdown and Pygments, and are skipped without them. They weave a small project of two documents, with a file, a chunk in three fragments over the two, a reference to a chunk that does not exist, a link between documents and an alert, and look for each piece of the web in the pages.

import re
from pathlib import Path

import pytest

pytest.importorskip("markdown")
pytest.importorskip("pygments")

from literate.cli import main  # noqa: E402
from literate.config import Config  # noqa: E402
from literate.tangle import Error, documents  # noqa: E402
from literate.weave import slug, title_of, weave  # noqa: E402


@pytest.fixture
def site(project):
    project("index.md",
            "Example", "=======", "",
            "See [the next chapter](10-more.md).", "",
            "> [!WARNING]", "> Careful.", "",
            "    # in hello.py:", "    import sys", "", "    <<say hello>>", "",
            "Saying hello.", "",
            "    # in say hello:", "    print('hello')", "",
            "Again.", "",
            "    print('again')", "",
            "Something missing.", "",
            "    # in broken:", "    <<nowhere>>")
    project("10-more.md", "# More", "", "    # in say hello:", "    print('more')")
    Path("logo.svg").write_text("<svg/>")
    config = Config(name="Hello", tagline="a <em>test</em>", repository="https://example.org/hello",
                    logo="logo.svg", logoDark="invert", links={"home": "../"})
    assert weave(config, documents(), Path("site"), branch="dev") == 3
    return {page: Path("site", page).read_text() for page in ["index.html", "10-more.html", "chunks.html"]}


⟨the tests of the weaver⟩

Titles and anchors are made from the headings and the names of chunks.

def test_titles_and_anchors(site):
    assert title_of(Path("literate/index.md")) == "Example"
    assert title_of(Path("literate/10-more.md")) == "More"
    assert slug("say hello") == "say-hello" and slug("src/a.py") == "src-a-py"
    assert "<title>Example · Hello</title>" in site["index.html"]
    for anchor in ['id="hello-py-1"', 'id="say-hello-1"', 'id="say-hello-2"', 'id="broken-1"']:
        assert anchor in site["index.html"]
    assert 'id="say-hello-3"' in site["10-more.html"]

Each fragment is linked to the one before and after it, wherever they are, and to the chunks that use it; a reference is a link, or a red name when nothing defines it; a file links to itself in the repository, on the branch asked for.

def test_the_links_of_the_chunks(site):
    index, more = site["index.html"], site["10-more.html"]
    assert '<a class="ref" href="#say-hello-1">⟨say hello⟩</a>' in index
    assert 'used in <a href="#hello-py-1">⟨hello.py⟩</a>' in index
    assert 'continued <a href="#say-hello-2">further on</a>' in index
    assert 'continues <a href="index.html#say-hello-2">the fragment before</a>' in more
    assert 'used in <a href="index.html#hello-py-1">⟨hello.py⟩</a>' in more
    assert "⟨say hello⟩</a> ≡" in index and "⟨say hello⟩</a> +≡" in index
    assert '<span class="undefined">⟨nowhere⟩</span>' in index
    assert 'href="https://example.org/hello/blob/dev/hello.py"' in index
    assert 'href="10-more.html"' in index
    assert '<blockquote class="alert warning">' in index
    assert "<code>hello.py</code>" in site["chunks.html"]

The header has the logo, the name and the links, the index of chunks marked on its own page; the tagline, as HTML, closes the page; the title of the front page, and only of the front page, has the logo too; the logo and the stylesheet are written with the pages.

def test_the_frame_of_the_pages(site):
    index, more = site["index.html"], site["10-more.html"]
    logo = '<img class="logo invert" src="logo.svg" alt="">'
    assert f'<a class="home" href="index.html">{logo}Hello</a>' in index
    assert "<span>a <em>test</em></span>" in index
    assert ('<a href="../">home</a> <a href="chunks.html">chunks</a> '
            '<a href="https://example.org/hello">source</a>') in more
    assert '<a href="chunks.html" aria-current="page">chunks</a>' in site["chunks.html"]
    assert re.search(r"<h1[^>]*>" + re.escape(logo) + "Example", index)
    assert not re.search(r"<h1[^>]*><img", more)
    assert Path("site/logo.svg").read_text() == "<svg/>"
    assert ".chunk-name" in Path("site/style.css").read_text()

A project without a repository has no links to it; one with an image of its logo for dark backgrounds gets both images; one with a template of its own gets its pages in it, and an error for a placeholder that does not exist.

def test_what_the_project_chooses(project):
    project("index.md", "# Title", "", "    # in a.py:", "    x = 1")
    Path("light.svg").write_text("<svg/>")
    Path("dark.svg").write_text("<svg/>")
    weave(Config(name="P", logo="light.svg", logoDark="dark.svg"), documents(), Path("site"))
    index = Path("site/index.html").read_text()
    assert "repository" not in index and ">source<" not in index
    assert '<picture><source srcset="dark.svg" media="(prefers-color-scheme: dark)">' in index
    assert Path("site/dark.svg").exists()
    Path("mine.html").write_text("{{name}}: {{title}}")
    weave(Config(name="P", template="mine.html"), documents(), Path("site"))
    assert Path("site/index.html").read_text() == "P: Title"
    Path("mine.html").write_text("{{nmae}}")
    with pytest.raises(Error, match="nmae"):
        weave(Config(template="mine.html"), documents(), Path("site"))

literate weave weaves into the folder of the configuration.

def test_weaving_from_the_command_line(project, capsys):
    project("index.md", "# Title", "", "    # in a.py:", "    x = 1")
    Path("literate.json").write_text('{"site": "web"}')
    assert main(["weave"]) == 0
    assert "wove 2 pages into web" in capsys.readouterr().out
    assert Path("web/chunks.html").exists()