1
0
mirror of https://github.com/venthur/blag.git synced 2025-11-25 20:52:43 +00:00

add missing docstrings

This commit is contained in:
Bastian Venthur
2023-09-20 15:09:28 +02:00
parent 4f3516fb19
commit c92130559c
12 changed files with 72 additions and 10 deletions

View File

@@ -1,8 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""blag's core methods. """blag's core methods."""
"""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -32,7 +30,7 @@ logging.basicConfig(
def main(arguments: list[str] | None = None) -> None: def main(arguments: list[str] | None = None) -> None:
"""Main entrypoint for the CLI. """Run the CLI.
This method parses the CLI arguments and executes the respective This method parses the CLI arguments and executes the respective
commands. commands.
@@ -328,7 +326,7 @@ def process_markdown(
for src, dst in convertibles: for src, dst in convertibles:
logger.debug(f"Processing {src}") logger.debug(f"Processing {src}")
with open(f"{input_dir}/{src}", "r") as fh: with open(f"{input_dir}/{src}") as fh:
body = fh.read() body = fh.read()
content, meta = convert_markdown(md, body) content, meta = convert_markdown(md, body)

View File

@@ -94,9 +94,10 @@ def convert_markdown(
class MarkdownLinkTreeprocessor(Treeprocessor): class MarkdownLinkTreeprocessor(Treeprocessor):
"""Converts relative links to .md files to .html""" """Converts relative links to .md files to .html."""
def run(self, root: Element) -> Element: def run(self, root: Element) -> Element:
"""Process the ElementTree."""
for element in root.iter(): for element in root.iter():
if element.tag == "a": if element.tag == "a":
url = element.get("href") url = element.get("href")
@@ -109,6 +110,7 @@ class MarkdownLinkTreeprocessor(Treeprocessor):
return root return root
def convert(self, url: str) -> str: def convert(self, url: str) -> str:
"""Convert relative .md-links to .html-links."""
scheme, netloc, path, query, fragment = urlsplit(url) scheme, netloc, path, query, fragment = urlsplit(url)
logger.debug( logger.debug(
f"{url}: {scheme=} {netloc=} {path=} {query=} {fragment=}" f"{url}: {scheme=} {netloc=} {path=} {query=} {fragment=}"
@@ -126,6 +128,7 @@ class MarkdownLinkExtension(Extension):
"""markdown.extension that converts relative .md- to .html-links.""" """markdown.extension that converts relative .md- to .html-links."""
def extendMarkdown(self, md: Markdown) -> None: def extendMarkdown(self, md: Markdown) -> None:
"""Register the MarkdownLinkTreeprocessor."""
md.treeprocessors.register( md.treeprocessors.register(
MarkdownLinkTreeprocessor(md), MarkdownLinkTreeprocessor(md),
"mdlink", "mdlink",

View File

@@ -1,6 +1,4 @@
"""Helper methods for blag's quickstart command. """Helper methods for blag's quickstart command."""
"""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations

View File

@@ -1 +1,3 @@
"""Version information for the blag package."""
__VERSION__ = "2.1.0" __VERSION__ = "2.1.0"

View File

@@ -0,0 +1 @@
"""Tests for blag."""

View File

@@ -1,3 +1,6 @@
"""Pytest fixtures."""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -14,6 +17,7 @@ from blag import blag, quickstart
@pytest.fixture @pytest.fixture
def environment(cleandir: str) -> Iterator[Environment]: def environment(cleandir: str) -> Iterator[Environment]:
"""Create a Jinja2 environment."""
site = { site = {
"base_url": "site base_url", "base_url": "site base_url",
"title": "site title", "title": "site title",
@@ -26,31 +30,37 @@ def environment(cleandir: str) -> Iterator[Environment]:
@pytest.fixture @pytest.fixture
def page_template(environment: Environment) -> Iterator[Template]: def page_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 page-template."""
yield environment.get_template("page.html") yield environment.get_template("page.html")
@pytest.fixture @pytest.fixture
def article_template(environment: Environment) -> Iterator[Template]: def article_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 article-template."""
yield environment.get_template("article.html") yield environment.get_template("article.html")
@pytest.fixture @pytest.fixture
def index_template(environment: Environment) -> Iterator[Template]: def index_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 index-template."""
yield environment.get_template("index.html") yield environment.get_template("index.html")
@pytest.fixture @pytest.fixture
def archive_template(environment: Environment) -> Iterator[Template]: def archive_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 archive-template."""
yield environment.get_template("archive.html") yield environment.get_template("archive.html")
@pytest.fixture @pytest.fixture
def tags_template(environment: Environment) -> Iterator[Template]: def tags_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 tags-template."""
yield environment.get_template("tags.html") yield environment.get_template("tags.html")
@pytest.fixture @pytest.fixture
def tag_template(environment: Environment) -> Iterator[Template]: def tag_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 tag-template."""
yield environment.get_template("tag.html") yield environment.get_template("tag.html")
@@ -80,6 +90,7 @@ author = a. u. thor
@pytest.fixture @pytest.fixture
def args(cleandir: Callable[[], Iterator[str]]) -> Iterator[Namespace]: def args(cleandir: Callable[[], Iterator[str]]) -> Iterator[Namespace]:
"""Create a Namespace with default arguments."""
args = Namespace( args = Namespace(
input_dir="content", input_dir="content",
output_dir="build", output_dir="build",

View File

@@ -1,3 +1,6 @@
"""Test blag."""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -15,12 +18,14 @@ from blag import __VERSION__, blag
def test_generate_feed(cleandir: str) -> None: def test_generate_feed(cleandir: str) -> None:
"""Test generate_feed."""
articles: list[tuple[str, dict[str, Any]]] = [] articles: list[tuple[str, dict[str, Any]]] = []
blag.generate_feed(articles, "build", " ", " ", " ", " ") blag.generate_feed(articles, "build", " ", " ", " ", " ")
assert os.path.exists("build/atom.xml") assert os.path.exists("build/atom.xml")
def test_feed(cleandir: str) -> None: def test_feed(cleandir: str) -> None:
"""Test feed."""
articles: list[tuple[str, dict[str, Any]]] = [ articles: list[tuple[str, dict[str, Any]]] = [
( (
"dest1.html", "dest1.html",
@@ -73,6 +78,7 @@ def test_feed(cleandir: str) -> None:
def test_generate_feed_with_description(cleandir: str) -> None: def test_generate_feed_with_description(cleandir: str) -> None:
"""Test generate_feed with description."""
# if a description is provided, it will be used as the summary in # if a description is provided, it will be used as the summary in
# the feed, otherwise we simply use the title of the article # the feed, otherwise we simply use the title of the article
articles: list[tuple[str, dict[str, Any]]] = [ articles: list[tuple[str, dict[str, Any]]] = [
@@ -98,6 +104,7 @@ def test_generate_feed_with_description(cleandir: str) -> None:
def test_parse_args_build() -> None: def test_parse_args_build() -> None:
"""Test parse_args with build."""
# test default args # test default args
args = blag.parse_args(["build"]) args = blag.parse_args(["build"])
assert args.input_dir == "content" assert args.input_dir == "content"
@@ -131,6 +138,7 @@ def test_parse_args_build() -> None:
def test_get_config() -> None: def test_get_config() -> None:
"""Test get_config."""
config = """ config = """
[main] [main]
base_url = https://example.com/ base_url = https://example.com/
@@ -180,6 +188,7 @@ author = a. u. thor
def test_environment_factory(cleandir: str) -> None: def test_environment_factory(cleandir: str) -> None:
"""Test environment_factory."""
globals_: dict[str, object] = {"foo": "bar", "test": "me"} globals_: dict[str, object] = {"foo": "bar", "test": "me"}
env = blag.environment_factory("templates", globals_=globals_) env = blag.environment_factory("templates", globals_=globals_)
assert env.globals["foo"] == "bar" assert env.globals["foo"] == "bar"
@@ -191,6 +200,7 @@ def test_process_markdown(
page_template: Template, page_template: Template,
article_template: Template, article_template: Template,
) -> None: ) -> None:
"""Test process_markdown."""
page1 = """\ page1 = """\
title: some page title: some page
@@ -240,6 +250,7 @@ foo bar
def test_build(args: Namespace) -> None: def test_build(args: Namespace) -> None:
"""Test build."""
page1 = """\ page1 = """\
title: some page title: some page
@@ -313,16 +324,19 @@ foo bar
], ],
) )
def test_missing_template_raises(template: str, args: Namespace) -> None: def test_missing_template_raises(template: str, args: Namespace) -> None:
"""Test that missing templates raise SystemExit."""
os.remove(f"templates/{template}") os.remove(f"templates/{template}")
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
blag.build(args) blag.build(args)
def test_main(cleandir: str) -> None: def test_main(cleandir: str) -> None:
"""Test main."""
blag.main(["build"]) blag.main(["build"])
def test_cli_version(capsys: CaptureFixture[str]) -> None: def test_cli_version(capsys: CaptureFixture[str]) -> None:
"""Test --version."""
with pytest.raises(SystemExit) as ex: with pytest.raises(SystemExit) as ex:
blag.main(["--version"]) blag.main(["--version"])
# normal system exit # normal system exit
@@ -333,6 +347,7 @@ def test_cli_version(capsys: CaptureFixture[str]) -> None:
def test_cli_verbose(cleandir: str, caplog: LogCaptureFixture) -> None: def test_cli_verbose(cleandir: str, caplog: LogCaptureFixture) -> None:
"""Test --verbose."""
blag.main(["build"]) blag.main(["build"])
assert "DEBUG" not in caplog.text assert "DEBUG" not in caplog.text

View File

@@ -1,3 +1,6 @@
"""Tests for the devserver module."""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -11,6 +14,7 @@ from blag import devserver
def test_get_last_modified(cleandir: str) -> None: def test_get_last_modified(cleandir: str) -> None:
"""Test get_last_modified."""
# take initial time # take initial time
t1 = devserver.get_last_modified(["content"]) t1 = devserver.get_last_modified(["content"])
@@ -29,6 +33,7 @@ def test_get_last_modified(cleandir: str) -> None:
def test_autoreload_builds_immediately(args: Namespace) -> None: def test_autoreload_builds_immediately(args: Namespace) -> None:
"""Test autoreload builds immediately."""
# create a dummy file that can be build # create a dummy file that can be build
with open("content/test.md", "w") as fh: with open("content/test.md", "w") as fh:
fh.write("boo") fh.write("boo")
@@ -54,6 +59,7 @@ def test_autoreload_builds_immediately(args: Namespace) -> None:
"ignore::pytest.PytestUnhandledThreadExceptionWarning" "ignore::pytest.PytestUnhandledThreadExceptionWarning"
) )
def test_autoreload(args: Namespace) -> None: def test_autoreload(args: Namespace) -> None:
"""Test autoreload."""
t = threading.Thread( t = threading.Thread(
target=devserver.autoreload, target=devserver.autoreload,
args=(args,), args=(args,),

View File

@@ -1,3 +1,6 @@
"""Test markdown module."""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -34,6 +37,7 @@ from blag.markdown import convert_markdown, markdown_factory
], ],
) )
def test_convert_markdown_links(input_: str, expected: str) -> None: def test_convert_markdown_links(input_: str, expected: str) -> None:
"""Test convert_markdown."""
md = markdown_factory() md = markdown_factory()
html, _ = convert_markdown(md, input_) html, _ = convert_markdown(md, input_)
assert expected in html assert expected in html
@@ -51,6 +55,7 @@ def test_convert_markdown_links(input_: str, expected: str) -> None:
], ],
) )
def test_dont_convert_normal_links(input_: str, expected: str) -> None: def test_dont_convert_normal_links(input_: str, expected: str) -> None:
"""Test convert_markdown doesn't convert normal links."""
md = markdown_factory() md = markdown_factory()
html, _ = convert_markdown(md, input_) html, _ = convert_markdown(md, input_)
assert expected in html assert expected in html
@@ -70,17 +75,20 @@ def test_dont_convert_normal_links(input_: str, expected: str) -> None:
], ],
) )
def test_convert_metadata(input_: str, expected: dict[str, Any]) -> None: def test_convert_metadata(input_: str, expected: dict[str, Any]) -> None:
"""Test convert_markdown converts metadata correctly."""
md = markdown_factory() md = markdown_factory()
_, meta = convert_markdown(md, input_) _, meta = convert_markdown(md, input_)
assert expected == meta assert expected == meta
def test_markdown_factory() -> None: def test_markdown_factory() -> None:
"""Test markdown_factory."""
md = markdown_factory() md = markdown_factory()
assert isinstance(md, markdown.Markdown) assert isinstance(md, markdown.Markdown)
def test_smarty() -> None: def test_smarty() -> None:
"""Test smarty."""
md = markdown_factory() md = markdown_factory()
md1 = """ md1 = """
@@ -95,6 +103,7 @@ this --- is -- a test ...
def test_smarty_code() -> None: def test_smarty_code() -> None:
"""Test smarty doesn't touch code."""
md = markdown_factory() md = markdown_factory()
md1 = """ md1 = """

View File

@@ -1,3 +1,6 @@
"""Tests for the quickstart module."""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -9,21 +12,24 @@ from blag.quickstart import get_input, quickstart
def test_get_input_default_answer(monkeypatch: MonkeyPatch) -> None: def test_get_input_default_answer(monkeypatch: MonkeyPatch) -> None:
"""Test get_input with default answer."""
monkeypatch.setattr("builtins.input", lambda x: "") monkeypatch.setattr("builtins.input", lambda x: "")
answer = get_input("foo", "bar") answer = get_input("foo", "bar")
assert answer == "bar" assert answer == "bar"
def test_get_input(monkeypatch: MonkeyPatch) -> None: def test_get_input(monkeypatch: MonkeyPatch) -> None:
"""Test get_input."""
monkeypatch.setattr("builtins.input", lambda x: "baz") monkeypatch.setattr("builtins.input", lambda x: "baz")
answer = get_input("foo", "bar") answer = get_input("foo", "bar")
assert answer == "baz" assert answer == "baz"
def test_quickstart(cleandir: str, monkeypatch: MonkeyPatch) -> None: def test_quickstart(cleandir: str, monkeypatch: MonkeyPatch) -> None:
"""Test quickstart."""
monkeypatch.setattr("builtins.input", lambda x: "foo") monkeypatch.setattr("builtins.input", lambda x: "foo")
quickstart(None) quickstart(None)
with open("config.ini", "r") as fh: with open("config.ini") as fh:
data = fh.read() data = fh.read()
assert "base_url = foo" in data assert "base_url = foo" in data
assert "title = foo" in data assert "title = foo" in data

View File

@@ -1,3 +1,6 @@
"""Test the templates."""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -7,6 +10,7 @@ from jinja2 import Template
def test_page(page_template: Template) -> None: def test_page(page_template: Template) -> None:
"""Test the page template."""
ctx = { ctx = {
"content": "this is the content", "content": "this is the content",
"title": "this is the title", "title": "this is the title",
@@ -17,6 +21,7 @@ def test_page(page_template: Template) -> None:
def test_article(article_template: Template) -> None: def test_article(article_template: Template) -> None:
"""Test the article template."""
ctx = { ctx = {
"content": "this is the content", "content": "this is the content",
"title": "this is the title", "title": "this is the title",
@@ -29,6 +34,7 @@ def test_article(article_template: Template) -> None:
def test_index(index_template: Template) -> None: def test_index(index_template: Template) -> None:
"""Test the index template."""
entry = { entry = {
"title": "this is a title", "title": "this is a title",
"dst": "https://example.com/link", "dst": "https://example.com/link",
@@ -49,6 +55,7 @@ def test_index(index_template: Template) -> None:
def test_archive(archive_template: Template) -> None: def test_archive(archive_template: Template) -> None:
"""Test the archive template."""
entry = { entry = {
"title": "this is a title", "title": "this is a title",
"dst": "https://example.com/link", "dst": "https://example.com/link",
@@ -67,6 +74,7 @@ def test_archive(archive_template: Template) -> None:
def test_tags(tags_template: Template) -> None: def test_tags(tags_template: Template) -> None:
"""Test the tags template."""
tags = [("foo", 42)] tags = [("foo", 42)]
ctx = { ctx = {
"tags": tags, "tags": tags,
@@ -80,6 +88,7 @@ def test_tags(tags_template: Template) -> None:
def test_tag(tag_template: Template) -> None: def test_tag(tag_template: Template) -> None:
"""Test the tag template."""
entry = { entry = {
"title": "this is a title", "title": "this is a title",
"dst": "https://example.com/link", "dst": "https://example.com/link",

View File

@@ -1,3 +1,6 @@
"""Test the version module."""
# remove when we don't support py38 anymore # remove when we don't support py38 anymore
from __future__ import annotations from __future__ import annotations
@@ -5,4 +8,5 @@ import blag
def test_version() -> None: def test_version() -> None:
"""Test the version of the package."""
assert isinstance(blag.__VERSION__, str) assert isinstance(blag.__VERSION__, str)