Debian Codegraph @

test/units/utils/collection_loader/test_collection_loader.py

raw
1 from __future__ import annotations
2
3 import inspect
4 import os
5 import pkgutil
6 import pytest
7 import re
8 import sys
9 import typing as t
10
11 from importlib import import_module
12
13 from ansible.modules import ping as ping_module
14 from ansible.utils.collection_loader import AnsibleCollectionConfig, AnsibleCollectionRef
15 from ansible.utils.collection_loader._collection_finder import (
16 _AnsibleCollectionFinder, _AnsibleCollectionLoader, _AnsibleCollectionNSPkgLoader, _AnsibleCollectionPkgLoader,
17 _AnsibleCollectionPkgLoaderBase, _AnsibleCollectionRootPkgLoader, _AnsibleNSTraversable, _AnsiblePathHookFinder,
18 _get_collection_name_from_path, _get_collection_role_path, _get_collection_metadata, _iter_modules_impl, _to_bytes, _to_text
19 )
20 from ansible.utils.collection_loader._collection_config import _EventSource
21 from unittest.mock import MagicMock, NonCallableMagicMock, patch
22
23
24 # fixture to ensure we always clean up the import stuff when we're done
25 @pytest.fixture(autouse=True, scope='function')
26 def teardown(*args, **kwargs):
27 yield
28 reset_collections_loader_state()
29
30 # BEGIN STANDALONE TESTS - these exercise behaviors of the individual components without the import machinery
31
32
33 @pytest.mark.filterwarnings(
34 'ignore:'
35 r'find_module\(\) is deprecated and slated for removal in Python 3\.12; use find_spec\(\) instead'
36 ':DeprecationWarning',
37 'ignore:'
38 r'FileFinder\.find_loader\(\) is deprecated and slated for removal in Python 3\.12; use find_spec\(\) instead'
39 ':DeprecationWarning',
40 )
41 @pytest.mark.skipif(sys.version_info >= (3, 12), reason='Testing Python 2 codepath (find_module) on Python 3, <= 3.11')
42 def test_find_module_py3_lt_312():
43 dir_to_a_file = os.path.dirname(ping_module.__file__)
44 path_hook_finder = _AnsiblePathHookFinder(_AnsibleCollectionFinder(), dir_to_a_file)
45
46 # setuptools may fall back to find_module on Python 3 if find_spec returns None
47 # see https://github.com/pypa/setuptools/pull/2918
48 assert path_hook_finder.find_spec('missing') is None
49 assert path_hook_finder.find_module('missing') is None
50
51
52 @pytest.mark.skipif(sys.version_info < (3, 12), reason='Testing Python 2 codepath (find_module) on Python >= 3.12')
53 def test_find_module_py3_gt_311():
54 dir_to_a_file = os.path.dirname(ping_module.__file__)
55 path_hook_finder = _AnsiblePathHookFinder(_AnsibleCollectionFinder(), dir_to_a_file)
56
57 # setuptools may fall back to find_module on Python 3 if find_spec returns None
58 # see https://github.com/pypa/setuptools/pull/2918
59 assert path_hook_finder.find_spec('missing') is None
60
61
62 def test_finder_setup():
63 # ensure scalar path is listified
64 f = _AnsibleCollectionFinder(paths='/bogus/bogus')
65 assert isinstance(f._n_collection_paths, list)
66
67 # ensure sys.path paths that have an ansible_collections dir are added to the end of the collections paths
68 with patch.object(sys, 'path', ['/bogus', default_test_collection_paths[1], '/morebogus', default_test_collection_paths[0]]):
69 with patch('os.path.isdir', side_effect=lambda x: b'bogus' not in x):
70 f = _AnsibleCollectionFinder(paths=['/explicit', '/other'])
71 assert f._n_collection_paths == ['/explicit', '/other', default_test_collection_paths[1], default_test_collection_paths[0]]
72
73 configured_paths = ['/bogus']
74 playbook_paths = ['/playbookdir']
75 with patch.object(sys, 'path', ['/bogus', '/playbookdir']) and patch('os.path.isdir', side_effect=lambda x: b'bogus' in x):
76 f = _AnsibleCollectionFinder(paths=configured_paths)
77 assert f._n_collection_paths == configured_paths
78
79 f.set_playbook_paths(playbook_paths)
80 assert f._n_collection_paths == extend_paths(playbook_paths, 'collections') + configured_paths
81
82 # ensure scalar playbook_paths gets listified
83 f.set_playbook_paths(playbook_paths[0])
84 assert f._n_collection_paths == extend_paths(playbook_paths, 'collections') + configured_paths
85
86
87 def test_finder_not_interested():
88 f = get_default_finder()
89 assert f.find_module('nothanks') is None
90 assert f.find_module('nothanks.sub', path=['/bogus/dir']) is None
91
92
93 def test_finder_ns():
94 # ensure we can still load ansible_collections and ansible_collections.ansible when they don't exist on disk
95 f = _AnsibleCollectionFinder(paths=['/bogus/bogus'])
96 loader = f.find_module('ansible_collections')
97 assert isinstance(loader, _AnsibleCollectionRootPkgLoader)
98
99 loader = f.find_module('ansible_collections.ansible', path=['/bogus/bogus'])
100 assert isinstance(loader, _AnsibleCollectionNSPkgLoader)
101
102 f = get_default_finder()
103 loader = f.find_module('ansible_collections')
104 assert isinstance(loader, _AnsibleCollectionRootPkgLoader)
105
106 # path is not allowed for top-level
107 with pytest.raises(ValueError):
108 f.find_module('ansible_collections', path=['whatever'])
109
110 # path is required for subpackages
111 with pytest.raises(ValueError):
112 f.find_module('ansible_collections.whatever', path=None)
113
114 paths = [os.path.join(p, 'ansible_collections/nonexistns') for p in default_test_collection_paths]
115
116 # test missing
117 loader = f.find_module('ansible_collections.nonexistns', paths)
118 assert loader is None
119
120
121 # keep these up top to make sure the loader install/remove are working, since we rely on them heavily in the tests
122 def test_loader_remove():
123 fake_mp = [MagicMock(), _AnsibleCollectionFinder(), MagicMock(), _AnsibleCollectionFinder()]
124 fake_ph = [MagicMock().m1, MagicMock().m2, _AnsibleCollectionFinder()._ansible_collection_path_hook, NonCallableMagicMock]
125 # must nest until 2.6 compilation is totally donezo
126 with patch.object(sys, 'meta_path', fake_mp):
127 with patch.object(sys, 'path_hooks', fake_ph):
128 _AnsibleCollectionFinder()._remove()
129 assert len(sys.meta_path) == 2
130 # no AnsibleCollectionFinders on the meta path after remove is called
131 assert all((not isinstance(mpf, _AnsibleCollectionFinder) for mpf in sys.meta_path))
132 assert len(sys.path_hooks) == 3
133 # none of the remaining path hooks should point at an AnsibleCollectionFinder
134 assert all((not isinstance(ph.__self__, _AnsibleCollectionFinder) for ph in sys.path_hooks if hasattr(ph, '__self__')))
135 assert AnsibleCollectionConfig.collection_finder is None
136
137
138 def test_loader_install():
139 fake_mp = [MagicMock(), _AnsibleCollectionFinder(), MagicMock(), _AnsibleCollectionFinder()]
140 fake_ph = [MagicMock().m1, MagicMock().m2, _AnsibleCollectionFinder()._ansible_collection_path_hook, NonCallableMagicMock]
141 # must nest until 2.6 compilation is totally donezo
142 with patch.object(sys, 'meta_path', fake_mp):
143 with patch.object(sys, 'path_hooks', fake_ph):
144 f = _AnsibleCollectionFinder()
145 f._install()
146 assert len(sys.meta_path) == 3 # should have removed the existing ACFs and installed a new one
147 assert sys.meta_path[0] is f # at the front
148 # the rest of the meta_path should not be AnsibleCollectionFinders
149 assert all((not isinstance(mpf, _AnsibleCollectionFinder) for mpf in sys.meta_path[1:]))
150 assert len(sys.path_hooks) == 4 # should have removed the existing ACF path hooks and installed a new one
151 # the first path hook should be ours, make sure it's pointing at the right instance
152 assert hasattr(sys.path_hooks[0], '__self__') and sys.path_hooks[0].__self__ is f
153 # the rest of the path_hooks should not point at an AnsibleCollectionFinder
154 assert all((not isinstance(ph.__self__, _AnsibleCollectionFinder) for ph in sys.path_hooks[1:] if hasattr(ph, '__self__')))
155 assert AnsibleCollectionConfig.collection_finder is f
156 with pytest.raises(ValueError):
157 AnsibleCollectionConfig.collection_finder = f
158
159
160 def test_finder_coll():
161 f = get_default_finder()
162
163 tests = [
164 {'name': 'ansible_collections.testns.testcoll', 'test_paths': [default_test_collection_paths]},
165 {'name': 'ansible_collections.ansible.builtin', 'test_paths': [['/bogus'], default_test_collection_paths]},
166 ]
167 # ensure finder works for legit paths and bogus paths
168 for test_dict in tests:
169 # splat the dict values to our locals
170 globals().update(test_dict)
171 parent_pkg = name.rpartition('.')[0]
172 for paths in test_paths:
173 paths = [os.path.join(p, parent_pkg.replace('.', '/')) for p in paths]
174 loader = f.find_module(name, path=paths)
175 assert isinstance(loader, _AnsibleCollectionPkgLoader)
176
177
178 def test_root_loader_not_interested():
179 with pytest.raises(ImportError):
180 _AnsibleCollectionRootPkgLoader('not_ansible_collections_toplevel', path_list=[])
181
182 with pytest.raises(ImportError):
183 _AnsibleCollectionRootPkgLoader('ansible_collections.somens', path_list=['/bogus'])
184
185
186 def test_root_loader():
187 name = 'ansible_collections'
188 # ensure this works even when ansible_collections doesn't exist on disk
189 for paths in [], default_test_collection_paths:
190 sys.modules.pop(name, None)
191 loader = _AnsibleCollectionRootPkgLoader(name, paths)
192 assert repr(loader).startswith('_AnsibleCollectionRootPkgLoader(path=')
193 module = loader.load_module(name)
194 assert module.__name__ == name
195 assert module.__path__ == [p for p in extend_paths(paths, name) if os.path.isdir(p)]
196 # even if the dir exists somewhere, this loader doesn't support get_data, so make __file__ a non-file
197 assert module.__file__ == '<ansible_synthetic_collection_package>'
198 assert module.__package__ == name
199 assert sys.modules.get(name) == module
200
201
202 def test_nspkg_loader_not_interested():
203 with pytest.raises(ImportError):
204 _AnsibleCollectionNSPkgLoader('not_ansible_collections_toplevel.something', path_list=[])
205
206 with pytest.raises(ImportError):
207 _AnsibleCollectionNSPkgLoader('ansible_collections.somens.somecoll', path_list=[])
208
209
210 def test_nspkg_loader_load_module():
211 # ensure the loader behaves on the toplevel and ansible packages for both legit and missing/bogus paths
212 for name in ['ansible_collections.ansible', 'ansible_collections.testns']:
213 parent_pkg = name.partition('.')[0]
214 module_to_load = name.rpartition('.')[2]
215 paths = extend_paths(default_test_collection_paths, parent_pkg)
216 existing_child_paths = [p for p in extend_paths(paths, module_to_load) if os.path.exists(p)]
217 sys.modules.pop(name, None)
218 loader = _AnsibleCollectionNSPkgLoader(name, path_list=paths)
219 assert repr(loader).startswith('_AnsibleCollectionNSPkgLoader(path=')
220 module = loader.load_module(name)
221 assert module.__name__ == name
222 assert isinstance(module.__loader__, _AnsibleCollectionNSPkgLoader)
223 assert module.__path__ == existing_child_paths
224 assert module.__package__ == name
225 assert module.__file__ == '<ansible_synthetic_collection_package>'
226 assert sys.modules.get(name) == module
227
228
229 def test_collpkg_loader_not_interested():
230 with pytest.raises(ImportError):
231 _AnsibleCollectionPkgLoader('not_ansible_collections', path_list=[])
232
233 with pytest.raises(ImportError):
234 _AnsibleCollectionPkgLoader('ansible_collections.ns', path_list=['/bogus/bogus'])
235
236
237 def test_collpkg_loader_load_module():
238 reset_collections_loader_state()
239 with patch('ansible.utils.collection_loader.AnsibleCollectionConfig') as p:
240 for name in ['ansible_collections.ansible.builtin', 'ansible_collections.testns.testcoll']:
241 parent_pkg = name.rpartition('.')[0]
242 module_to_load = name.rpartition('.')[2]
243 paths = extend_paths(default_test_collection_paths, parent_pkg)
244 existing_child_paths = [p for p in extend_paths(paths, module_to_load) if os.path.exists(p)]
245 is_builtin = 'ansible.builtin' in name
246 sys.modules.pop(name, None)
247 loader = _AnsibleCollectionPkgLoader(name, path_list=paths)
248 assert repr(loader).startswith('_AnsibleCollectionPkgLoader(path=')
249 module = loader.load_module(name)
250 assert module.__name__ == name
251 assert isinstance(module.__loader__, _AnsibleCollectionPkgLoader)
252 if is_builtin:
253 assert module.__path__ == []
254 else:
255 assert module.__path__ == [existing_child_paths[0]]
256
257 assert module.__package__ == name
258 if is_builtin:
259 assert module.__file__ == '<ansible_synthetic_collection_package>'
260 else:
261 assert module.__file__.endswith('__synthetic__') and os.path.isdir(os.path.dirname(module.__file__))
262 assert sys.modules.get(name) == module
263
264 assert hasattr(module, '_collection_meta') and isinstance(module._collection_meta, dict)
265
266 # FIXME: validate _collection_meta contents match what's on disk (or not)
267
268 # verify the module has metadata, then try loading it with busted metadata
269 assert module._collection_meta
270
271 _collection_finder = import_module('ansible.utils.collection_loader._collection_finder')
272
273 with patch.object(_collection_finder, '_meta_yml_to_dict', side_effect=Exception('bang')):
274 with pytest.raises(Exception) as ex:
275 _AnsibleCollectionPkgLoader(name, path_list=paths).load_module(name)
276
277 assert 'error parsing collection metadata' in str(ex.value)
278
279
280 def test_coll_loader():
281 with patch('ansible.utils.collection_loader.AnsibleCollectionConfig'):
282 with pytest.raises(ValueError):
283 # not a collection
284 _AnsibleCollectionLoader('ansible_collections')
285
286 with pytest.raises(ValueError):
287 # bogus paths
288 _AnsibleCollectionLoader('ansible_collections.testns.testcoll', path_list=[])
289
290 # FIXME: more
291
292
293 def test_path_hook_setup():
294 with patch.object(sys, 'path_hooks', []):
295 found_hook = None
296 pathhook_exc = None
297 try:
298 found_hook = _AnsiblePathHookFinder._get_filefinder_path_hook()
299 except Exception as phe:
300 pathhook_exc = phe
301
302 assert str(pathhook_exc) == 'need exactly one FileFinder import hook (found 0)'
303
304 assert repr(_AnsiblePathHookFinder(object(), '/bogus/path')) == "_AnsiblePathHookFinder(path='/bogus/path')"
305
306
307 def test_path_hook_importerror():
308 # ensure that AnsiblePathHookFinder.find_module swallows ImportError from path hook delegation on Py3, eg if the delegated
309 # path hook gets passed a file on sys.path (python36.zip)
310 reset_collections_loader_state()
311 path_to_a_file = os.path.join(default_test_collection_paths[0], 'ansible_collections/testns/testcoll/plugins/action/my_action.py')
312 # it's a bug if the following pops an ImportError...
313 assert _AnsiblePathHookFinder(_AnsibleCollectionFinder(), path_to_a_file).find_module('foo.bar.my_action') is None
314
315
316 def test_new_or_existing_module():
317 module_name = 'blar.test.module'
318 pkg_name = module_name.rpartition('.')[0]
319
320 # create new module case
321 nuke_module_prefix(module_name)
322 with _AnsibleCollectionPkgLoaderBase._new_or_existing_module(module_name, __package__=pkg_name) as new_module:
323 # the module we just created should now exist in sys.modules
324 assert sys.modules.get(module_name) is new_module
325 assert new_module.__name__ == module_name
326
327 # the module should stick since we didn't raise an exception in the contextmgr
328 assert sys.modules.get(module_name) is new_module
329
330 # reuse existing module case
331 with _AnsibleCollectionPkgLoaderBase._new_or_existing_module(module_name, __attr1__=42, blar='yo') as existing_module:
332 assert sys.modules.get(module_name) is new_module # should be the same module we created earlier
333 assert hasattr(existing_module, '__package__') and existing_module.__package__ == pkg_name
334 assert hasattr(existing_module, '__attr1__') and existing_module.__attr1__ == 42
335 assert hasattr(existing_module, 'blar') and existing_module.blar == 'yo'
336
337 # exception during update existing shouldn't zap existing module from sys.modules
338 with pytest.raises(ValueError) as ve:
339 with _AnsibleCollectionPkgLoaderBase._new_or_existing_module(module_name) as existing_module:
340 err_to_raise = ValueError('bang')
341 raise err_to_raise
342 # make sure we got our error
343 assert ve.value is err_to_raise
344 # and that the module still exists
345 assert sys.modules.get(module_name) is existing_module
346
347 # test module removal after exception during creation
348 nuke_module_prefix(module_name)
349 with pytest.raises(ValueError) as ve:
350 with _AnsibleCollectionPkgLoaderBase._new_or_existing_module(module_name) as new_module:
351 err_to_raise = ValueError('bang')
352 raise err_to_raise
353 # make sure we got our error
354 assert ve.value is err_to_raise
355 # and that the module was removed
356 assert sys.modules.get(module_name) is None
357
358
359 def test_iter_modules_impl():
360 modules_trailer = 'ansible_collections/testns/testcoll/plugins'
361 modules_pkg_prefix = modules_trailer.replace('/', '.') + '.'
362 modules_path = os.path.join(default_test_collection_paths[0], modules_trailer)
363 modules = list(_iter_modules_impl([modules_path], modules_pkg_prefix))
364
365 assert modules
366 assert set([('ansible_collections.testns.testcoll.plugins.action', True),
367 ('ansible_collections.testns.testcoll.plugins.module_utils', True),
368 ('ansible_collections.testns.testcoll.plugins.modules', True)]) == set(modules)
369
370 modules_trailer = 'ansible_collections/testns/testcoll/plugins/modules'
371 modules_pkg_prefix = modules_trailer.replace('/', '.') + '.'
372 modules_path = os.path.join(default_test_collection_paths[0], modules_trailer)
373 modules = list(_iter_modules_impl([modules_path], modules_pkg_prefix))
374
375 assert modules
376 assert len(modules) == 1
377 assert modules[0][0] == 'ansible_collections.testns.testcoll.plugins.modules.amodule' # name
378 assert modules[0][1] is False # is_pkg
379
380 # FIXME: more
381
382
383 # BEGIN IN-CIRCUIT TESTS - these exercise behaviors of the loader when wired up to the import machinery
384
385
386 def test_import_from_collection(monkeypatch):
387 collection_root = os.path.join(os.path.dirname(__file__), 'fixtures', 'collections')
388 collection_path = os.path.join(collection_root, 'ansible_collections/testns/testcoll/plugins/module_utils/my_util.py')
389
390 # THIS IS UNSTABLE UNDER A DEBUGGER
391 # the trace we're expecting to be generated when running the code below:
392 # answer = question()
393 expected_trace_log = [
394 (collection_path, 5, 'call'),
395 (collection_path, 6, 'line'),
396 (collection_path, 6, 'return'),
397 ]
398
399 # define the collection root before any ansible code has been loaded
400 # otherwise config will have already been loaded and changing the environment will have no effect
401 monkeypatch.setenv('ANSIBLE_COLLECTIONS_PATH', collection_root)
402
403 finder = _AnsibleCollectionFinder(paths=[collection_root])
404 reset_collections_loader_state(finder)
405
406 from ansible_collections.testns.testcoll.plugins.module_utils.my_util import question
407
408 original_trace_function = sys.gettrace()
409 trace_log = []
410
411 if original_trace_function: # pragma: nocover
412 # enable tracing while preserving the existing trace function (coverage)
413 def my_trace_function(frame, event, arg):
414 trace_log.append((frame.f_code.co_filename, frame.f_lineno, event))
415
416 # the original trace function expects to have itself set as the trace function
417 sys.settrace(original_trace_function)
418 # call the original trace function
419 original_trace_function(frame, event, arg)
420 # restore our trace function
421 sys.settrace(my_trace_function)
422
423 return my_trace_function
424 else: # pragma: nocover
425 # no existing trace function, so our trace function is much simpler
426 def my_trace_function(frame, event, arg):
427 trace_log.append((frame.f_code.co_filename, frame.f_lineno, event))
428
429 return my_trace_function
430
431 sys.settrace(my_trace_function)
432
433 try:
434 # run a minimal amount of code while the trace is running
435 # adding more code here, including use of a context manager, will add more to our trace
436 answer = question()
437 finally:
438 sys.settrace(original_trace_function)
439
440 # make sure 'import ... as ...' works on builtin synthetic collections
441 # the following import is not supported (it tries to find module_utils in ansible.plugins)
442 # import ansible_collections.ansible.builtin.plugins.module_utils as c1
443 import ansible_collections.ansible.builtin.plugins.action as c2
444 import ansible_collections.ansible.builtin.plugins as c3
445 import ansible_collections.ansible.builtin as c4
446 import ansible_collections.ansible as c5
447 import ansible_collections as c6
448
449 # make sure 'import ...' works on builtin synthetic collections
450 import ansible_collections.ansible.builtin.plugins.module_utils
451
452 import ansible_collections.ansible.builtin.plugins.action
453 assert ansible_collections.ansible.builtin.plugins.action == c3.action == c2
454
455 import ansible_collections.ansible.builtin.plugins
456 assert ansible_collections.ansible.builtin.plugins == c4.plugins == c3
457
458 import ansible_collections.ansible.builtin
459 assert ansible_collections.ansible.builtin == c5.builtin == c4
460
461 import ansible_collections.ansible
462 assert ansible_collections.ansible == c6.ansible == c5
463
464 import ansible_collections
465 assert ansible_collections == c6
466
467 # make sure 'from ... import ...' works on builtin synthetic collections
468 from ansible_collections.ansible import builtin
469 from ansible_collections.ansible.builtin import plugins
470 assert builtin.plugins == plugins
471
472 from ansible_collections.ansible.builtin.plugins import action
473 from ansible_collections.ansible.builtin.plugins.action import command
474 assert action.command == command
475
476 from ansible_collections.ansible.builtin.plugins.module_utils import basic
477 from ansible_collections.ansible.builtin.plugins.module_utils.basic import AnsibleModule
478 assert basic.AnsibleModule == AnsibleModule
479
480 # make sure relative imports work from collections code
481 # these require __package__ to be set correctly
482 import ansible_collections.testns.testcoll.plugins.module_utils.my_other_util
483 import ansible_collections.testns.testcoll.plugins.action.my_action
484
485 # verify that code loaded from a collection does not inherit __future__ statements from the collection loader
486 # if the collection code inherits the annotations future feature from the collection loader this will fail
487 assert inspect.get_annotations(question)['return'] is float
488
489 # verify that the filename and line number reported by the trace is correct
490 # this makes sure that collection loading preserves file paths and line numbers
491 assert trace_log == expected_trace_log
492
493
494 def test_eventsource():
495 es = _EventSource()
496 # fire when empty should succeed
497 es.fire(42)
498 handler1 = MagicMock()
499 handler2 = MagicMock()
500 es += handler1
501 es.fire(99, my_kwarg='blah')
502 handler1.assert_called_with(99, my_kwarg='blah')
503 es += handler2
504 es.fire(123, foo='bar')
505 handler1.assert_called_with(123, foo='bar')
506 handler2.assert_called_with(123, foo='bar')
507 es -= handler2
508 handler1.reset_mock()
509 handler2.reset_mock()
510 es.fire(123, foo='bar')
511 handler1.assert_called_with(123, foo='bar')
512 handler2.assert_not_called()
513 es -= handler1
514 handler1.reset_mock()
515 es.fire('blah', kwarg=None)
516 handler1.assert_not_called()
517 handler2.assert_not_called()
518 es -= handler1 # should succeed silently
519 handler_bang = MagicMock(side_effect=Exception('bang'))
520 es += handler_bang
521 with pytest.raises(Exception) as ex:
522 es.fire(123)
523 assert 'bang' in str(ex.value)
524 handler_bang.assert_called_with(123)
525 with pytest.raises(ValueError):
526 es += 42
527
528
529 def test_on_collection_load():
530 finder = get_default_finder()
531 reset_collections_loader_state(finder)
532
533 load_handler = MagicMock()
534 AnsibleCollectionConfig.on_collection_load += load_handler
535
536 m = import_module('ansible_collections.testns.testcoll')
537 load_handler.assert_called_once_with(collection_name='testns.testcoll', collection_path=os.path.dirname(m.__file__))
538
539 _meta = _get_collection_metadata('testns.testcoll')
540 assert _meta
541 # FIXME: compare to disk
542
543 finder = get_default_finder()
544 reset_collections_loader_state(finder)
545
546 AnsibleCollectionConfig.on_collection_load += MagicMock(side_effect=Exception('bang'))
547 with pytest.raises(Exception) as ex:
548 import_module('ansible_collections.testns.testcoll')
549 assert 'bang' in str(ex.value)
550
551
552 def test_default_collection_config():
553 finder = get_default_finder()
554 reset_collections_loader_state(finder)
555 assert AnsibleCollectionConfig.default_collection is None
556 AnsibleCollectionConfig.default_collection = 'foo.bar'
557 assert AnsibleCollectionConfig.default_collection == 'foo.bar'
558
559
560 def test_default_collection_detection():
561 finder = get_default_finder()
562 reset_collections_loader_state(finder)
563
564 # we're clearly not under a collection path
565 assert _get_collection_name_from_path('/') is None
566
567 # something that looks like a collection path but isn't importable by our finder
568 assert _get_collection_name_from_path('/foo/ansible_collections/bogusns/boguscoll/bar') is None
569
570 # legit, at the top of the collection
571 live_collection_path = os.path.join(os.path.dirname(__file__), 'fixtures/collections/ansible_collections/testns/testcoll')
572 assert _get_collection_name_from_path(live_collection_path) == 'testns.testcoll'
573
574 # legit, deeper inside the collection
575 live_collection_deep_path = os.path.join(live_collection_path, 'plugins/modules')
576 assert _get_collection_name_from_path(live_collection_deep_path) == 'testns.testcoll'
577
578 # this one should be hidden by the real testns.testcoll, so should not resolve
579 masked_collection_path = os.path.join(os.path.dirname(__file__), 'fixtures/collections_masked/ansible_collections/testns/testcoll')
580 assert _get_collection_name_from_path(masked_collection_path) is None
581
582
583 @pytest.mark.parametrize(
584 'role_name,collection_list,expected_collection_name,expected_path_suffix',
585 [
586 ('some_role', ['testns.testcoll', 'ansible.bogus'], 'testns.testcoll', 'testns/testcoll/roles/some_role'),
587 ('testns.testcoll.some_role', ['ansible.bogus', 'testns.testcoll'], 'testns.testcoll', 'testns/testcoll/roles/some_role'),
588 ('testns.testcoll.some_role', [], 'testns.testcoll', 'testns/testcoll/roles/some_role'),
589 ('testns.testcoll.some_role', None, 'testns.testcoll', 'testns/testcoll/roles/some_role'),
590 ('some_role', [], None, None),
591 ('some_role', None, None, None),
592 ])
593 def test_collection_role_name_location(role_name, collection_list, expected_collection_name, expected_path_suffix):
594 finder = get_default_finder()
595 reset_collections_loader_state(finder)
596
597 expected_path = None
598 if expected_path_suffix:
599 expected_path = os.path.join(os.path.dirname(__file__), 'fixtures/collections/ansible_collections', expected_path_suffix)
600
601 found = _get_collection_role_path(role_name, collection_list)
602
603 if found:
604 assert found[0] == role_name.rpartition('.')[2]
605 assert found[1] == expected_path
606 assert found[2] == expected_collection_name
607 else:
608 assert expected_collection_name is None and expected_path_suffix is None
609
610
611 def test_bogus_imports():
612 finder = get_default_finder()
613 reset_collections_loader_state(finder)
614
615 # ensure ImportError on known-bogus imports
616 bogus_imports = ['bogus_toplevel', 'ansible_collections.bogusns', 'ansible_collections.testns.boguscoll',
617 'ansible_collections.testns.testcoll.bogussub', 'ansible_collections.ansible.builtin.bogussub']
618 for bogus_import in bogus_imports:
619 with pytest.raises(ImportError):
620 import_module(bogus_import)
621
622
623 def test_empty_vs_no_code():
624 finder = get_default_finder()
625 reset_collections_loader_state(finder)
626
627 from ansible_collections.testns import testcoll # synthetic package with no code on disk
628 from ansible_collections.testns.testcoll.plugins import module_utils # real package with empty code file
629
630 # ensure synthetic packages have no code object at all (prevent bogus coverage entries)
631 assert testcoll.__loader__.get_source(testcoll.__name__) is None
632 assert testcoll.__loader__.get_code(testcoll.__name__) is None
633
634 # ensure empty package inits do have a code object
635 assert module_utils.__loader__.get_source(module_utils.__name__) == b''
636 assert module_utils.__loader__.get_code(module_utils.__name__) is not None
637
638
639 def test_finder_playbook_paths():
640 finder = get_default_finder()
641 reset_collections_loader_state(finder)
642
643 import ansible_collections
644 import ansible_collections.ansible
645 import ansible_collections.testns
646
647 # ensure the package modules look like we expect
648 assert hasattr(ansible_collections, '__path__') and len(ansible_collections.__path__) > 0
649 assert hasattr(ansible_collections.ansible, '__path__') and len(ansible_collections.ansible.__path__) > 0
650 assert hasattr(ansible_collections.testns, '__path__') and len(ansible_collections.testns.__path__) > 0
651
652 # these shouldn't be visible yet, since we haven't added the playbook dir
653 with pytest.raises(ImportError):
654 import ansible_collections.ansible.playbook_adj_other
655
656 with pytest.raises(ImportError):
657 import ansible_collections.testns.playbook_adj_other
658
659 assert AnsibleCollectionConfig.playbook_paths == []
660 playbook_path_fixture_dir = os.path.join(os.path.dirname(__file__), 'fixtures/playbook_path')
661
662 # configure the playbook paths
663 AnsibleCollectionConfig.playbook_paths = [playbook_path_fixture_dir]
664
665 # playbook paths go to the front of the line
666 assert AnsibleCollectionConfig.collection_paths[0] == os.path.join(playbook_path_fixture_dir, 'collections')
667
668 # playbook paths should be updated on the existing root ansible_collections path, as well as on the 'ansible' namespace (but no others!)
669 assert ansible_collections.__path__[0] == os.path.join(playbook_path_fixture_dir, 'collections/ansible_collections')
670 assert ansible_collections.ansible.__path__[0] == os.path.join(playbook_path_fixture_dir, 'collections/ansible_collections/ansible')
671 assert all('playbook_path' not in p for p in ansible_collections.testns.__path__)
672
673 # should succeed since we fixed up the package path
674 import ansible_collections.ansible.playbook_adj_other
675 # should succeed since we didn't import freshns before hacking in the path
676 import ansible_collections.freshns.playbook_adj_other
677 # should fail since we've already imported something from this path and didn't fix up its package path
678 with pytest.raises(ImportError):
679 import ansible_collections.testns.playbook_adj_other
680
681
682 def test_toplevel_iter_modules():
683 finder = get_default_finder()
684 reset_collections_loader_state(finder)
685
686 modules = list(pkgutil.iter_modules(default_test_collection_paths, ''))
687 assert len(modules) == 1
688 assert modules[0][1] == 'ansible_collections'
689
690
691 def test_iter_modules_namespaces():
692 finder = get_default_finder()
693 reset_collections_loader_state(finder)
694
695 paths = extend_paths(default_test_collection_paths, 'ansible_collections')
696 modules = list(pkgutil.iter_modules(paths, 'ansible_collections.'))
697 assert len(modules) == 2
698 assert all(m[2] is True for m in modules)
699 assert all(isinstance(m[0], _AnsiblePathHookFinder) for m in modules)
700 assert set(['ansible_collections.testns', 'ansible_collections.ansible']) == set(m[1] for m in modules)
701
702
703 def test_collection_get_data():
704 finder = get_default_finder()
705 reset_collections_loader_state(finder)
706
707 # something that's there
708 d = pkgutil.get_data('ansible_collections.testns.testcoll', 'plugins/action/my_action.py')
709 assert b'hello from my_action.py' in d
710
711 # something that's not there
712 d = pkgutil.get_data('ansible_collections.testns.testcoll', 'bogus/bogus')
713 assert d is None
714
715 with pytest.raises(ValueError):
716 plugins_pkg = import_module('ansible_collections.ansible.builtin')
717 assert not os.path.exists(os.path.dirname(plugins_pkg.__file__))
718 d = pkgutil.get_data('ansible_collections.ansible.builtin', 'plugins/connection/local.py')
719
720
721 @pytest.mark.parametrize(
722 'ref,ref_type,expected_collection,expected_subdirs,expected_resource,expected_python_pkg_name',
723 [
724 ('ns.coll.myaction', 'action', 'ns.coll', '', 'myaction', 'ansible_collections.ns.coll.plugins.action'),
725 ('ns.coll.subdir1.subdir2.myaction', 'action', 'ns.coll', 'subdir1.subdir2', 'myaction', 'ansible_collections.ns.coll.plugins.action.subdir1.subdir2'),
726 ('ns.coll.myrole', 'role', 'ns.coll', '', 'myrole', 'ansible_collections.ns.coll.roles.myrole'),
727 ('ns.coll.subdir1.subdir2.myrole', 'role', 'ns.coll', 'subdir1.subdir2', 'myrole', 'ansible_collections.ns.coll.roles.subdir1.subdir2.myrole'),
728 ])
729 def test_fqcr_parsing_valid(ref, ref_type, expected_collection,
730 expected_subdirs, expected_resource, expected_python_pkg_name):
731 assert AnsibleCollectionRef.is_valid_fqcr(ref, ref_type)
732
733 r = AnsibleCollectionRef.from_fqcr(ref, ref_type)
734 assert r.collection == expected_collection
735 assert r.subdirs == expected_subdirs
736 assert r.resource == expected_resource
737 assert r.n_python_package_name == expected_python_pkg_name
738
739 r = AnsibleCollectionRef.try_parse_fqcr(ref, ref_type)
740 assert r.collection == expected_collection
741 assert r.subdirs == expected_subdirs
742 assert r.resource == expected_resource
743 assert r.n_python_package_name == expected_python_pkg_name
744
745
746 @pytest.mark.parametrize(
747 ('fqcn', 'expected'),
748 (
749 ('ns1.coll2', True),
750 ('ns1#coll2', False),
751 ('def.coll3', False),
752 ('ns4.return', False),
753 ('assert.this', False),
754 ('import.that', False),
755 ('.that', False),
756 ('this.', False),
757 ('.', False),
758 ('', False),
759 ),
760 )
761 def test_fqcn_validation(fqcn, expected):
762 """Verify that is_valid_collection_name validates FQCN correctly."""
763 assert AnsibleCollectionRef.is_valid_collection_name(fqcn) is expected
764
765
766 @pytest.mark.parametrize(
767 'ref,ref_type,expected_error_type,expected_error_expression',
768 [
769 ('no_dots_at_all_action', 'action', ValueError, 'is not a valid collection reference'),
770 ('no_nscoll.myaction', 'action', ValueError, 'is not a valid collection reference'),
771 ('no_nscoll%myaction', 'action', ValueError, 'is not a valid collection reference'),
772 ('ns.coll.myaction', 'bogus', ValueError, 'invalid collection ref_type'),
773 ])
774 def test_fqcr_parsing_invalid(ref, ref_type, expected_error_type, expected_error_expression):
775 assert not AnsibleCollectionRef.is_valid_fqcr(ref, ref_type)
776
777 with pytest.raises(expected_error_type) as curerr:
778 AnsibleCollectionRef.from_fqcr(ref, ref_type)
779
780 assert re.search(expected_error_expression, str(curerr.value))
781
782 r = AnsibleCollectionRef.try_parse_fqcr(ref, ref_type)
783 assert r is None
784
785
786 @pytest.mark.parametrize(
787 'name,subdirs,resource,ref_type,python_pkg_name',
788 [
789 ('ns.coll', None, 'res', 'doc_fragments', 'ansible_collections.ns.coll.plugins.doc_fragments'),
790 ('ns.coll', 'subdir1', 'res', 'doc_fragments', 'ansible_collections.ns.coll.plugins.doc_fragments.subdir1'),
791 ('ns.coll', 'subdir1.subdir2', 'res', 'action', 'ansible_collections.ns.coll.plugins.action.subdir1.subdir2'),
792 ])
793 def test_collectionref_components_valid(name, subdirs, resource, ref_type, python_pkg_name):
794 x = AnsibleCollectionRef(name, subdirs, resource, ref_type)
795
796 assert x.collection == name
797 if subdirs:
798 assert x.subdirs == subdirs
799 else:
800 assert x.subdirs == ''
801
802 assert x.resource == resource
803 assert x.ref_type == ref_type
804 assert x.n_python_package_name == python_pkg_name
805
806
807 @pytest.mark.parametrize(
808 'dirname,expected_result',
809 [
810 ('become_plugins', 'become'),
811 ('cache_plugins', 'cache'),
812 ('connection_plugins', 'connection'),
813 ('library', 'modules'),
814 ('filter_plugins', 'filter'),
815 ('bogus_plugins', ValueError),
816 (None, ValueError)
817 ]
818 )
819 def test_legacy_plugin_dir_to_plugin_type(dirname, expected_result):
820 if isinstance(expected_result, str):
821 assert AnsibleCollectionRef.legacy_plugin_dir_to_plugin_type(dirname) == expected_result
822 else:
823 with pytest.raises(expected_result):
824 AnsibleCollectionRef.legacy_plugin_dir_to_plugin_type(dirname)
825
826
827 @pytest.mark.parametrize(
828 'name,subdirs,resource,ref_type,expected_error_type,expected_error_expression',
829 [
830 ('bad_ns', '', 'resource', 'action', ValueError, 'invalid collection name'),
831 ('ns.coll.', '', 'resource', 'action', ValueError, 'invalid collection name'),
832 ('ns.coll', 'badsubdir#', 'resource', 'action', ValueError, 'invalid subdirs entry'),
833 ('ns.coll', 'badsubdir.', 'resource', 'action', ValueError, 'invalid subdirs entry'),
834 ('ns.coll', '.badsubdir', 'resource', 'action', ValueError, 'invalid subdirs entry'),
835 ('ns.coll', '', 'resource', 'bogus', ValueError, 'invalid collection ref_type'),
836 ])
837 def test_collectionref_components_invalid(name, subdirs, resource, ref_type, expected_error_type, expected_error_expression):
838 with pytest.raises(expected_error_type) as curerr:
839 AnsibleCollectionRef(name, subdirs, resource, ref_type)
840
841 assert re.search(expected_error_expression, str(curerr.value))
842
843
844 def test_importlib_resources():
845 from importlib.resources import files
846 from pathlib import Path
847
848 f = get_default_finder()
849 reset_collections_loader_state(f)
850
851 ansible_collections_ns = files('ansible_collections')
852 ansible_ns = files('ansible_collections.ansible')
853 testns = files('ansible_collections.testns')
854 testcoll = files('ansible_collections.testns.testcoll')
855 testcoll2 = files('ansible_collections.testns.testcoll2')
856 module_utils = files('ansible_collections.testns.testcoll.plugins.module_utils')
857
858 assert isinstance(ansible_collections_ns, _AnsibleNSTraversable)
859 assert isinstance(ansible_ns, _AnsibleNSTraversable)
860 assert isinstance(testcoll, Path)
861 assert isinstance(module_utils, Path)
862
863 assert ansible_collections_ns.is_dir()
864 assert ansible_ns.is_dir()
865 assert testcoll.is_dir()
866 assert module_utils.is_dir()
867
868 first_path = Path(default_test_collection_paths[0])
869 second_path = Path(default_test_collection_paths[1])
870 testns_paths = []
871 ansible_ns_paths = []
872 for path in default_test_collection_paths[:2]:
873 ansible_ns_paths.append(Path(path) / 'ansible_collections' / 'ansible')
874 testns_paths.append(Path(path) / 'ansible_collections' / 'testns')
875
876 assert testns._paths == testns_paths
877 # NOTE: The next two asserts check for subsets to accommodate running the unit tests when externally installed collections are available.
878 assert set(ansible_ns_paths).issubset(ansible_ns._paths)
879 assert set(Path(p) / 'ansible_collections' for p in default_test_collection_paths[:2]).issubset(ansible_collections_ns._paths)
880 assert testcoll2 == second_path / 'ansible_collections' / 'testns' / 'testcoll2'
881
882 assert {p.name for p in module_utils.glob('*.py')} == {'__init__.py', 'my_other_util.py', 'my_util.py'}
883 nestcoll_mu_init = first_path / 'ansible_collections' / 'testns' / 'testcoll' / 'plugins' / 'module_utils' / '__init__.py'
884 assert next(module_utils.glob('__init__.py')) == nestcoll_mu_init
885
886
887 # BEGIN TEST SUPPORT
888
889 default_test_collection_paths = [
890 os.path.join(os.path.dirname(__file__), 'fixtures', 'collections'),
891 os.path.join(os.path.dirname(__file__), 'fixtures', 'collections_masked'),
892 '/bogus/bogussub'
893 ]
894
895
896 def get_default_finder():
897 return _AnsibleCollectionFinder(paths=default_test_collection_paths)
898
899
900 def extend_paths(path_list, suffix):
901 suffix = suffix.replace('.', '/')
902 return [os.path.join(p, suffix) for p in path_list]
903
904
905 def nuke_module_prefix(prefix):
906 for module_to_nuke in [m for m in sys.modules if m.startswith(prefix)]:
907 sys.modules.pop(module_to_nuke)
908
909
910 def reset_collections_loader_state(metapath_finder=None):
911 _AnsibleCollectionFinder._remove()
912
913 nuke_module_prefix('ansible_collections')
914 nuke_module_prefix('ansible.modules')
915 nuke_module_prefix('ansible.plugins')
916
917 # FIXME: better to move this someplace else that gets cleaned up automatically?
918 _AnsibleCollectionLoader._redirected_package_map = {}
919
920 AnsibleCollectionConfig._default_collection = None
921 AnsibleCollectionConfig._on_collection_load = _EventSource()
922
923 if metapath_finder:
924 metapath_finder._install()
925
926
927 class SurrogateEncryptedString:
928 def __init__(self, value) -> None:
929 self._value = value
930
931 def _decrypt(self) -> str:
932 return self._value
933
934
935 @pytest.mark.parametrize('value, expected_result', (
936 (b'somebytes', 'somebytes'),
937 (SurrogateEncryptedString("encrypted"), "encrypted"),
938 ('astring', 'astring'),
939 (None, None),
940 (1.2, TypeError),
941 ))
942 def test_to_text(value: t.Any, expected_result: t.Any) -> None:
943 """Validate the private `_to_text` implementation."""
944 if isinstance(expected_result, type) and issubclass(expected_result, Exception):
945 with pytest.raises(expected_result):
946 _to_text(value)
947 else:
948 assert _to_text(value) == expected_result
949
950
951 @pytest.mark.parametrize('value, expected_result', (
952 ('somestr', b'somestr'),
953 (SurrogateEncryptedString("encrypted"), b"encrypted"),
954 (b'somebytes', b'somebytes'),
955 (None, None),
956 (1.2, TypeError),
957 ))
958 def test_to_bytes(value: t.Any, expected_result: t.Any) -> None:
959 """Validate the private `_to_bytes` implementation."""
960 if isinstance(expected_result, type) and issubclass(expected_result, Exception):
961 with pytest.raises(expected_result):
962 _to_bytes(value)
963 else:
964 assert _to_bytes(value) == expected_result