Debian Codegraph @

test/integration/targets/module_utils/library/test_optional.py

raw
1 #!/usr/bin/python
2 # Most of these names are only available via PluginLoader so pylint doesn't
3 # know they exist
4 # pylint: disable=no-name-in-module
5 from __future__ import annotations
6
7 from ansible.module_utils.basic import AnsibleModule
8
9 # internal constants to keep pylint from griping about constant-valued conditionals
10 _private_false = False
11 _private_true = True
12
13 # module_utils import statements nested below any block are considered optional "best-effort" for AnsiballZ to include.
14 # test a number of different import shapes and nesting types to exercise this...
15
16 # first, some nested imports that should succeed...
17 try:
18 from ansible.module_utils.urls import fetch_url as yep1
19 except ImportError:
20 yep1 = None
21
22 try:
23 import ansible.module_utils.common.text.converters as yep2
24 except ImportError:
25 yep2 = None
26
27 try:
28 # optional import from a legit collection
29 from ansible_collections.testns.testcoll.plugins.module_utils.legit import importme as yep3
30 except ImportError:
31 yep3 = None
32
33 # and a bunch that should fail to be found, but not break the module_utils payload build in the process...
34 try:
35 from ansible.module_utils.bogus import fromnope1
36 except ImportError:
37 fromnope1 = None
38
39 if _private_false:
40 from ansible.module_utils.alsobogus import fromnope2
41 else:
42 fromnope2 = None
43
44 try:
45 import ansible.module_utils.verybogus
46 nope1 = ansible.module_utils.verybogus
47 except ImportError:
48 nope1 = None
49
50 # deepish nested with multiple block types- make sure the AST walker made it all the way down
51 try:
52 if _private_true:
53 if _private_true:
54 if _private_true:
55 if _private_true:
56 try:
57 import ansible.module_utils.stillbogus as nope2
58 except ImportError:
59 raise
60 except ImportError:
61 nope2 = None
62
63 try:
64 # optional import from a valid collection with an invalid package
65 from ansible_collections.testns.testcoll.plugins.module_utils.bogus import collnope1
66 except ImportError:
67 collnope1 = None
68
69 try:
70 # optional import from a bogus collection
71 from ansible_collections.bogusns.boguscoll.plugins.module_utils.bogus import collnope2
72 except ImportError:
73 collnope2 = None
74
75 module = AnsibleModule(argument_spec={})
76
77 if not all([yep1, yep2, yep3]):
78 module.fail_json(msg='one or more existing optional imports did not resolve')
79
80 if any([fromnope1, fromnope2, nope1, nope2, collnope1, collnope2]):
81 module.fail_json(msg='one or more missing optional imports resolved unexpectedly')
82
83 module.exit_json(msg='all missing optional imports behaved as expected')