From 76a033cf437ec2cd5108de1eeaf64e34e38c514c Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Sun, 10 Apr 2022 15:50:58 +0200 Subject: [PATCH] feat: create generate worker --- bopytex/worker/generate.py | 13 +++++++++++ bopytex/worker/worker.py | 28 ---------------------- test/worker/test_generate.py | 45 ++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 28 deletions(-) create mode 100644 bopytex/worker/generate.py delete mode 100644 bopytex/worker/worker.py create mode 100644 test/worker/test_generate.py diff --git a/bopytex/worker/generate.py b/bopytex/worker/generate.py new file mode 100644 index 0000000..ff80f76 --- /dev/null +++ b/bopytex/worker/generate.py @@ -0,0 +1,13 @@ +from jinja2.environment import Template + + +def generate(args, deps, output): + env = args["jinja2"]["environment"] + template = env.get_template(deps[0]) + with open(output, "w") as out: + out.write(tpl2tex(template, metas=args)) + yield f"GENERATE - {deps[0]} to {output}" + + +def tpl2tex(template: Template, metas: dict = {}) -> str: + return template.render(metas) diff --git a/bopytex/worker/worker.py b/bopytex/worker/worker.py deleted file mode 100644 index d544d77..0000000 --- a/bopytex/worker/worker.py +++ /dev/null @@ -1,28 +0,0 @@ -""" A worker consumes tasks """ -def generate(): - pass - - -def compile(): - pass - - -def activate_corr(): - pass - - -def join_pdf(): - pass - - -def clean(): - pass - - -WORKERS = { - "GENERATE": generate, - "COMPILE": compile, - "ACTIVATE_CORR": activate_corr, - "JOIN_PDF": join_pdf, - "CLEAN": clean, -} diff --git a/test/worker/test_generate.py b/test/worker/test_generate.py new file mode 100644 index 0000000..ab90ba7 --- /dev/null +++ b/test/worker/test_generate.py @@ -0,0 +1,45 @@ +import os +import jinja2 +from pathlib import Path +from bopytex.worker.generate import tpl2tex, generate +import pytest + + +def test_tpl2tex(): + tpl = "Plop {{a}}" + jinja2_tpl = jinja2.Template(tpl) + fed = tpl2tex(jinja2_tpl, metas={"a": 1}) + assert fed == "Plop 1" + + +@pytest.fixture +def template_path(tmp_path): + template = tmp_path / "template.j2" + with open(template, "w") as tpl: + tpl.write("Plop {{ a }}") + return template + + +@pytest.fixture +def jinja2_env(tmp_path): + templateEnv = jinja2.Environment(loader=jinja2.FileSystemLoader(tmp_path)) + return templateEnv + + +def test_generate(template_path, jinja2_env): + tmp_path = template_path.parent + os.chdir(tmp_path) + + assert template_path.exists + template = str(template_path.name) + output = "output" + + result = next(generate( + args={"a": 2, "jinja2": {"environment": jinja2_env}}, + deps=[template], + output=output, + )) + assert result == "GENERATE - template.j2 to output" + with open(output, "r") as out: + lines = out.readlines() + assert lines == ["Plop 2"]