Debian Codegraph @

ansible_collections/community/docker/tests/unit/plugins/inventory/test_docker_containers.py

raw
1 # Copyright (c), Felix Fontein <[email protected]>, 2020
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 import typing as t
8 from unittest.mock import create_autospec
9
10 import pytest
11 from ansible.inventory.data import InventoryData
12 from ansible.parsing.dataloader import DataLoader
13 from ansible.template import Templar
14 from ansible_collections.community.internal_test_tools.tests.unit.utils.trust import (
15 make_trusted,
16 )
17
18 from ansible_collections.community.docker.plugins.inventory.docker_containers import (
19 InventoryModule,
20 )
21
22 if t.TYPE_CHECKING:
23 from collections.abc import Callable
24
25
26 @pytest.fixture(scope="module", name="templar")
27 def templar_fixture() -> Templar:
28 dataloader = create_autospec(DataLoader, instance=True)
29 return Templar(loader=dataloader)
30
31
32 @pytest.fixture(scope="module", name="inventory")
33 def inventory_fixture(templar: Templar) -> InventoryModule:
34 r = InventoryModule()
35 r.inventory = InventoryData()
36 r.templar = templar
37 return r
38
39
40 LOVING_THARP = {
41 "Id": "7bd547963679e3209cafd52aff21840b755c96fd37abcd7a6e19da8da6a7f49a",
42 "Name": "/loving_tharp",
43 "Image": "sha256:349f492ff18add678364a62a67ce9a13487f14293ae0af1baf02398aa432f385",
44 "State": {
45 "Running": True,
46 },
47 "Config": {
48 "Image": "quay.io/ansible/ubuntu1804-test-container:1.21.0",
49 },
50 }
51
52
53 LOVING_THARP_STACK = {
54 "Id": "7bd547963679e3209cafd52aff21840b755c96fd37abcd7a6e19da8da6a7f49a",
55 "Name": "/loving_tharp",
56 "Image": "sha256:349f492ff18add678364a62a67ce9a13487f14293ae0af1baf02398aa432f385",
57 "State": {
58 "Running": True,
59 },
60 "Config": {
61 "Image": "quay.io/ansible/ubuntu1804-test-container:1.21.0",
62 "Labels": {
63 "com.docker.stack.namespace": "my_stack",
64 },
65 },
66 "NetworkSettings": {
67 "Ports": {
68 "22/tcp": [{"HostIp": "0.0.0.0", "HostPort": "32802"}],
69 },
70 },
71 }
72
73
74 LOVING_THARP_SERVICE = {
75 "Id": "7bd547963679e3209cafd52aff21840b755c96fd37abcd7a6e19da8da6a7f49a",
76 "Name": "/loving_tharp",
77 "Image": "sha256:349f492ff18add678364a62a67ce9a13487f14293ae0af1baf02398aa432f385",
78 "State": {
79 "Running": True,
80 },
81 "Config": {
82 "Image": "quay.io/ansible/ubuntu1804-test-container:1.21.0",
83 "Labels": {
84 "com.docker.swarm.service.name": "my_service",
85 },
86 },
87 }
88
89
90 def create_get_option(
91 options: dict[str, t.Any], default: t.Any = False
92 ) -> Callable[[str], t.Any]:
93 def get_option(option: str) -> t.Any:
94 if option in options:
95 return options[option]
96 return default
97
98 return get_option
99
100
101 class FakeClient:
102 def __init__(self, *hosts: dict[str, t.Any]) -> None:
103 self.get_results: dict[str, t.Any] = {}
104 list_reply: list[dict[str, t.Any]] = []
105 for host in hosts:
106 list_reply.append(
107 {
108 "Id": host["Id"],
109 "Names": [host["Name"]] if host["Name"] else [],
110 "Image": host["Config"]["Image"],
111 "ImageId": host["Image"],
112 }
113 )
114 self.get_results[f"/containers/{host['Name']}/json"] = host
115 self.get_results[f"/containers/{host['Id']}/json"] = host
116 self.get_results["/containers/json"] = list_reply
117
118 def get_json(self, url: str, *param: str, **kwargs: t.Any) -> t.Any:
119 url = url.format(*param)
120 return self.get_results[url]
121
122
123 def test_populate(inventory: InventoryModule, mocker: t.Any) -> None:
124 assert inventory.inventory is not None
125 client = FakeClient(LOVING_THARP)
126
127 inventory.get_option = mocker.MagicMock( # type: ignore[method-assign]
128 side_effect=create_get_option(
129 {
130 "verbose_output": True,
131 "connection_type": "docker-api",
132 "add_legacy_groups": False,
133 "compose": {},
134 "groups": {},
135 "keyed_groups": {},
136 "filters": None,
137 }
138 )
139 )
140 inventory._populate(client) # type: ignore
141
142 host_1 = inventory.inventory.get_host("loving_tharp")
143 assert host_1 is not None
144 host_1_vars = host_1.get_vars()
145
146 assert host_1_vars["ansible_host"] == "loving_tharp"
147 assert host_1_vars["ansible_connection"] == "community.docker.docker_api"
148 assert "ansible_ssh_host" not in host_1_vars
149 assert "ansible_ssh_port" not in host_1_vars
150 assert "docker_state" in host_1_vars
151 assert "docker_config" in host_1_vars
152 assert "docker_image" in host_1_vars
153
154 assert len(inventory.inventory.groups["ungrouped"].hosts) == 0
155 assert len(inventory.inventory.groups["all"].hosts) == 0
156 assert len(inventory.inventory.groups) == 2
157 assert len(inventory.inventory.hosts) == 1
158
159
160 def test_populate_service(inventory: InventoryModule, mocker: t.Any) -> None:
161 assert inventory.inventory is not None
162 client = FakeClient(LOVING_THARP_SERVICE)
163
164 inventory.get_option = mocker.MagicMock( # type: ignore[method-assign]
165 side_effect=create_get_option(
166 {
167 "verbose_output": False,
168 "connection_type": "docker-cli",
169 "add_legacy_groups": True,
170 "compose": {},
171 "groups": {},
172 "keyed_groups": {},
173 "docker_host": "unix://var/run/docker.sock",
174 "filters": None,
175 }
176 )
177 )
178 inventory._populate(client) # type: ignore
179
180 host_1 = inventory.inventory.get_host("loving_tharp")
181 assert host_1 is not None
182 host_1_vars = host_1.get_vars()
183
184 assert host_1_vars["ansible_host"] == "loving_tharp"
185 assert host_1_vars["ansible_connection"] == "community.docker.docker"
186 assert "ansible_ssh_host" not in host_1_vars
187 assert "ansible_ssh_port" not in host_1_vars
188 assert "docker_state" not in host_1_vars
189 assert "docker_config" not in host_1_vars
190 assert "docker_image" not in host_1_vars
191
192 assert len(inventory.inventory.groups["ungrouped"].hosts) == 0
193 assert len(inventory.inventory.groups["all"].hosts) == 0
194 assert len(inventory.inventory.groups["7bd547963679e"].hosts) == 1
195 assert (
196 len(
197 inventory.inventory.groups[
198 "7bd547963679e3209cafd52aff21840b755c96fd37abcd7a6e19da8da6a7f49a"
199 ].hosts
200 )
201 == 1
202 )
203 assert (
204 len(
205 inventory.inventory.groups[
206 "image_quay.io/ansible/ubuntu1804-test-container:1.21.0"
207 ].hosts
208 )
209 == 1
210 )
211 assert len(inventory.inventory.groups["loving_tharp"].hosts) == 1
212 assert len(inventory.inventory.groups["running"].hosts) == 1
213 assert len(inventory.inventory.groups["stopped"].hosts) == 0
214 assert len(inventory.inventory.groups["service_my_service"].hosts) == 1
215 assert len(inventory.inventory.groups["unix://var/run/docker.sock"].hosts) == 1
216 assert len(inventory.inventory.groups) == 10
217 assert len(inventory.inventory.hosts) == 1
218
219
220 def test_populate_stack(inventory: InventoryModule, mocker: t.Any) -> None:
221 assert inventory.inventory is not None
222 client = FakeClient(LOVING_THARP_STACK)
223
224 inventory.get_option = mocker.MagicMock( # type: ignore[method-assign]
225 side_effect=create_get_option(
226 {
227 "verbose_output": False,
228 "connection_type": "ssh",
229 "add_legacy_groups": True,
230 "compose": {},
231 "groups": {},
232 "keyed_groups": {},
233 "docker_host": "unix://var/run/docker.sock",
234 "default_ip": "127.0.0.1",
235 "private_ssh_port": 22,
236 "filters": None,
237 }
238 )
239 )
240 inventory._populate(client) # type: ignore
241
242 host_1 = inventory.inventory.get_host("loving_tharp")
243 assert host_1 is not None
244 host_1_vars = host_1.get_vars()
245
246 assert host_1_vars["ansible_ssh_host"] == "127.0.0.1"
247 assert host_1_vars["ansible_ssh_port"] == "32802"
248 assert "ansible_host" not in host_1_vars
249 assert "ansible_connection" not in host_1_vars
250 assert "docker_state" not in host_1_vars
251 assert "docker_config" not in host_1_vars
252 assert "docker_image" not in host_1_vars
253
254 assert len(inventory.inventory.groups["ungrouped"].hosts) == 0
255 assert len(inventory.inventory.groups["all"].hosts) == 0
256 assert len(inventory.inventory.groups["7bd547963679e"].hosts) == 1
257 assert (
258 len(
259 inventory.inventory.groups[
260 "7bd547963679e3209cafd52aff21840b755c96fd37abcd7a6e19da8da6a7f49a"
261 ].hosts
262 )
263 == 1
264 )
265 assert (
266 len(
267 inventory.inventory.groups[
268 "image_quay.io/ansible/ubuntu1804-test-container:1.21.0"
269 ].hosts
270 )
271 == 1
272 )
273 assert len(inventory.inventory.groups["loving_tharp"].hosts) == 1
274 assert len(inventory.inventory.groups["running"].hosts) == 1
275 assert len(inventory.inventory.groups["stopped"].hosts) == 0
276 assert len(inventory.inventory.groups["stack_my_stack"].hosts) == 1
277 assert len(inventory.inventory.groups["unix://var/run/docker.sock"].hosts) == 1
278 assert len(inventory.inventory.groups) == 10
279 assert len(inventory.inventory.hosts) == 1
280
281
282 def test_populate_filter_none(inventory: InventoryModule, mocker: t.Any) -> None:
283 assert inventory.inventory is not None
284 client = FakeClient(LOVING_THARP)
285
286 inventory.get_option = mocker.MagicMock( # type: ignore[method-assign]
287 side_effect=create_get_option(
288 {
289 "verbose_output": True,
290 "connection_type": "docker-api",
291 "add_legacy_groups": False,
292 "compose": {},
293 "groups": {},
294 "keyed_groups": {},
295 "filters": [
296 {"exclude": True},
297 ],
298 }
299 )
300 )
301 inventory._populate(client) # type: ignore
302
303 assert len(inventory.inventory.hosts) == 0
304
305
306 def test_populate_filter(inventory: InventoryModule, mocker: t.Any) -> None:
307 assert inventory.inventory is not None
308 client = FakeClient(LOVING_THARP)
309
310 inventory.get_option = mocker.MagicMock( # type: ignore[method-assign]
311 side_effect=create_get_option(
312 {
313 "verbose_output": True,
314 "connection_type": "docker-api",
315 "add_legacy_groups": False,
316 "compose": {},
317 "groups": {},
318 "keyed_groups": {},
319 "filters": [
320 {"include": make_trusted("docker_state.Running is true")},
321 {"exclude": True},
322 ],
323 }
324 )
325 )
326 inventory._populate(client) # type: ignore
327
328 host_1 = inventory.inventory.get_host("loving_tharp")
329 assert host_1 is not None
330 host_1_vars = host_1.get_vars()
331
332 assert host_1_vars["ansible_host"] == "loving_tharp"
333 assert len(inventory.inventory.hosts) == 1