hs-test: fixed timed out tests passing in the CI
[vpp.git] / test / vpp_object.py
1 """ abstract vpp object and object registry """
2
3 import abc
4
5
6 class VppObject(metaclass=abc.ABCMeta):
7     """Abstract vpp object"""
8
9     @abc.abstractmethod
10     def add_vpp_config(self) -> None:
11         """Add the configuration for this object to vpp."""
12         pass
13
14     @abc.abstractmethod
15     def query_vpp_config(self) -> bool:
16         """Query the vpp configuration.
17
18         :return: True if the object is configured"""
19         pass
20
21     @abc.abstractmethod
22     def remove_vpp_config(self) -> None:
23         """Remove the configuration for this object from vpp."""
24         pass
25
26     def object_id(self) -> str:
27         """Return a unique string representing this object."""
28         return "Undefined. for <%s %s>" % (self.__class__.__name__, id(self))
29
30     def __str__(self) -> str:
31         return self.object_id()
32
33     def __repr__(self) -> str:
34         return "<%s>" % self.object_id()
35
36     def __hash__(self) -> int:
37         return hash(self.object_id())
38
39     def __eq__(self, other) -> bool:
40         if not isinstance(other, self.__class__):
41             return NotImplemented
42         if other.object_id() == self.object_id():
43             return True
44         return False
45
46     # This can be removed when python2 support is dropped.
47     def __ne__(self, other):
48         return not self.__eq__(other)
49
50
51 class VppObjectRegistry:
52     """Class which handles automatic configuration cleanup."""
53
54     _shared_state = {}
55
56     def __init__(self) -> None:
57         self.__dict__ = self._shared_state
58         if not hasattr(self, "_object_registry"):
59             self._object_registry = []
60         if not hasattr(self, "_object_dict"):
61             self._object_dict = dict()
62
63     def register(self, obj: VppObject, logger) -> None:
64         """Register an object in the registry."""
65         if obj.object_id() not in self._object_dict:
66             self._object_registry.append(obj)
67             self._object_dict[obj.object_id()] = obj
68             logger.debug("REG: registering %s" % obj)
69         else:
70             logger.debug("REG: duplicate add, ignoring (%s)" % obj)
71
72     def unregister_all(self, logger) -> None:
73         """Remove all object registrations from registry."""
74         logger.debug("REG: removing all object registrations")
75         self._object_registry = []
76         self._object_dict = dict()
77
78     def remove_vpp_config(self, logger) -> None:
79         """
80         Remove configuration (if present) from vpp and then remove all objects
81         from the registry.
82         """
83         if not self._object_registry:
84             logger.info("REG: No objects registered for auto-cleanup.")
85             return
86         logger.info("REG: Removing VPP configuration for registered objects")
87         # remove the config in reverse order as there might be dependencies
88         failed = []
89         for obj in reversed(self._object_registry):
90             if obj.query_vpp_config():
91                 logger.info("REG: Removing configuration for %s" % obj)
92                 obj.remove_vpp_config()
93                 if obj.query_vpp_config():
94                     failed.append(obj)
95             else:
96                 logger.info(
97                     "REG: Skipping removal for %s, configuration not present" % obj
98                 )
99         self.unregister_all(logger)
100         if failed:
101             logger.error("REG: Couldn't remove configuration for object(s):")
102             for obj in failed:
103                 logger.error(repr(obj))
104             raise Exception(
105                 "Couldn't remove configuration for object(s): %s"
106                 % (", ".join(str(x) for x in failed))
107             )