Add tests for some device & address variables
[tinc] / test / integration / testlib / test.py
1 """Test context that wraps Tinc instances and terminates them on exit."""
2
3 import typing as T
4
5 from .log import log
6 from .proc import Tinc
7
8
9 class Test:
10     """Test context. Allows you to obtain Tinc instances which are automatically
11     stopped (and killed if necessary) at __exit__. Should be wrapped in `with`
12     statements (like the built-in `open`). Should be used sparingly (as it usually
13     happens, thanks to Windows: service registration and removal is quite slow,
14     which makes tests take a long time to run, especially on modest CI VMs).
15     """
16
17     name: str
18     _nodes: T.List[Tinc]
19
20     def __init__(self, name: str) -> None:
21         self._nodes = []
22         self.name = name
23
24     def node(self, addr: str = "", init: T.Union[str, bool] = "") -> Tinc:
25         """Create a Tinc instance and remember it for termination on exit."""
26         node = Tinc(addr=addr)
27         self._nodes.append(node)
28         if init:
29             if isinstance(init, bool):
30                 init = ""
31             stdin = f"""
32                 init {node}
33                 set Port 0
34                 set Address localhost
35                 set DeviceType dummy
36                 {init}
37             """
38             node.cmd(stdin=stdin)
39         return node
40
41     def __str__(self) -> str:
42         return self.name
43
44     def __enter__(self) -> "Test":
45         log.info("RUNNING TEST: %s", self.name)
46         return self
47
48     def __exit__(self, exc_type, exc_val, exc_tb) -> None:
49         for node in self._nodes:
50             node.cleanup()
51         log.info("FINISHED TEST: %s", self.name)