1306abd656e098cf2d58c52855f8e2367461b06d
[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 = "") -> Tinc:
25         """Create a Tinc instance and remember it for termination on exit."""
26         node = Tinc(addr=addr)
27         self._nodes.append(node)
28         return node
29
30     def __str__(self) -> str:
31         return self.name
32
33     def __enter__(self) -> "Test":
34         log.info("RUNNING TEST: %s", self.name)
35         return self
36
37     def __exit__(self, exc_type, exc_val, exc_tb) -> None:
38         for node in self._nodes:
39             node.cleanup()
40         log.info("FINISHED TEST: %s", self.name)