Merge branch 'master' into delete_extra_files

This commit is contained in:
Bastian Venthur
2023-11-12 17:23:48 +01:00
63 changed files with 2115 additions and 1123 deletions

View File

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

View File

@@ -1,53 +1,72 @@
from tempfile import TemporaryDirectory
"""Pytest fixtures."""
# remove when we don't support py38 anymore
from __future__ import annotations
import os
from argparse import Namespace
from tempfile import TemporaryDirectory
from typing import Callable, Iterator
import pytest
from jinja2 import Environment, Template
from blag import blag
from blag import blag, quickstart
@pytest.fixture
def environment():
def environment(cleandir: str) -> Iterator[Environment]:
"""Create a Jinja2 environment."""
site = {
'base_url': 'site base_url',
'title': 'site title',
'description': 'site description',
'author': 'site author',
"base_url": "site base_url",
"title": "site title",
"description": "site description",
"author": "site author",
}
env = blag.environment_factory(globals_=dict(site=site))
env = blag.environment_factory("templates", globals_=dict(site=site))
yield env
@pytest.fixture
def page_template(environment):
yield environment.get_template('page.html')
def page_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 page-template."""
yield environment.get_template("page.html")
@pytest.fixture
def article_template(environment):
yield environment.get_template('article.html')
def article_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 article-template."""
yield environment.get_template("article.html")
@pytest.fixture
def archive_template(environment):
yield environment.get_template('archive.html')
def index_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 index-template."""
yield environment.get_template("index.html")
@pytest.fixture
def tags_template(environment):
yield environment.get_template('tags.html')
def archive_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 archive-template."""
yield environment.get_template("archive.html")
@pytest.fixture
def tag_template(environment):
yield environment.get_template('tag.html')
def tags_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 tags-template."""
yield environment.get_template("tags.html")
@pytest.fixture
def cleandir():
"""Create a temporary workind directory and cwd.
def tag_template(environment: Environment) -> Iterator[Template]:
"""Create a Jinja2 tag-template."""
yield environment.get_template("tag.html")
"""
@pytest.fixture
def cleandir() -> Iterator[str]:
"""Create a temporary working directory and cwd."""
config = """
[main]
base_url = https://example.com/
@@ -57,30 +76,25 @@ author = a. u. thor
"""
with TemporaryDirectory() as dir:
for d in 'content', 'build', 'static', 'templates':
os.mkdir(f'{dir}/{d}')
with open(f'{dir}/config.ini', 'w') as fh:
os.mkdir(f"{dir}/build")
with open(f"{dir}/config.ini", "w") as fh:
fh.write(config)
# change directory
old_cwd = os.getcwd()
os.chdir(dir)
quickstart.copy_default_theme()
yield dir
# and change back afterwards
os.chdir(old_cwd)
@pytest.fixture
def args(cleandir):
class NameSpace:
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
args = NameSpace(
input_dir='content',
output_dir='build',
static_dir='static',
template_dir='templates',
def args(cleandir: Callable[[], Iterator[str]]) -> Iterator[Namespace]:
"""Create a Namespace with default arguments."""
args = Namespace(
input_dir="content",
output_dir="build",
static_dir="static",
template_dir="templates",
)
yield args

View File

@@ -1,122 +1,144 @@
from tempfile import TemporaryDirectory
"""Test blag."""
# remove when we don't support py38 anymore
from __future__ import annotations
import os
from argparse import Namespace
from datetime import datetime
from tempfile import TemporaryDirectory
from typing import Any
import pytest
from jinja2 import Template
from pytest import CaptureFixture, LogCaptureFixture
from blag import blag
from blag import __VERSION__, blag
def test_generate_feed(cleandir):
articles = []
blag.generate_feed(articles, 'build', ' ', ' ', ' ', ' ')
assert os.path.exists('build/atom.xml')
def test_generate_feed(cleandir: str) -> None:
"""Test generate_feed."""
articles: list[tuple[str, dict[str, Any]]] = []
blag.generate_feed(articles, "build", " ", " ", " ", " ")
assert os.path.exists("build/atom.xml")
def test_feed(cleandir):
articles = [
[
'dest1.html',
def test_feed(cleandir: str) -> None:
"""Test feed."""
articles: list[tuple[str, dict[str, Any]]] = [
(
"dest1.html",
{
'title': 'title1',
'date': datetime(2019, 6, 6),
'content': 'content1',
}
],
[
'dest2.html',
"title": "title1",
"date": datetime(2019, 6, 6),
"content": "content1",
},
),
(
"dest2.html",
{
'title': 'title2',
'date': datetime(1980, 5, 9),
'content': 'content2',
}
],
"title": "title2",
"date": datetime(1980, 5, 9),
"content": "content2",
},
),
]
blag.generate_feed(articles, 'build', 'https://example.com/',
'blog title', 'blog description', 'blog author')
with open('build/atom.xml') as fh:
blag.generate_feed(
articles,
"build",
"https://example.com/",
"blog title",
"blog description",
"blog author",
)
with open("build/atom.xml") as fh:
feed = fh.read()
assert '<title>blog title</title>' in feed
assert "<title>blog title</title>" in feed
# enable when https://github.com/getpelican/feedgenerator/issues/22
# is fixed
# assert '<subtitle>blog description</subtitle>' in feed
assert '<author><name>blog author</name></author>' in feed
assert "<author><name>blog author</name></author>" in feed
# article 1
assert '<title>title1</title>' in feed
assert "<title>title1</title>" in feed
assert '<summary type="html">title1' in feed
assert '<published>2019-06-06' in feed
assert "<published>2019-06-06" in feed
assert '<content type="html">content1' in feed
assert '<link href="https://example.com/dest1.html"' in feed
# article 2
assert '<title>title2</title>' in feed
assert "<title>title2</title>" in feed
assert '<summary type="html">title2' in feed
assert '<published>1980-05-09' in feed
assert "<published>1980-05-09" in feed
assert '<content type="html">content2' in feed
assert '<link href="https://example.com/dest2.html"' in feed
def test_generate_feed_with_description(cleandir):
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
# the feed, otherwise we simply use the title of the article
articles = [[
'dest.html',
{
'title': 'title',
'description': 'description',
'date': datetime(2019, 6, 6),
'content': 'content',
}
]]
blag.generate_feed(articles, 'build', ' ', ' ', ' ', ' ')
articles: list[tuple[str, dict[str, Any]]] = [
(
"dest.html",
{
"title": "title",
"description": "description",
"date": datetime(2019, 6, 6),
"content": "content",
},
)
]
blag.generate_feed(articles, "build", " ", " ", " ", " ")
with open('build/atom.xml') as fh:
with open("build/atom.xml") as fh:
feed = fh.read()
assert '<title>title</title>' in feed
assert "<title>title</title>" in feed
assert '<summary type="html">description' in feed
assert '<published>2019-06-06' in feed
assert "<published>2019-06-06" in feed
assert '<content type="html">content' in feed
def test_parse_args_build():
def test_parse_args_build() -> None:
"""Test parse_args with build."""
# test default args
args = blag.parse_args(['build'])
assert args.input_dir == 'content'
assert args.output_dir == 'build'
assert args.template_dir == 'templates'
assert args.static_dir == 'static'
args = blag.parse_args(["build"])
assert args.input_dir == "content"
assert args.output_dir == "build"
assert args.template_dir == "templates"
assert args.static_dir == "static"
# input dir
args = blag.parse_args(['build', '-i', 'foo'])
assert args.input_dir == 'foo'
args = blag.parse_args(['build', '--input-dir', 'foo'])
assert args.input_dir == 'foo'
args = blag.parse_args(["build", "-i", "foo"])
assert args.input_dir == "foo"
args = blag.parse_args(["build", "--input-dir", "foo"])
assert args.input_dir == "foo"
# output dir
args = blag.parse_args(['build', '-o', 'foo'])
assert args.output_dir == 'foo'
args = blag.parse_args(['build', '--output-dir', 'foo'])
assert args.output_dir == 'foo'
args = blag.parse_args(["build", "-o", "foo"])
assert args.output_dir == "foo"
args = blag.parse_args(["build", "--output-dir", "foo"])
assert args.output_dir == "foo"
# template dir
args = blag.parse_args(['build', '-t', 'foo'])
assert args.template_dir == 'foo'
args = blag.parse_args(['build', '--template-dir', 'foo'])
assert args.template_dir == 'foo'
args = blag.parse_args(["build", "-t", "foo"])
assert args.template_dir == "foo"
args = blag.parse_args(["build", "--template-dir", "foo"])
assert args.template_dir == "foo"
# static dir
args = blag.parse_args(['build', '-s', 'foo'])
assert args.static_dir == 'foo'
args = blag.parse_args(['build', '--static-dir', 'foo'])
assert args.static_dir == 'foo'
args = blag.parse_args(["build", "-s", "foo"])
assert args.static_dir == "foo"
args = blag.parse_args(["build", "--static-dir", "foo"])
assert args.static_dir == "foo"
def test_get_config():
def test_get_config() -> None:
"""Test get_config."""
config = """
[main]
base_url = https://example.com/
@@ -126,25 +148,24 @@ author = a. u. thor
"""
# happy path
with TemporaryDirectory() as dir:
configfile = f'{dir}/config.ini'
with open(configfile, 'w') as fh:
configfile = f"{dir}/config.ini"
with open(configfile, "w") as fh:
fh.write(config)
config_parsed = blag.get_config(configfile)
assert config_parsed['base_url'] == 'https://example.com/'
assert config_parsed['title'] == 'title'
assert config_parsed['description'] == 'description'
assert config_parsed['author'] == 'a. u. thor'
assert config_parsed["base_url"] == "https://example.com/"
assert config_parsed["title"] == "title"
assert config_parsed["description"] == "description"
assert config_parsed["author"] == "a. u. thor"
# a missing required config causes a sys.exit
for x in 'base_url', 'title', 'description', 'author':
config2 = '\n'.join([line
for line
in config.splitlines()
if not line.startswith(x)])
for x in "base_url", "title", "description", "author":
config2 = "\n".join(
[line for line in config.splitlines() if not line.startswith(x)]
)
with TemporaryDirectory() as dir:
configfile = f'{dir}/config.ini'
with open(configfile, 'w') as fh:
configfile = f"{dir}/config.ini"
with open(configfile, "w") as fh:
fh.write(config2)
with pytest.raises(SystemExit):
config_parsed = blag.get_config(configfile)
@@ -158,25 +179,28 @@ description = description
author = a. u. thor
"""
with TemporaryDirectory() as dir:
configfile = f'{dir}/config.ini'
with open(configfile, 'w') as fh:
configfile = f"{dir}/config.ini"
with open(configfile, "w") as fh:
fh.write(config)
config_parsed = blag.get_config(configfile)
assert config_parsed['base_url'] == 'https://example.com/'
assert config_parsed["base_url"] == "https://example.com/"
def test_environment_factory():
globals_ = {
'foo': 'bar',
'test': 'me'
}
env = blag.environment_factory(globals_=globals_)
assert env.globals['foo'] == 'bar'
assert env.globals['test'] == 'me'
def test_environment_factory(cleandir: str) -> None:
"""Test environment_factory."""
globals_: dict[str, object] = {"foo": "bar", "test": "me"}
env = blag.environment_factory("templates", globals_=globals_)
assert env.globals["foo"] == "bar"
assert env.globals["test"] == "me"
def test_process_markdown(cleandir, page_template, article_template):
def test_process_markdown(
cleandir: str,
page_template: Template,
article_template: Template,
) -> None:
"""Test process_markdown."""
page1 = """\
title: some page
@@ -202,17 +226,12 @@ foo bar
convertibles = []
for i, txt in enumerate((page1, article1, article2)):
i = str(i)
with open(f'content/{i}', 'w') as fh:
with open(f"content/{str(i)}", "w") as fh:
fh.write(txt)
convertibles.append([i, i])
convertibles.append((str(i), str(i)))
articles, pages = blag.process_markdown(
convertibles,
'content',
'build',
page_template,
article_template
convertibles, "content", "build", page_template, article_template
)
assert isinstance(articles, list)
@@ -220,17 +239,18 @@ foo bar
for dst, context in articles:
assert isinstance(dst, str)
assert isinstance(context, dict)
assert 'content' in context
assert "content" in context
assert isinstance(pages, list)
assert len(pages) == 1
for dst, context in pages:
assert isinstance(dst, str)
assert isinstance(context, dict)
assert 'content' in context
assert "content" in context
def test_build(args):
def test_build(args: Namespace) -> None:
"""Test build."""
page1 = """\
title: some page
@@ -259,39 +279,41 @@ foo bar
# write some convertibles
convertibles = []
for i, txt in enumerate((page1, article1, article2)):
i = str(i)
with open(f'{args.input_dir}/{i}.md', 'w') as fh:
with open(f"{args.input_dir}/{str(i)}.md", "w") as fh:
fh.write(txt)
convertibles.append([i, i])
convertibles.append((str(i), str(i)))
# some static files
with open(f'{args.static_dir}/test', 'w') as fh:
fh.write('hello')
with open(f"{args.static_dir}/test", "w") as fh:
fh.write("hello")
os.mkdir(f'{args.input_dir}/testdir')
with open(f'{args.input_dir}/testdir/test', 'w') as fh:
fh.write('hello')
os.mkdir(f"{args.input_dir}/testdir")
with open(f"{args.input_dir}/testdir/test", "w") as fh:
fh.write("hello")
blag.build(args)
# test existence of the three converted files
for i in range(3):
assert os.path.exists(f'{args.output_dir}/{i}.html')
assert os.path.exists(f"{args.output_dir}/{i}.html")
# ... static file
assert os.path.exists(f'{args.output_dir}/test')
assert os.path.exists(f"{args.output_dir}/test")
# ... directory
assert os.path.exists(f'{args.output_dir}/testdir/test')
assert os.path.exists(f"{args.output_dir}/testdir/test")
# ... feed
assert os.path.exists(f'{args.output_dir}/atom.xml')
assert os.path.exists(f"{args.output_dir}/atom.xml")
# ... index
assert os.path.exists(f"{args.output_dir}/index.html")
# ... archive
assert os.path.exists(f'{args.output_dir}/index.html')
assert os.path.exists(f"{args.output_dir}/archive.html")
# ... tags
assert os.path.exists(f'{args.output_dir}/tags/index.html')
assert os.path.exists(f'{args.output_dir}/tags/foo.html')
assert os.path.exists(f'{args.output_dir}/tags/bar.html')
assert os.path.exists(f"{args.output_dir}/tags/index.html")
assert os.path.exists(f"{args.output_dir}/tags/foo.html")
assert os.path.exists(f"{args.output_dir}/tags/bar.html")
def test_remove_extra_files(args):
"""Test that extra files are removed."""
# create a file and directory in output dir that have no corresponding
# source
file_path = f'{args.output_dir}/a'
@@ -306,23 +328,44 @@ def test_remove_extra_files(args):
assert not os.path.exists(dir_path)
def test_main(cleandir):
blag.main(['build'])
@pytest.mark.parametrize(
"template",
[
"page.html",
"article.html",
"index.html",
"archive.html",
"tags.html",
"tag.html",
],
)
def test_missing_template_raises(template: str, args: Namespace) -> None:
"""Test that missing templates raise SystemExit."""
os.remove(f"templates/{template}")
with pytest.raises(SystemExit):
blag.build(args)
def test_cli_version(capsys):
def test_main(cleandir: str) -> None:
"""Test main."""
blag.main(["build"])
def test_cli_version(capsys: CaptureFixture[str]) -> None:
"""Test --version."""
with pytest.raises(SystemExit) as ex:
blag.main(['--version'])
blag.main(["--version"])
# normal system exit
assert ex.value.code == 0
# proper version reported
out, _ = capsys.readouterr()
assert blag.__VERSION__ in out
assert __VERSION__ in out
def test_cli_verbose(cleandir, caplog):
blag.main(['build'])
assert 'DEBUG' not in caplog.text
def test_cli_verbose(cleandir: str, caplog: LogCaptureFixture) -> None:
"""Test --verbose."""
blag.main(["build"])
assert "DEBUG" not in caplog.text
blag.main(['--verbose', 'build'])
assert 'DEBUG' in caplog.text
blag.main(["--verbose", "build"])
assert "DEBUG" in caplog.text

View File

@@ -1,66 +1,82 @@
import time
"""Tests for the devserver module."""
# remove when we don't support py38 anymore
from __future__ import annotations
import threading
import time
from argparse import Namespace
import pytest
from blag import devserver
def test_get_last_modified(cleandir):
def test_get_last_modified(cleandir: str) -> None:
"""Test get_last_modified."""
# take initial time
t1 = devserver.get_last_modified(['content'])
t1 = devserver.get_last_modified(["content"])
# wait a bit, create a file and measure again
time.sleep(0.1)
with open('content/test', 'w') as fh:
fh.write('boo')
t2 = devserver.get_last_modified(['content'])
with open("content/test", "w") as fh:
fh.write("boo")
t2 = devserver.get_last_modified(["content"])
# wait a bit and take time again
time.sleep(0.1)
t3 = devserver.get_last_modified(['content'])
t3 = devserver.get_last_modified(["content"])
assert t2 > t1
assert t2 == t3
def test_autoreload_builds_immediately(args):
def test_autoreload_builds_immediately(args: Namespace) -> None:
"""Test autoreload builds immediately."""
# create a dummy file that can be build
with open('content/test.md', 'w') as fh:
fh.write('boo')
with open("content/test.md", "w") as fh:
fh.write("boo")
t = threading.Thread(target=devserver.autoreload,
args=(args, ),
daemon=True,)
t0 = devserver.get_last_modified(['build'])
t = threading.Thread(
target=devserver.autoreload,
args=(args,),
daemon=True,
)
t0 = devserver.get_last_modified(["build"])
t.start()
# try for 5 seconds...
for i in range(5):
time.sleep(1)
t1 = devserver.get_last_modified(['build'])
t1 = devserver.get_last_modified(["build"])
print(t1)
if t1 > t0:
break
assert t1 > t0
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") # noqa
def test_autoreload(args):
t = threading.Thread(target=devserver.autoreload,
args=(args, ),
daemon=True,)
@pytest.mark.filterwarnings(
"ignore::pytest.PytestUnhandledThreadExceptionWarning"
)
def test_autoreload(args: Namespace) -> None:
"""Test autoreload."""
t = threading.Thread(
target=devserver.autoreload,
args=(args,),
daemon=True,
)
t.start()
t0 = devserver.get_last_modified(['build'])
t0 = devserver.get_last_modified(["build"])
# create a dummy file that can be build
with open('content/test.md', 'w') as fh:
fh.write('boo')
with open("content/test.md", "w") as fh:
fh.write("boo")
# try for 5 seconds to see if we rebuild once...
for i in range(5):
time.sleep(1)
t1 = devserver.get_last_modified(['build'])
t1 = devserver.get_last_modified(["build"])
if t1 > t0:
break
assert t1 > t0

View File

@@ -1,71 +1,94 @@
from datetime import datetime
"""Test markdown module."""
# remove when we don't support py38 anymore
from __future__ import annotations
from datetime import datetime
from typing import Any
import pytest
import markdown
import pytest
from blag.markdown import convert_markdown, markdown_factory
@pytest.mark.parametrize("input_, expected", [
# inline
('[test](test.md)', 'test.html'),
('[test](test.md "test")', 'test.html'),
('[test](a/test.md)', 'a/test.html'),
('[test](a/test.md "test")', 'a/test.html'),
('[test](/test.md)', '/test.html'),
('[test](/test.md "test")', '/test.html'),
('[test](/a/test.md)', '/a/test.html'),
('[test](/a/test.md "test")', '/a/test.html'),
# reference
('[test][]\n[test]: test.md ''', 'test.html'),
('[test][]\n[test]: test.md "test"', 'test.html'),
('[test][]\n[test]: a/test.md', 'a/test.html'),
('[test][]\n[test]: a/test.md "test"', 'a/test.html'),
('[test][]\n[test]: /test.md', '/test.html'),
('[test][]\n[test]: /test.md "test"', '/test.html'),
('[test][]\n[test]: /a/test.md', '/a/test.html'),
('[test][]\n[test]: /a/test.md "test"', '/a/test.html'),
])
def test_convert_markdown_links(input_, expected):
@pytest.mark.parametrize(
"input_, expected",
[
# inline
("[test](test.md)", "test.html"),
('[test](test.md "test")', "test.html"),
("[test](a/test.md)", "a/test.html"),
('[test](a/test.md "test")', "a/test.html"),
("[test](/test.md)", "/test.html"),
('[test](/test.md "test")', "/test.html"),
("[test](/a/test.md)", "/a/test.html"),
('[test](/a/test.md "test")', "/a/test.html"),
# reference
("[test][]\n[test]: test.md " "", "test.html"),
('[test][]\n[test]: test.md "test"', "test.html"),
("[test][]\n[test]: a/test.md", "a/test.html"),
('[test][]\n[test]: a/test.md "test"', "a/test.html"),
("[test][]\n[test]: /test.md", "/test.html"),
('[test][]\n[test]: /test.md "test"', "/test.html"),
("[test][]\n[test]: /a/test.md", "/a/test.html"),
('[test][]\n[test]: /a/test.md "test"', "/a/test.html"),
],
)
def test_convert_markdown_links(input_: str, expected: str) -> None:
"""Test convert_markdown."""
md = markdown_factory()
html, _ = convert_markdown(md, input_)
assert expected in html
@pytest.mark.parametrize("input_, expected", [
# scheme
('[test](https://)', 'https://'),
# netloc
('[test](//test.md)', '//test.md'),
# no path
('[test]()', ''),
])
def test_dont_convert_normal_links(input_, expected):
@pytest.mark.parametrize(
"input_, expected",
[
# scheme
("[test](https://)", "https://"),
# netloc
("[test](//test.md)", "//test.md"),
# no path
("[test]()", ""),
],
)
def test_dont_convert_normal_links(input_: str, expected: str) -> None:
"""Test convert_markdown doesn't convert normal links."""
md = markdown_factory()
html, _ = convert_markdown(md, input_)
assert expected in html
@pytest.mark.parametrize("input_, expected", [
('foo: bar', {'foo': 'bar'}),
('foo: those are several words', {'foo': 'those are several words'}),
('tags: this, is, a, test\n', {'tags': ['this', 'is', 'a', 'test']}),
('tags: this, IS, a, test', {'tags': ['this', 'is', 'a', 'test']}),
('date: 2020-01-01 12:10', {'date':
datetime(2020, 1, 1, 12, 10).astimezone()}),
])
def test_convert_metadata(input_, expected):
@pytest.mark.parametrize(
"input_, expected",
[
("foo: bar", {"foo": "bar"}),
("foo: those are several words", {"foo": "those are several words"}),
("tags: this, is, a, test\n", {"tags": ["this", "is", "a", "test"]}),
("tags: this, IS, a, test", {"tags": ["this", "is", "a", "test"]}),
(
"date: 2020-01-01 12:10",
{"date": datetime(2020, 1, 1, 12, 10).astimezone()},
),
],
)
def test_convert_metadata(input_: str, expected: dict[str, Any]) -> None:
"""Test convert_markdown converts metadata correctly."""
md = markdown_factory()
_, meta = convert_markdown(md, input_)
assert expected == meta
def test_markdown_factory():
def test_markdown_factory() -> None:
"""Test markdown_factory."""
md = markdown_factory()
assert isinstance(md, markdown.Markdown)
def test_smarty():
def test_smarty() -> None:
"""Test smarty."""
md = markdown_factory()
md1 = """
@@ -74,12 +97,13 @@ this --- is -- a test ...
"""
html, meta = convert_markdown(md, md1)
assert 'mdash' in html
assert 'ndash' in html
assert 'hellip' in html
assert "mdash" in html
assert "ndash" in html
assert "hellip" in html
def test_smarty_code():
def test_smarty_code() -> None:
"""Test smarty doesn't touch code."""
md = markdown_factory()
md1 = """
@@ -88,6 +112,6 @@ this --- is -- a test ...
```
"""
html, meta = convert_markdown(md, md1)
assert 'mdash' not in html
assert 'ndash' not in html
assert 'hellip' not in html
assert "mdash" not in html
assert "ndash" not in html
assert "hellip" not in html

View File

@@ -1,24 +1,51 @@
"""Tests for the quickstart module."""
# remove when we don't support py38 anymore
from __future__ import annotations
import os
from pytest import MonkeyPatch
from blag.quickstart import get_input, quickstart
def test_get_input_default_answer(monkeypatch):
monkeypatch.setattr('builtins.input', lambda x: '')
def test_get_input_default_answer(monkeypatch: MonkeyPatch) -> None:
"""Test get_input with default answer."""
monkeypatch.setattr("builtins.input", lambda x: "")
answer = get_input("foo", "bar")
assert answer == 'bar'
assert answer == "bar"
def test_get_input(monkeypatch):
monkeypatch.setattr('builtins.input', lambda x: 'baz')
def test_get_input(monkeypatch: MonkeyPatch) -> None:
"""Test get_input."""
monkeypatch.setattr("builtins.input", lambda x: "baz")
answer = get_input("foo", "bar")
assert answer == 'baz'
assert answer == "baz"
def test_quickstart(cleandir, monkeypatch):
monkeypatch.setattr('builtins.input', lambda x: 'foo')
def test_quickstart(cleandir: str, monkeypatch: MonkeyPatch) -> None:
"""Test quickstart."""
monkeypatch.setattr("builtins.input", lambda x: "foo")
quickstart(None)
with open('config.ini', 'r') as fh:
with open("config.ini") as fh:
data = fh.read()
assert 'base_url = foo' in data
assert 'title = foo' in data
assert 'description = foo' in data
assert 'author = foo' in data
assert "base_url = foo" in data
assert "title = foo" in data
assert "description = foo" in data
assert "author = foo" in data
for template in (
"archive.html",
"article.html",
"base.html",
"index.html",
"page.html",
"tag.html",
"tags.html",
):
assert os.path.exists(f"templates/{template}")
for directory in "build", "content", "static":
assert os.path.exists(directory)

View File

@@ -1,73 +1,107 @@
"""Test the templates."""
# remove when we don't support py38 anymore
from __future__ import annotations
import datetime
from jinja2 import Template
def test_page(page_template):
def test_page(page_template: Template) -> None:
"""Test the page template."""
ctx = {
'content': 'this is the content',
'title': 'this is the title',
"content": "this is the content",
"title": "this is the title",
}
result = page_template.render(ctx)
assert 'this is the content' in result
assert 'this is the title' in result
assert "this is the content" in result
assert "this is the title" in result
def test_article(article_template):
def test_article(article_template: Template) -> None:
"""Test the article template."""
ctx = {
'content': 'this is the content',
'title': 'this is the title',
'date': datetime.datetime(1980, 5, 9),
"content": "this is the content",
"title": "this is the title",
"date": datetime.datetime(1980, 5, 9),
}
result = article_template.render(ctx)
assert 'this is the content' in result
assert 'this is the title' in result
assert '1980-05-09' in result
assert "this is the content" in result
assert "this is the title" in result
assert "1980-05-09" in result
def test_archive(archive_template):
def test_index(index_template: Template) -> None:
"""Test the index template."""
entry = {
'title': 'this is a title',
'dst': 'https://example.com/link',
'date': datetime.datetime(1980, 5, 9),
"title": "this is a title",
"dst": "https://example.com/link",
"date": datetime.datetime(1980, 5, 9),
}
archive = [entry]
ctx = {
'archive': archive,
"archive": archive,
}
result = index_template.render(ctx)
assert "site title" in result
assert "this is a title" in result
assert "1980-05-09" in result
assert "https://example.com/link" in result
assert "/archive.html" in result
def test_archive(archive_template: Template) -> None:
"""Test the archive template."""
entry = {
"title": "this is a title",
"dst": "https://example.com/link",
"date": datetime.datetime(1980, 5, 9),
}
archive = [entry]
ctx = {
"archive": archive,
}
result = archive_template.render(ctx)
assert 'site title' in result
assert "Archive" in result
assert 'this is a title' in result
assert '1980-05-09' in result
assert 'https://example.com/link' in result
assert "this is a title" in result
assert "1980-05-09" in result
assert "https://example.com/link" in result
def test_tags(tags_template):
tags = [('foo', 42)]
def test_tags(tags_template: Template) -> None:
"""Test the tags template."""
tags = [("foo", 42)]
ctx = {
'tags': tags,
"tags": tags,
}
result = tags_template.render(ctx)
assert 'Tags' in result
assert "Tags" in result
assert 'foo.html' in result
assert 'foo' in result
assert '42' in result
assert "foo.html" in result
assert "foo" in result
assert "42" in result
def test_tag(tag_template):
def test_tag(tag_template: Template) -> None:
"""Test the tag template."""
entry = {
'title': 'this is a title',
'dst': 'https://example.com/link',
'date': datetime.datetime(1980, 5, 9),
"title": "this is a title",
"dst": "https://example.com/link",
"date": datetime.datetime(1980, 5, 9),
}
archive = [entry]
ctx = {
'tag': 'foo',
'archive': archive,
"tag": "foo",
"archive": archive,
}
result = tag_template.render(ctx)
assert 'Tag foo' in result
assert "foo" in result
assert 'this is a title' in result
assert '1980-05-09' in result
assert 'https://example.com/link' in result
assert "this is a title" in result
assert "1980-05-09" in result
assert "https://example.com/link" in result

View File

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