Debian Codegraph @

ansible_collections/amazon/aws/tests/unit/plugins/inventory/test_aws_rds.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2022 Aubin Bikouo <@abikouo>
4 #
5 # This file is part of Ansible
6 #
7 # Ansible is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Ansible is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
19
20 import copy
21 import random
22 import string
23 from unittest.mock import MagicMock
24 from unittest.mock import call
25 from unittest.mock import patch
26
27 import pytest
28
29 try:
30 import botocore
31 except ImportError:
32 # Handled by HAS_BOTO3
33 pass
34
35 from ansible.errors import AnsibleError
36
37 from ansible_collections.amazon.aws.plugins.inventory.aws_rds import InventoryModule
38 from ansible_collections.amazon.aws.plugins.inventory.aws_rds import _add_tags_for_rds_hosts
39 from ansible_collections.amazon.aws.plugins.inventory.aws_rds import _describe_db_clusters
40 from ansible_collections.amazon.aws.plugins.inventory.aws_rds import _describe_db_instances
41 from ansible_collections.amazon.aws.plugins.inventory.aws_rds import _find_hosts_with_valid_statuses
42 from ansible_collections.amazon.aws.plugins.inventory.aws_rds import _get_rds_hostname
43 from ansible_collections.amazon.aws.plugins.inventory.aws_rds import ansible_dict_to_boto3_filter_list
44 from ansible_collections.amazon.aws.plugins.module_utils.botocore import HAS_BOTO3
45
46 if not HAS_BOTO3:
47 pytestmark = pytest.mark.skip("test_aws_rds.py requires the python modules 'boto3' and 'botocore'")
48
49
50 def make_clienterror_exception(code="AccessDenied"):
51 return botocore.exceptions.ClientError(
52 {
53 "Error": {"Code": code, "Message": "User is not authorized to perform: xxx on resource: user yyyy"},
54 "ResponseMetadata": {"RequestId": "01234567-89ab-cdef-0123-456789abcdef"},
55 },
56 "getXXX",
57 )
58
59
60 @pytest.fixture(name="inventory")
61 def fixture_inventory():
62 inventory = InventoryModule()
63 inventory.inventory = MagicMock()
64 inventory._populate_host_vars = MagicMock()
65
66 inventory.all_clients = MagicMock()
67 inventory.get_option = MagicMock()
68
69 inventory._set_composite_vars = MagicMock()
70 inventory._add_host_to_composed_groups = MagicMock()
71 inventory._add_host_to_keyed_groups = MagicMock()
72 inventory._read_config_data = MagicMock()
73 inventory._set_credentials = MagicMock()
74
75 inventory.get_cache_key = MagicMock()
76
77 inventory._cache = {}
78 return inventory
79
80
81 @pytest.fixture(name="connection")
82 def fixture_connection():
83 conn = MagicMock()
84 return conn
85
86
87 @pytest.mark.parametrize(
88 "suffix,result",
89 [
90 ("aws_rds.yml", True),
91 ("aws_rds.yaml", True),
92 ("aws_RDS.yml", False),
93 ("AWS_rds.yaml", False),
94 ],
95 )
96 def test_inventory_verify_file_suffix(inventory, suffix, result, tmp_path):
97 test_dir = tmp_path / "test_aws_rds"
98 test_dir.mkdir()
99 inventory_file = "inventory" + suffix
100 inventory_file = test_dir / inventory_file
101 inventory_file.write_text("my inventory")
102 assert result == inventory.verify_file(str(inventory_file))
103
104
105 def test_inventory_verify_file_with_missing_file(inventory):
106 inventory_file = "this_file_does_not_exist_aws_rds.yml"
107 assert not inventory.verify_file(inventory_file)
108
109
110 def generate_random_string(with_digits=True, with_punctuation=True, length=16):
111 data = string.ascii_letters
112 if with_digits:
113 data += string.digits
114 if with_punctuation:
115 data += string.punctuation
116 return "".join([random.choice(data) for i in range(length)])
117
118
119 @pytest.mark.parametrize(
120 "hosts,statuses,expected",
121 [
122 (
123 [
124 {"host": "host1", "DBInstanceStatus": "Available", "Status": "active"},
125 {"host": "host2", "DBInstanceStatus": "Creating", "Status": "active"},
126 {"host": "host3", "DBInstanceStatus": "Stopped", "Status": "active"},
127 {"host": "host4", "DBInstanceStatus": "Configuring", "Status": "active"},
128 ],
129 ["Available"],
130 [{"host": "host1", "DBInstanceStatus": "Available", "Status": "active"}],
131 ),
132 (
133 [
134 {"host": "host1", "DBInstanceStatus": "Available", "Status": "active"},
135 {"host": "host2", "DBInstanceStatus": "Creating", "Status": "active"},
136 {"host": "host3", "DBInstanceStatus": "Stopped", "Status": "active"},
137 {"host": "host4", "DBInstanceStatus": "Configuring", "Status": "active"},
138 ],
139 ["all"],
140 [
141 {"host": "host1", "DBInstanceStatus": "Available", "Status": "active"},
142 {"host": "host2", "DBInstanceStatus": "Creating", "Status": "active"},
143 {"host": "host3", "DBInstanceStatus": "Stopped", "Status": "active"},
144 {"host": "host4", "DBInstanceStatus": "Configuring", "Status": "active"},
145 ],
146 ),
147 (
148 [
149 {"host": "host1", "DBInstanceStatus": "Available", "Status": "active"},
150 {"host": "host2", "DBInstanceStatus": "Creating", "Status": "Available"},
151 {"host": "host3", "DBInstanceStatus": "Stopped", "Status": "active"},
152 {"host": "host4", "DBInstanceStatus": "Configuring", "Status": "active"},
153 ],
154 ["Available"],
155 [
156 {"host": "host1", "DBInstanceStatus": "Available", "Status": "active"},
157 {"host": "host2", "DBInstanceStatus": "Creating", "Status": "Available"},
158 ],
159 ),
160 ],
161 )
162 def test_find_hosts_with_valid_statuses(hosts, statuses, expected):
163 assert expected == _find_hosts_with_valid_statuses(hosts, statuses)
164
165
166 @pytest.mark.parametrize(
167 "host,expected",
168 [
169 ({"DBClusterIdentifier": "my_cluster_id"}, "my_cluster_id"),
170 ({"DBClusterIdentifier": "my_cluster_id", "DBInstanceIdentifier": "my_instance_id"}, "my_instance_id"),
171 ],
172 )
173 def test_get_rds_hostname(host, expected):
174 assert expected == _get_rds_hostname(host)
175
176
177 @pytest.mark.parametrize("hosts", ["", "host1", "host2,host3", "host2,host3,host1"])
178 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_rds._get_rds_hostname")
179 def test_inventory_format_inventory(m_get_rds_hostname, inventory, hosts):
180 hosts_vars = {
181 "host1": {"var10": "value10"},
182 "host2": {"var20": "value20", "var21": "value21"},
183 "host3": {"var30": "value30", "var31": "value31", "var32": "value32"},
184 }
185
186 m_get_rds_hostname.side_effect = lambda h: h["name"]
187
188 class _inventory_host(object):
189 def __init__(self, name, host_vars):
190 self.name = name
191 self.vars = host_vars
192
193 inventory.inventory = MagicMock()
194 inventory.inventory.get_host.side_effect = lambda x: _inventory_host(name=x, host_vars=hosts_vars.get(x))
195
196 hosts = [{"name": x} for x in hosts.split(",") if x]
197 expected = {
198 "_meta": {"hostvars": {x["name"]: hosts_vars.get(x["name"]) for x in hosts}},
199 "aws_rds": {"hosts": [x["name"] for x in hosts]},
200 }
201
202 assert expected == inventory._format_inventory(hosts)
203 if hosts == []:
204 m_get_rds_hostname.assert_not_called()
205
206
207 @pytest.mark.parametrize("length", range(0, 10, 2))
208 def test_inventory_populate(inventory, length):
209 group = "aws_rds"
210 hosts = [f"host_{int(i)}" for i in range(length)]
211
212 inventory._add_hosts = MagicMock()
213 inventory._populate(hosts=hosts)
214
215 inventory.inventory.add_group.assert_called_with("aws_rds")
216
217 if len(hosts) == 0:
218 inventory.inventory._add_hosts.assert_not_called()
219 inventory.inventory.add_child.assert_not_called()
220 else:
221 inventory._add_hosts.assert_called_with(hosts=hosts, group=group)
222 inventory.inventory.add_child.assert_called_with("all", group)
223
224
225 def test_inventory_populate_from_source(inventory):
226 source_data = {
227 "_meta": {
228 "hostvars": {
229 "host_1_0": {"var10": "value10"},
230 "host_2": {"var2": "value2"},
231 "host_3": {"var3": ["value30", "value31", "value32"]},
232 }
233 },
234 "all": {"hosts": ["host_1_0", "host_1_1", "host_2", "host_3"]},
235 "aws_host_1": {"hosts": ["host_1_0", "host_1_1"]},
236 "aws_host_2": {"hosts": ["host_2"]},
237 "aws_host_3": {"hosts": ["host_3"]},
238 }
239
240 inventory._populate_from_source(source_data)
241 inventory.inventory.add_group.assert_has_calls(
242 [
243 call("aws_host_1"),
244 call("aws_host_2"),
245 call("aws_host_3"),
246 ],
247 any_order=True,
248 )
249 inventory.inventory.add_child.assert_has_calls(
250 [
251 call("all", "aws_host_1"),
252 call("all", "aws_host_2"),
253 call("all", "aws_host_3"),
254 ],
255 any_order=True,
256 )
257
258 inventory._populate_host_vars.assert_has_calls(
259 [
260 call(["host_1_0"], {"var10": "value10"}, "aws_host_1"),
261 call(["host_1_1"], {}, "aws_host_1"),
262 call(["host_2"], {"var2": "value2"}, "aws_host_2"),
263 call(["host_3"], {"var3": ["value30", "value31", "value32"]}, "aws_host_3"),
264 ],
265 any_order=True,
266 )
267
268
269 @pytest.mark.parametrize("strict", [True, False])
270 def test_add_tags_for_rds_hosts_with_no_hosts(connection, strict):
271 hosts = []
272
273 _add_tags_for_rds_hosts(connection, hosts, strict)
274 connection.list_tags_for_resource.assert_not_called()
275
276
277 def test_add_tags_for_rds_hosts_with_hosts(connection):
278 hosts = [
279 {"DBInstanceArn": "dbarn1"},
280 {"DBInstanceArn": "dbarn2"},
281 {"DBClusterArn": "clusterarn1"},
282 ]
283
284 rds_hosts_tags = {
285 "dbarn1": {"TagList": ["tag1=dbarn1", "phase=units"]},
286 "dbarn2": {"TagList": ["tag2=dbarn2", "collection=amazon.aws"]},
287 "clusterarn1": {"TagList": ["tag1=clusterarn1", "tool=ansible-test"]},
288 }
289 connection.list_tags_for_resource.side_effect = lambda **kwargs: rds_hosts_tags.get(kwargs.get("ResourceName"))
290
291 _add_tags_for_rds_hosts(connection, hosts, strict=False)
292
293 assert hosts == [
294 {"DBInstanceArn": "dbarn1", "Tags": ["tag1=dbarn1", "phase=units"]},
295 {"DBInstanceArn": "dbarn2", "Tags": ["tag2=dbarn2", "collection=amazon.aws"]},
296 {"DBClusterArn": "clusterarn1", "Tags": ["tag1=clusterarn1", "tool=ansible-test"]},
297 ]
298
299
300 def test_add_tags_for_rds_hosts_with_failure_not_strict(connection):
301 hosts = [{"DBInstanceArn": "dbarn1"}]
302
303 connection.list_tags_for_resource.side_effect = make_clienterror_exception()
304
305 _add_tags_for_rds_hosts(connection, hosts, strict=False)
306
307 assert hosts == [
308 {"DBInstanceArn": "dbarn1", "Tags": []},
309 ]
310
311
312 def test_add_tags_for_rds_hosts_with_failure_strict(connection):
313 hosts = [{"DBInstanceArn": "dbarn1"}]
314
315 connection.list_tags_for_resource.side_effect = make_clienterror_exception()
316
317 with pytest.raises(botocore.exceptions.ClientError):
318 _add_tags_for_rds_hosts(connection, hosts, strict=True)
319
320
321 ADD_TAGS_FOR_RDS_HOSTS = "ansible_collections.amazon.aws.plugins.inventory.aws_rds._add_tags_for_rds_hosts"
322
323
324 @patch(ADD_TAGS_FOR_RDS_HOSTS)
325 def test_describe_db_clusters(m_add_tags_for_rds_hosts, connection):
326 db_cluster = {
327 "DatabaseName": "my_sample_db",
328 "DBClusterIdentifier": "db_id_01",
329 "Status": "Stopped",
330 "DbClusterResourceId": "cluster_resource_id",
331 "DBClusterArn": "arn:xxx:xxxx",
332 "DeletionProtection": True,
333 }
334
335 connection.describe_db_clusters.return_value = {"DBClusters": [db_cluster]}
336
337 filters = generate_random_string(with_punctuation=False)
338 strict = False
339
340 result = _describe_db_clusters(connection=connection, filters=filters, strict=strict)
341
342 assert result == [db_cluster]
343
344 m_add_tags_for_rds_hosts.assert_called_with(connection, result, strict)
345
346
347 @pytest.mark.parametrize("strict", [True, False])
348 @patch(ADD_TAGS_FOR_RDS_HOSTS)
349 def test_describe_db_clusters_with_access_denied(m_add_tags_for_rds_hosts, connection, strict):
350 connection.describe_db_clusters.side_effect = make_clienterror_exception()
351
352 filters = generate_random_string(with_punctuation=False)
353
354 if strict:
355 with pytest.raises(AnsibleError):
356 _describe_db_clusters(connection=connection, filters=filters, strict=strict)
357 else:
358 assert _describe_db_clusters(connection=connection, filters=filters, strict=strict) == []
359
360 m_add_tags_for_rds_hosts.assert_not_called()
361
362
363 @patch(ADD_TAGS_FOR_RDS_HOSTS)
364 def test_describe_db_clusters_with_client_error(m_add_tags_for_rds_hosts, connection):
365 connection.describe_db_clusters.side_effect = make_clienterror_exception(code="Unknown")
366
367 filters = generate_random_string(with_punctuation=False)
368 with pytest.raises(AnsibleError):
369 _describe_db_clusters(connection=connection, filters=filters, strict=False)
370
371 m_add_tags_for_rds_hosts.assert_not_called()
372
373
374 @patch(ADD_TAGS_FOR_RDS_HOSTS)
375 def test_describe_db_instances(m_add_tags_for_rds_hosts, connection):
376 db_instance = {
377 "DBInstanceIdentifier": "db_id_01",
378 "Status": "Stopped",
379 "DBName": "my_sample_db_01",
380 "DBClusterIdentifier": "db_cluster_001",
381 "DBInstanceArn": "arn:db:xxxx:xxxx:xxxx",
382 "Engine": "mysql",
383 }
384
385 conn_paginator = MagicMock()
386 paginate = MagicMock()
387
388 connection.get_paginator.return_value = conn_paginator
389 conn_paginator.paginate.return_value = paginate
390
391 paginate.build_full_result.return_value = {"DBInstances": [db_instance]}
392
393 filters = generate_random_string(with_punctuation=False)
394 strict = False
395
396 result = _describe_db_instances(connection=connection, filters=filters, strict=strict)
397
398 assert result == [db_instance]
399
400 m_add_tags_for_rds_hosts.assert_called_with(connection, result, strict)
401 connection.get_paginator.assert_called_with("describe_db_instances")
402 conn_paginator.paginate.assert_called_with(Filters=filters)
403
404
405 DESCRIBE_DB_INSTANCES = "ansible_collections.amazon.aws.plugins.inventory.aws_rds._describe_db_instances"
406 DESCRIBE_DB_CLUSTERS = "ansible_collections.amazon.aws.plugins.inventory.aws_rds._describe_db_clusters"
407 FIND_HOSTS_WITH_VALID_STATUSES = (
408 "ansible_collections.amazon.aws.plugins.inventory.aws_rds._find_hosts_with_valid_statuses"
409 )
410
411
412 @pytest.mark.parametrize("gather_clusters", [True, False])
413 @pytest.mark.parametrize("regions", range(1, 5))
414 @patch(DESCRIBE_DB_INSTANCES)
415 @patch(DESCRIBE_DB_CLUSTERS)
416 @patch(FIND_HOSTS_WITH_VALID_STATUSES)
417 def test_inventory_get_all_db_hosts(
418 m_find_hosts, m_describe_db_clusters, m_describe_db_instances, inventory, gather_clusters, regions
419 ):
420 params = {
421 "gather_clusters": gather_clusters,
422 "regions": [f"us-east-{int(i)}" for i in range(regions)],
423 "instance_filters": generate_random_string(),
424 "cluster_filters": generate_random_string(),
425 "strict": random.choice((True, False)),
426 "statuses": [random.choice(["Available", "Stopped", "Running", "Creating"]) for i in range(3)],
427 }
428
429 connections = [MagicMock() for i in range(regions)]
430
431 inventory.all_clients.return_value = [(connections[i], f"us-east-{int(i)}") for i in range(regions)]
432
433 ids = list(reversed(range(regions)))
434 db_instances = [{"DBInstanceIdentifier": f"db_00{int(i)}"} for i in ids]
435 db_clusters = [{"DBClusterIdentifier": f"cluster_00{int(i)}"} for i in ids]
436
437 m_describe_db_instances.side_effect = [[i] for i in db_instances]
438 m_describe_db_clusters.side_effect = [[i] for i in db_clusters]
439
440 result = list(sorted(db_instances, key=lambda x: x["DBInstanceIdentifier"]))
441 if gather_clusters:
442 result += list(sorted(db_clusters, key=lambda x: x["DBClusterIdentifier"]))
443
444 m_find_hosts.return_value = result
445
446 assert result == inventory._get_all_db_hosts(**params)
447 inventory.all_clients.assert_called_with("rds")
448 m_describe_db_instances.assert_has_calls(
449 [call(connections[i], params["instance_filters"], strict=params["strict"]) for i in range(regions)]
450 )
451
452 if gather_clusters:
453 m_describe_db_clusters.assert_has_calls(
454 [call(connections[i], params["cluster_filters"], strict=params["strict"]) for i in range(regions)]
455 )
456
457 m_find_hosts.assert_called_with(result, params["statuses"])
458
459
460 @pytest.mark.parametrize("hostvars_prefix", [True])
461 @pytest.mark.parametrize("hostvars_suffix", [True])
462 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_rds._get_rds_hostname")
463 def test_inventory_add_hosts(m_get_rds_hostname, inventory, hostvars_prefix, hostvars_suffix):
464 _options = {
465 "strict": random.choice((False, True)),
466 "compose": random.choice((False, True)),
467 "keyed_groups": "keyed_group_test_inventory_add_hosts",
468 "groups": ["all", "test_inventory_add_hosts"],
469 }
470
471 if hostvars_prefix:
472 _options["hostvars_prefix"] = f"prefix_{generate_random_string(length=8, with_punctuation=False)}"
473 if hostvars_suffix:
474 _options["hostvars_suffix"] = f"suffix_{generate_random_string(length=8, with_punctuation=False)}"
475
476 def _get_option_side_effect(x):
477 return _options.get(x)
478
479 inventory.get_option.side_effect = _get_option_side_effect
480
481 m_get_rds_hostname.side_effect = lambda h: (
482 h["DBInstanceIdentifier"] if "DBInstanceIdentifier" in h else h["DBClusterIdentifier"]
483 )
484
485 hosts = [
486 {
487 "DBInstanceIdentifier": "db_i_001",
488 "Tags": [{"Key": "Name", "Value": "db_001"}, {"Key": "RunningEngine", "Value": "mysql"}],
489 "availability_zone": "us-east-1a",
490 },
491 {
492 "DBInstanceIdentifier": "db_i_002",
493 "Tags": [{"Key": "ClusterName", "Value": "test_cluster"}, {"Key": "RunningOS", "Value": "CoreOS"}],
494 },
495 {
496 "DBClusterIdentifier": "test_cluster",
497 "Tags": [{"Key": "CluserVersionOrigin", "Value": "2.0"}, {"Key": "Provider", "Value": "RedHat"}],
498 },
499 {
500 "DBClusterIdentifier": "another_cluster",
501 "Tags": [{"Key": "TestingPurpose", "Value": "Ansible"}],
502 "availability_zones": ["us-west-1a", "us-east-1b"],
503 },
504 ]
505
506 group = f"test_add_hosts_group_{generate_random_string(length=10, with_punctuation=False)}"
507 inventory._add_hosts(hosts, group)
508
509 m_get_rds_hostname.assert_has_calls([call(h) for h in hosts], any_order=True)
510
511 hosts_names = ["db_i_001", "db_i_002", "test_cluster", "another_cluster"]
512 inventory.inventory.add_host.assert_has_calls([call(name, group=group) for name in hosts_names], any_order=True)
513
514 camel_hosts = [
515 {
516 "db_instance_identifier": "db_i_001",
517 "rds_tags": {"Name": "db_001", "RunningEngine": "mysql"},
518 "tags": {"Name": "db_001", "RunningEngine": "mysql"},
519 "availability_zone": "us-east-1a",
520 "region": "us-east-1",
521 },
522 {
523 "db_instance_identifier": "db_i_002",
524 "rds_tags": {"ClusterName": "test_cluster", "RunningOS": "CoreOS"},
525 "tags": {"ClusterName": "test_cluster", "RunningOS": "CoreOS"},
526 },
527 {
528 "db_cluster_identifier": "test_cluster",
529 "rds_tags": {"CluserVersionOrigin": "2.0", "Provider": "RedHat"},
530 "tags": {"CluserVersionOrigin": "2.0", "Provider": "RedHat"},
531 },
532 {
533 "db_cluster_identifier": "another_cluster",
534 "rds_tags": {"TestingPurpose": "Ansible"},
535 "tags": {"TestingPurpose": "Ansible"},
536 "availability_zones": ["us-west-1a", "us-east-1b"],
537 "region": "us-west-1",
538 },
539 ]
540
541 set_variable_calls = []
542 for i in range(len(camel_hosts)):
543 for var, value in camel_hosts[i].items():
544 if hostvars_prefix:
545 var = _options["hostvars_prefix"] + var
546 if hostvars_suffix:
547 var += _options["hostvars_suffix"]
548 set_variable_calls.append(call(hosts_names[i], var, value))
549
550 inventory.inventory.set_variable.assert_has_calls(set_variable_calls, any_order=True)
551
552 if hostvars_prefix or hostvars_suffix:
553 tmp = []
554 for host in camel_hosts:
555 new_host = copy.deepcopy(host)
556 for key, value in host.items():
557 new_key = key
558 if hostvars_prefix:
559 new_key = _options["hostvars_prefix"] + new_key
560 if hostvars_suffix:
561 new_key += _options["hostvars_suffix"]
562 new_host[new_key] = value
563 tmp.append(new_host)
564 camel_hosts = tmp
565
566 inventory._set_composite_vars.assert_has_calls(
567 [
568 call(_options["compose"], camel_hosts[i], hosts_names[i], strict=_options["strict"])
569 for i in range(len(camel_hosts))
570 ],
571 any_order=True,
572 )
573 inventory._add_host_to_composed_groups.assert_has_calls(
574 [
575 call(_options["groups"], camel_hosts[i], hosts_names[i], strict=_options["strict"])
576 for i in range(len(camel_hosts))
577 ],
578 any_order=True,
579 )
580 inventory._add_host_to_keyed_groups.assert_has_calls(
581 [
582 call(_options["keyed_groups"], camel_hosts[i], hosts_names[i], strict=_options["strict"])
583 for i in range(len(camel_hosts))
584 ],
585 any_order=True,
586 )
587
588
589 BASE_INVENTORY_PARSE = "ansible_collections.amazon.aws.plugins.inventory.aws_rds.AWSInventoryBase.parse"
590
591
592 @pytest.mark.parametrize("include_clusters", [True, False])
593 @pytest.mark.parametrize("filter_db_cluster_id", [True, False])
594 @pytest.mark.parametrize("user_cache_directive", [True, False])
595 @pytest.mark.parametrize("cache", [True, False])
596 @pytest.mark.parametrize("cache_hit", [True, False])
597 @patch(BASE_INVENTORY_PARSE)
598 def test_inventory_parse(
599 m_parse, inventory, include_clusters, filter_db_cluster_id, user_cache_directive, cache, cache_hit
600 ):
601 inventory_data = MagicMock()
602 loader = MagicMock()
603 path = generate_random_string(with_punctuation=False, with_digits=False)
604
605 options = {}
606 options["regions"] = [f"us-east-{d}" for d in range(random.randint(1, 5))]
607 options["strict_permissions"] = random.choice((True, False))
608 options["statuses"] = generate_random_string(with_punctuation=False)
609 options["include_clusters"] = include_clusters
610 options["filters"] = {
611 "db-instance-id": [
612 f"arn:db:{generate_random_string(with_punctuation=False)}" for i in range(random.randint(1, 10))
613 ],
614 "dbi-resource-id": generate_random_string(with_punctuation=False),
615 "domain": generate_random_string(with_digits=False, with_punctuation=False),
616 "engine": generate_random_string(with_digits=False, with_punctuation=False),
617 }
618 if filter_db_cluster_id:
619 options["filters"]["db-cluster-id"] = [
620 f"arn:cluster:{generate_random_string(with_punctuation=False)}" for i in range(random.randint(1, 10))
621 ]
622
623 options["cache"] = user_cache_directive
624
625 def get_option_side_effect(v):
626 return options.get(v)
627
628 inventory.get_option.side_effect = get_option_side_effect
629
630 cache_key = path + generate_random_string()
631 inventory.get_cache_key.return_value = cache_key
632
633 cache_key_value = generate_random_string()
634 if cache_hit:
635 inventory._cache[cache_key] = cache_key_value
636
637 inventory._populate = MagicMock()
638 inventory._populate_from_source = MagicMock()
639 inventory._get_all_db_hosts = MagicMock()
640 all_db_hosts = [
641 {"host": f"host_{int(random.randint(1, 1000))}"},
642 {"host": f"host_{int(random.randint(1, 1000))}"},
643 {"host": f"host_{int(random.randint(1, 1000))}"},
644 {"host": f"host_{int(random.randint(1, 1000))}"},
645 ]
646 inventory._get_all_db_hosts.return_value = all_db_hosts
647
648 format_cache_key_value = f"format_inventory_{all_db_hosts}"
649 inventory._format_inventory = MagicMock()
650 inventory._format_inventory.return_value = format_cache_key_value
651
652 inventory.parse(inventory_data, loader, path, cache)
653
654 m_parse.assert_called_with(inventory_data, loader, path, cache=cache)
655
656 boto3_instance_filters = ansible_dict_to_boto3_filter_list(options["filters"])
657 boto3_cluster_filters = []
658 if filter_db_cluster_id and include_clusters:
659 boto3_cluster_filters = ansible_dict_to_boto3_filter_list(
660 {"db-cluster-id": options["filters"]["db-cluster-id"]}
661 )
662
663 if not cache or not user_cache_directive or (cache and user_cache_directive and not cache_hit):
664 inventory._get_all_db_hosts.assert_called_with(
665 options["regions"],
666 boto3_instance_filters,
667 boto3_cluster_filters,
668 options["strict_permissions"],
669 options["statuses"],
670 include_clusters,
671 )
672 inventory._populate.assert_called_with(all_db_hosts)
673 inventory._format_inventory.assert_called_with(all_db_hosts)
674 else:
675 inventory._get_all_db_hosts.assert_not_called()
676 inventory._populate.assert_not_called()
677 inventory._format_inventory.assert_not_called()
678
679 if cache and user_cache_directive and cache_hit:
680 inventory._populate_from_source.assert_called_with(cache_key_value)
681
682 if cache and user_cache_directive and not cache_hit or (not cache and user_cache_directive):
683 # validate that cache was populated
684 assert inventory._cache[cache_key] == format_cache_key_value