Improve proxy server support
[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
13
14 def _read_template(tpl_name: str, maps: T.Dict[str, T.Any]) -> str:
15     tpl_path = path.TESTLIB_ROOT.joinpath("template", tpl_name)
16     tpl = Template(tpl_path.read_text(encoding="utf-8"))
17     return tpl.substitute(maps)
18
19
20 def make_script(node: str, script: str, source: str) -> str:
21     """Create a tincd script."""
22     addr = notifications.address
23     if isinstance(addr, str):
24         addr = f'r"{addr}"'  # 'r' is for Windows pipes: \\.\foo\bar
25     maps = {
26         "AUTH_KEY": notifications.authkey,
27         "CWD": path.CWD,
28         "NODE_NAME": node,
29         "NOTIFICATIONS_ADDR": addr,
30         "PYTHON_PATH": path.PYTHON_PATH,
31         "SCRIPT_NAME": script,
32         "SCRIPT_SOURCE": source,
33         "SRC_ROOT": path.TEST_SRC_ROOT,
34         "TEST_NAME": path.TEST_NAME,
35     }
36     return _read_template("script.py.tpl", maps)
37
38
39 def make_cmd_wrap(script: str) -> str:
40     """Create a .cmd wrapper for tincd script. Only makes sense on Windows."""
41     maps = {
42         "PYTHON_CMD": path.PYTHON_CMD,
43         "PYTHON_PATH": path.PYTHON_PATH,
44         "SCRIPT_PATH": script,
45         "VARIABLES": _CMD_VARS,
46     }
47     return _read_template("script.cmd.tpl", maps)
48
49
50 def make_netns_config(namespace: str, ip_addr: str, mask: int) -> str:
51     """Create a tincd script that does network namespace configuration."""
52     maps = {"NAMESPACE": namespace, "ADDRESS": ip_addr, "MASK": mask}
53     return _read_template("netns.py.tpl", maps)