Rewrite integration test suite in Python
[tinc] / test / integration / testlib / template.py
1 """Various script and configuration file templates."""
2
3 import os
4 import typing as T
5 from string import Template
6
7 from . import path
8 from .notification import notifications
9
10
11 _CMD_VARS = os.linesep.join([f"set {var}={val}" for var, val in path.env.items()])
12 _CMD_PY = "runpython" if "meson.exe" in path.PYTHON_PATH.lower() else ""
13
14
15 def _read_template(tpl_name: str, maps: T.Dict[str, T.Any]) -> str:
16     tpl_path = path.TESTLIB_ROOT.joinpath("template", tpl_name)
17     tpl = Template(tpl_path.read_text(encoding="utf-8"))
18     return tpl.substitute(maps)
19
20
21 def make_script(node: str, script: str, source: str) -> str:
22     """Create a tincd script."""
23     addr = notifications.address
24     if isinstance(addr, str):
25         addr = f'r"{addr}"'  # 'r' is for Windows pipes: \\.\foo\bar
26     maps = {
27         "AUTH_KEY": notifications.authkey,
28         "CWD": path.CWD,
29         "NODE_NAME": node,
30         "NOTIFICATIONS_ADDR": addr,
31         "PYTHON_PATH": path.PYTHON_PATH,
32         "SCRIPT_NAME": script,
33         "SCRIPT_SOURCE": source,
34         "SRC_ROOT": path.TEST_SRC_ROOT,
35         "TEST_NAME": path.TEST_NAME,
36     }
37     return _read_template("script.py.tpl", maps)
38
39
40 def make_cmd_wrap(script: str) -> str:
41     """Create a .cmd wrapper for tincd script. Only makes sense on Windows."""
42     maps = {
43         "PYTHON_CMD": _CMD_PY,
44         "PYTHON_PATH": path.PYTHON_PATH,
45         "SCRIPT_PATH": script,
46         "VARIABLES": _CMD_VARS,
47     }
48     return _read_template("script.cmd.tpl", maps)
49
50
51 def make_netns_config(namespace: str, ip_addr: str, mask: int) -> str:
52     """Create a tincd script that does network namespace configuration."""
53     maps = {"NAMESPACE": namespace, "ADDRESS": ip_addr, "MASK": mask}
54     return _read_template("netns.py.tpl", maps)