Debian Codegraph @

test/units/galaxy/test_api.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright: (c) 2019, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 import json
8 import os
9 import re
10 import pytest
11 import stat
12 import tarfile
13 import tempfile
14 import time
15
16 from io import BytesIO, StringIO
17 from unittest.mock import MagicMock
18
19 import ansible.constants as C
20 from ansible import context
21 from ansible.errors import AnsibleError
22 from ansible.galaxy import api as galaxy_api
23 from ansible.galaxy.api import CollectionVersionMetadata, GalaxyAPI, GalaxyError
24 from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken
25 from ansible.module_utils.common.file import S_IRWU_RG_RO
26 from ansible.module_utils.common.text.converters import to_native, to_text
27 import urllib.error
28 from ansible.utils import context_objects as co
29 from ansible.utils.display import Display
30
31
32 @pytest.fixture(autouse=True)
33 def reset_cli_args():
34 co.GlobalCLIArgs._Singleton__instance = None
35 # Required to initialise the GalaxyAPI object
36 context.CLIARGS._store = {'ignore_certs': False}
37 yield
38 co.GlobalCLIArgs._Singleton__instance = None
39
40
41 @pytest.fixture()
42 def collection_artifact(tmp_path_factory):
43 """ Creates a collection artifact tarball that is ready to be published """
44 output_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Output'))
45
46 tar_path = os.path.join(output_dir, 'namespace-collection-v1.0.0.tar.gz')
47 with tarfile.open(tar_path, 'w:gz') as tfile:
48 b_io = BytesIO(b"\x00\x01\x02\x03")
49 tar_info = tarfile.TarInfo('test')
50 tar_info.size = 4
51 tar_info.mode = S_IRWU_RG_RO
52 tfile.addfile(tarinfo=tar_info, fileobj=b_io)
53
54 yield tar_path
55
56
57 @pytest.fixture()
58 def cache_dir(tmp_path_factory, monkeypatch):
59 cache_dir = to_text(tmp_path_factory.mktemp('Test ÅÑŚÌβŁÈ Galaxy Cache'))
60 monkeypatch.setattr(C, 'GALAXY_CACHE_DIR', cache_dir)
61
62 yield cache_dir
63
64
65 def get_test_galaxy_api(url, version, token_ins=None, token_value=None, no_cache=True):
66 token_value = token_value or "my token"
67 token_ins = token_ins or GalaxyToken(token_value)
68 api = GalaxyAPI(None, "test", url, no_cache=no_cache)
69 # Warning, this doesn't test g_connect() because _available_api_versions is set here. That means
70 # that urls for v2 servers have to append '/api/' themselves in the input data.
71 api._available_api_versions = {version: '%s' % version}
72 api.token = token_ins
73
74 return api
75
76
77 def get_v3_collection_versions(namespace='namespace', name='collection'):
78 pagination_path = f"/api/galaxy/content/community/v3/plugin/{namespace}/content/community/collections/index/{namespace}/{name}/versions"
79 page_versions = (('1.0.0', '1.0.1',), ('1.0.2', '1.0.3',), ('1.0.4', '1.0.5'),)
80 responses = [
81 {}, # TODO: initial response
82 ]
83
84 first = f"{pagination_path}/?limit=100"
85 last = f"{pagination_path}/?limit=100&offset=200"
86 page_versions = [
87 {
88 "versions": ('1.0.0', '1.0.1',),
89 "url": first,
90 },
91 {
92 "versions": ('1.0.2', '1.0.3',),
93 "url": f"{pagination_path}/?limit=100&offset=100",
94 },
95 {
96 "versions": ('1.0.4', '1.0.5'),
97 "url": last,
98 },
99 ]
100
101 previous = None
102 for page in range(0, len(page_versions)):
103 data = []
104
105 if page_versions[page]["url"] == last:
106 next_page = None
107 else:
108 next_page = page_versions[page + 1]["url"]
109 links = {"first": first, "last": last, "next": next_page, "previous": previous}
110
111 for version in page_versions[page]["versions"]:
112 data.append(
113 {
114 "version": f"{version}",
115 "href": f"{pagination_path}/{version}/",
116 "created_at": "2022-05-13T15:55:58.913107Z",
117 "updated_at": "2022-05-13T15:55:58.913121Z",
118 "requires_ansible": ">=2.9.10"
119 }
120 )
121
122 responses.append({"meta": {"count": 6}, "links": links, "data": data})
123
124 previous = page_versions[page]["url"]
125 return responses
126
127
128 def get_collection_versions(namespace='namespace', name='collection'):
129 base_url = f'/api/v3/plugin/ansible/content/published/collections/index/{namespace}/{name}/'
130 versions_url = f'{base_url}versions/'
131
132 # Response for collection info
133 responses = [
134 {
135 "href": base_url,
136 "name": name,
137 "namespace": namespace,
138 "highest_version": {
139 "href": f"{versions_url}1.0.5",
140 "version": "1.0.5",
141 },
142 "versions_url": versions_url,
143 "deprecated": False,
144 "created_at": "2021-02-09T16:55:42.749915-05:00",
145 "updated_at": "2021-02-09T16:55:42.749915-05:00",
146 }
147 ]
148
149 # Paginated responses for versions
150 page_versions = (('1.0.0', '1.0.1',), ('1.0.2', '1.0.3',), ('1.0.4', '1.0.5'),)
151 prev_page = None
152 for page in range(1, len(page_versions) + 1):
153 if page < len(page_versions):
154 next_page = f'{versions_url}?limit=2&offset={page + 1}'
155 else:
156 next_page = None
157
158 version_results = []
159 for version in page_versions[int(page - 1)]:
160 version_results.append(
161 {'version': version, 'href': versions_url + '{0}/'.format(version)}
162 )
163
164 responses.append(
165 {
166 'meta': {
167 'count': 6,
168 },
169 'links': {
170 'first': f'{versions_url}?limit=2&offset=0',
171 'next': next_page,
172 'previous': prev_page,
173 'last': f'{versions_url}?limit=2&offset={len(page_versions)}',
174 },
175 'data': version_results,
176 }
177 )
178 prev_page = page
179
180 return responses
181
182
183 def test_api_no_auth():
184 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/")
185 actual = {}
186 api._add_auth_token(actual, "")
187 assert actual == {}
188
189
190 def test_api_no_auth_but_required():
191 expected = "No access token or username set. A token can be set with --api-key or at "
192 with pytest.raises(AnsibleError, match=expected):
193 GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/")._add_auth_token({}, "", required=True)
194
195
196 def test_api_token_auth():
197 token = GalaxyToken(token=u"my_token")
198 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
199 actual = {}
200 api._add_auth_token(actual, "", required=True)
201 assert actual == {'Authorization': 'Token my_token'}
202
203
204 def test_api_token_auth_with_token_type(monkeypatch):
205 token = KeycloakToken(auth_url='https://api.test/')
206 mock_token_get = MagicMock()
207 mock_token_get.return_value = 'my_token'
208 monkeypatch.setattr(token, 'get', mock_token_get)
209 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
210 actual = {}
211 api._add_auth_token(actual, "", token_type="Bearer", required=True)
212 assert actual == {'Authorization': 'Bearer my_token'}
213
214
215 def test_api_token_auth_with_v3_url(monkeypatch):
216 token = KeycloakToken(auth_url='https://api.test/')
217 mock_token_get = MagicMock()
218 mock_token_get.return_value = 'my_token'
219 monkeypatch.setattr(token, 'get', mock_token_get)
220 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
221 actual = {}
222 api._add_auth_token(actual, "https://galaxy.ansible.com/api/v3/resource/name", required=True)
223 assert actual == {'Authorization': 'Bearer my_token'}
224
225
226 def test_api_token_auth_with_v2_url():
227 token = GalaxyToken(token=u"my_token")
228 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
229 actual = {}
230 # Add v3 to random part of URL but response should only see the v2 as the full URI path segment.
231 api._add_auth_token(actual, "https://galaxy.ansible.com/api/v2/resourcev3/name", required=True)
232 assert actual == {'Authorization': 'Token my_token'}
233
234
235 def test_api_basic_auth_password():
236 token = BasicAuthToken(username=u"user", password=u"pass")
237 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
238 actual = {}
239 api._add_auth_token(actual, "", required=True)
240 assert actual == {'Authorization': 'Basic dXNlcjpwYXNz'}
241
242
243 def test_api_basic_auth_no_password():
244 token = BasicAuthToken(username=u"user")
245 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
246 actual = {}
247 api._add_auth_token(actual, "", required=True)
248 assert actual == {'Authorization': 'Basic dXNlcjo='}
249
250
251 def test_api_dont_override_auth_header():
252 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/")
253 actual = {'Authorization': 'Custom token'}
254 api._add_auth_token(actual, "", required=True)
255 assert actual == {'Authorization': 'Custom token'}
256
257
258 def test_initialise_galaxy(monkeypatch):
259 mock_open = MagicMock()
260 mock_open.side_effect = [
261 StringIO(u'{"available_versions":{"v1":"v1/"}}'),
262 StringIO(u'{"token":"my token"}'),
263 ]
264 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
265
266 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/")
267 actual = api.authenticate("github_token")
268
269 assert len(api.available_api_versions) == 1
270 assert api.available_api_versions['v1'] == u'v1/'
271 assert actual == {u'token': u'my token'}
272 assert mock_open.call_count == 2
273 assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/'
274 assert 'ansible-galaxy' in mock_open.mock_calls[0][2]['http_agent']
275 assert mock_open.mock_calls[1][1][0] == 'https://galaxy.ansible.com/api/v1/tokens/'
276 assert 'ansible-galaxy' in mock_open.mock_calls[1][2]['http_agent']
277 assert mock_open.mock_calls[1][2]['data'] == 'github_token=github_token'
278
279
280 def test_initialise_galaxy_with_auth(monkeypatch):
281 mock_open = MagicMock()
282 mock_open.side_effect = [
283 StringIO(u'{"available_versions":{"v1":"v1/"}}'),
284 StringIO(u'{"token":"my token"}'),
285 ]
286 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
287
288 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=GalaxyToken(token='my_token'))
289 actual = api.authenticate("github_token")
290
291 assert len(api.available_api_versions) == 1
292 assert api.available_api_versions['v1'] == u'v1/'
293 assert actual == {u'token': u'my token'}
294 assert mock_open.call_count == 2
295 assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/'
296 assert 'ansible-galaxy' in mock_open.mock_calls[0][2]['http_agent']
297 assert mock_open.mock_calls[1][1][0] == 'https://galaxy.ansible.com/api/v1/tokens/'
298 assert 'ansible-galaxy' in mock_open.mock_calls[1][2]['http_agent']
299 assert mock_open.mock_calls[1][2]['data'] == 'github_token=github_token'
300
301
302 def test_initialise_automation_hub(monkeypatch):
303 mock_open = MagicMock()
304 mock_open.side_effect = [
305 StringIO(u'{"available_versions":{"v3":"v3/"}}'),
306 ]
307 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
308 token = KeycloakToken(auth_url='https://api.test/')
309 mock_token_get = MagicMock()
310 mock_token_get.return_value = 'my_token'
311 monkeypatch.setattr(token, 'get', mock_token_get)
312
313 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
314
315 assert len(api.available_api_versions) == 1
316 assert api.available_api_versions['v3'] == u'v3/'
317
318 assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/'
319 assert 'ansible-galaxy' in mock_open.mock_calls[0][2]['http_agent']
320 assert mock_open.mock_calls[0][2]['headers'] == {'Authorization': 'Bearer my_token'}
321
322
323 def test_initialise_unknown(monkeypatch):
324 mock_open = MagicMock()
325 mock_open.side_effect = [
326 urllib.error.HTTPError('https://galaxy.ansible.com/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
327 urllib.error.HTTPError('https://galaxy.ansible.com/api/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
328 ]
329 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
330
331 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=GalaxyToken(token='my_token'))
332
333 expected = "Error when finding available api versions from test (%s) (HTTP Code: 500, Message: msg)" \
334 % api.api_server
335 with pytest.raises(AnsibleError, match=re.escape(expected)):
336 api.authenticate("github_token")
337
338
339 def test_get_available_api_versions(monkeypatch):
340 mock_open = MagicMock()
341 mock_open.side_effect = [
342 StringIO(u'{"available_versions":{"v1":"v1/","v3":"v3/"}}'),
343 ]
344 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
345
346 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/")
347 actual = api.available_api_versions
348 assert len(actual) == 2
349 assert actual['v1'] == u'v1/'
350 assert actual['v3'] == u'v3/'
351
352 assert mock_open.call_count == 1
353 assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/'
354 assert 'ansible-galaxy' in mock_open.mock_calls[0][2]['http_agent']
355
356
357 def test_publish_collection_missing_file():
358 fake_path = u'/fake/ÅÑŚÌβŁÈ/path'
359 expected = to_native("The collection path specified '%s' does not exist." % fake_path)
360
361 api = get_test_galaxy_api("https://galaxy.ansible.com/api/", "v3")
362 with pytest.raises(AnsibleError, match=expected):
363 api.publish_collection(fake_path)
364
365
366 def test_publish_collection_not_a_tarball():
367 expected = "The collection path specified '{0}' is not a tarball, use 'ansible-galaxy collection build' to " \
368 "create a proper release artifact."
369
370 api = get_test_galaxy_api("https://galaxy.ansible.com/api/", "v3")
371 with tempfile.NamedTemporaryFile(prefix=u'ÅÑŚÌβŁÈ') as temp_file:
372 temp_file.write(b"\x00")
373 temp_file.flush()
374 with pytest.raises(AnsibleError, match=expected.format(to_native(temp_file.name))):
375 api.publish_collection(temp_file.name)
376
377
378 def test_publish_collection_unsupported_version():
379 expected = "Galaxy action publish_collection requires API versions 'v3' but only 'v1' are available on test " \
380 "https://galaxy.ansible.com/api/"
381
382 api = get_test_galaxy_api("https://galaxy.ansible.com/api/", "v1")
383 with pytest.raises(AnsibleError, match=expected):
384 api.publish_collection("path")
385
386
387 @pytest.mark.parametrize('api_version, collection_url', [
388 ('v3', 'artifacts/collections'),
389 ])
390 def test_publish_collection(api_version, collection_url, collection_artifact, monkeypatch):
391 api = get_test_galaxy_api("https://galaxy.ansible.com/api/", api_version)
392
393 mock_call = MagicMock()
394 mock_call.return_value = {'task': 'http://task.url/'}
395 monkeypatch.setattr(api, '_call_galaxy', mock_call)
396
397 actual = api.publish_collection(collection_artifact)
398 assert actual == 'http://task.url/'
399 assert mock_call.call_count == 1
400 assert mock_call.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/%s/%s/' % (api_version, collection_url)
401 assert mock_call.mock_calls[0][2]['headers']['Content-length'] == len(mock_call.mock_calls[0][2]['args'])
402 assert mock_call.mock_calls[0][2]['headers']['Content-type'].startswith(
403 'multipart/form-data; boundary=')
404 assert mock_call.mock_calls[0][2]['args'].startswith(b'--')
405 assert mock_call.mock_calls[0][2]['method'] == 'POST'
406 assert mock_call.mock_calls[0][2]['auth_required'] is True
407
408
409 @pytest.mark.parametrize('api_version, collection_url, response, expected', [
410 ('v3', 'artifact/collections', {},
411 'Error when publishing collection to test (%s) (HTTP Code: 500, Message: msg Code: Unknown)'),
412 ('v3', 'artifact/collections', {
413 'errors': [
414 {
415 'code': 'conflict.collection_exists',
416 'detail': 'Collection "mynamespace-mycollection-4.1.1" already exists.',
417 'title': 'Conflict.',
418 'status': '400',
419 },
420 {
421 'code': 'quantum_improbability',
422 'title': u'Rändom(?) quantum improbability.',
423 'source': {'parameter': 'the_arrow_of_time'},
424 'meta': {'remediation': 'Try again before'},
425 },
426 ],
427 }, u'Error when publishing collection to test (%s) (HTTP Code: 500, Message: Collection '
428 u'"mynamespace-mycollection-4.1.1" already exists. Code: conflict.collection_exists), (HTTP Code: 500, '
429 u'Message: Rändom(?) quantum improbability. Code: quantum_improbability)')
430 ])
431 def test_publish_failure(api_version, collection_url, response, expected, collection_artifact, monkeypatch):
432 api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version)
433
434 expected_url = '%s/api/%s/%s' % (api.api_server, api_version, collection_url)
435
436 mock_open = MagicMock()
437 mock_open.side_effect = urllib.error.HTTPError(expected_url, 500, 'msg', {},
438 StringIO(to_text(json.dumps(response))))
439 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
440
441 with pytest.raises(GalaxyError, match=re.escape(to_native(expected % api.api_server))):
442 api.publish_collection(collection_artifact)
443
444
445 @pytest.mark.parametrize('server_url, api_version, token_type, token_ins, full_import_uri', [
446 ('https://galaxy.server.com/api/automation-hub/', 'v3', 'Bearer', KeycloakToken(auth_url='https://api.test/'),
447 'https://galaxy.server.com/api/automation-hub/v3/imports/collections/1234/'),
448 ])
449 def test_wait_import_task(server_url, api_version, token_type, token_ins, full_import_uri, monkeypatch):
450 api = get_test_galaxy_api(server_url, api_version, token_ins=token_ins)
451
452 mock_token_get = MagicMock()
453 mock_token_get.return_value = 'my token'
454 monkeypatch.setattr(token_ins, 'get', mock_token_get)
455
456 mock_open = MagicMock()
457 mock_open.return_value = StringIO(u'{"state":"success","finished_at":"time"}')
458 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
459
460 mock_display = MagicMock()
461 monkeypatch.setattr(Display, 'display', mock_display)
462
463 api.wait_import_task(full_import_uri)
464
465 assert mock_open.call_count == 1
466 assert mock_open.mock_calls[0][1][0] == full_import_uri
467 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
468
469 assert mock_display.call_count == 1
470 assert mock_display.mock_calls[0][1][0] == 'Waiting until Galaxy import task %s has completed' % full_import_uri
471
472
473 @pytest.mark.parametrize('server_url, api_version, token_type, token_ins, full_import_uri', [
474 ('https://galaxy.server.com/api/automation-hub', 'v3', 'Bearer', KeycloakToken(auth_url='https://api.test/'),
475 'https://galaxy.server.com/api/automation-hub/v3/imports/collections/1234/'),
476 ])
477 def test_wait_import_task_multiple_requests(server_url, api_version, token_type, token_ins, full_import_uri, monkeypatch):
478 api = get_test_galaxy_api(server_url, api_version, token_ins=token_ins)
479
480 mock_token_get = MagicMock()
481 mock_token_get.return_value = 'my token'
482 monkeypatch.setattr(token_ins, 'get', mock_token_get)
483
484 mock_open = MagicMock()
485 mock_open.side_effect = [
486 StringIO(u'{"state":"test"}'),
487 StringIO(u'{"state":"success","finished_at":"time"}'),
488 ]
489 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
490
491 mock_display = MagicMock()
492 monkeypatch.setattr(Display, 'display', mock_display)
493
494 mock_vvv = MagicMock()
495 monkeypatch.setattr(Display, 'vvv', mock_vvv)
496
497 monkeypatch.setattr(time, 'sleep', MagicMock())
498
499 api.wait_import_task(full_import_uri)
500
501 assert mock_open.call_count == 2
502 assert mock_open.mock_calls[0][1][0] == full_import_uri
503 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
504 assert mock_open.mock_calls[1][1][0] == full_import_uri
505 assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type
506
507 assert mock_display.call_count == 1
508 assert mock_display.mock_calls[0][1][0] == 'Waiting until Galaxy import task %s has completed' % full_import_uri
509
510 assert mock_vvv.call_count == 1
511 assert mock_vvv.mock_calls[0][1][0] == \
512 'Galaxy import process has a status of test, wait 2 seconds before trying again'
513
514
515 @pytest.mark.parametrize('server_url, api_version, token_type, token_ins, full_import_uri,', [
516 ('https://galaxy.server.com/api/automation-hub/', 'v3', 'Bearer', KeycloakToken(auth_url='https://api.test/'),
517 'https://galaxy.server.com/api/automation-hub/v3/imports/collections/1234/'),
518 ])
519 def test_wait_import_task_with_failure(server_url, api_version, token_type, token_ins, full_import_uri, monkeypatch):
520 api = get_test_galaxy_api(server_url, api_version, token_ins=token_ins)
521
522 mock_token_get = MagicMock()
523 mock_token_get.return_value = 'my token'
524 monkeypatch.setattr(token_ins, 'get', mock_token_get)
525
526 mock_open = MagicMock()
527 mock_open.side_effect = [
528 StringIO(to_text(json.dumps({
529 'finished_at': 'some_time',
530 'state': 'failed',
531 'error': {
532 'code': 'GW001',
533 'description': u'Becäuse I said so!',
534
535 },
536 'messages': [
537 {
538 'level': 'ERrOR',
539 'message': u'Somé error',
540 },
541 {
542 'level': 'WARNiNG',
543 'message': u'Some wärning',
544 },
545 {
546 'level': 'INFO',
547 'message': u'Somé info',
548 },
549 ],
550 }))),
551 ]
552 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
553
554 mock_display = MagicMock()
555 monkeypatch.setattr(Display, 'display', mock_display)
556
557 mock_vvv = MagicMock()
558 monkeypatch.setattr(Display, 'vvv', mock_vvv)
559
560 mock_warn = MagicMock()
561 monkeypatch.setattr(Display, 'warning', mock_warn)
562
563 mock_err = MagicMock()
564 monkeypatch.setattr(Display, 'error', mock_err)
565
566 expected = to_native(u'Galaxy import process failed: Becäuse I said so! (Code: GW001)')
567 with pytest.raises(AnsibleError, match=re.escape(expected)):
568 api.wait_import_task(full_import_uri)
569
570 assert mock_open.call_count == 1
571 assert mock_open.mock_calls[0][1][0] == full_import_uri
572 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
573
574 assert mock_display.call_count == 1
575 assert mock_display.mock_calls[0][1][0] == 'Waiting until Galaxy import task %s has completed' % full_import_uri
576
577 assert mock_vvv.call_count == 1
578 assert mock_vvv.mock_calls[0][1][0] == u'Galaxy import message: INFO - Somé info'
579
580 assert mock_warn.call_count == 1
581 assert mock_warn.mock_calls[0][1][0] == u'Galaxy import warning message: Some wärning'
582
583 assert mock_err.call_count == 1
584 assert mock_err.mock_calls[0][1][0] == u'Galaxy import error message: Somé error'
585
586
587 @pytest.mark.parametrize('server_url, api_version, token_type, token_ins, full_import_uri', [
588 ('https://galaxy.server.com/api/automation-hub/', 'v3', 'Bearer', KeycloakToken(auth_url='https://api.test/'),
589 'https://galaxy.server.com/api/automation-hub/v3/imports/collections/1234/'),
590 ])
591 def test_wait_import_task_with_failure_no_error(server_url, api_version, token_type, token_ins, full_import_uri, monkeypatch):
592 api = get_test_galaxy_api(server_url, api_version, token_ins=token_ins)
593
594 mock_token_get = MagicMock()
595 mock_token_get.return_value = 'my token'
596 monkeypatch.setattr(token_ins, 'get', mock_token_get)
597
598 mock_open = MagicMock()
599 mock_open.side_effect = [
600 StringIO(to_text(json.dumps({
601 'finished_at': 'some_time',
602 'state': 'failed',
603 'error': {},
604 'messages': [
605 {
606 'level': 'ERROR',
607 'message': u'Somé error',
608 },
609 {
610 'level': 'WARNING',
611 'message': u'Some wärning',
612 },
613 {
614 'level': 'INFO',
615 'message': u'Somé info',
616 },
617 ],
618 }))),
619 ]
620 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
621
622 mock_display = MagicMock()
623 monkeypatch.setattr(Display, 'display', mock_display)
624
625 mock_vvv = MagicMock()
626 monkeypatch.setattr(Display, 'vvv', mock_vvv)
627
628 mock_warn = MagicMock()
629 monkeypatch.setattr(Display, 'warning', mock_warn)
630
631 mock_err = MagicMock()
632 monkeypatch.setattr(Display, 'error', mock_err)
633
634 expected = 'Galaxy import process failed: Unknown error, see %s for more details \\(Code: UNKNOWN\\)' % full_import_uri
635 with pytest.raises(AnsibleError, match=expected):
636 api.wait_import_task(full_import_uri)
637
638 assert mock_open.call_count == 1
639 assert mock_open.mock_calls[0][1][0] == full_import_uri
640 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
641
642 assert mock_display.call_count == 1
643 assert mock_display.mock_calls[0][1][0] == 'Waiting until Galaxy import task %s has completed' % full_import_uri
644
645 assert mock_vvv.call_count == 1
646 assert mock_vvv.mock_calls[0][1][0] == u'Galaxy import message: INFO - Somé info'
647
648 assert mock_warn.call_count == 1
649 assert mock_warn.mock_calls[0][1][0] == u'Galaxy import warning message: Some wärning'
650
651 assert mock_err.call_count == 1
652 assert mock_err.mock_calls[0][1][0] == u'Galaxy import error message: Somé error'
653
654
655 @pytest.mark.parametrize('server_url, api_version, token_type, token_ins, full_import_uri', [
656 ('https://galaxy.server.com/api/automation-hub', 'v3', 'Bearer', KeycloakToken(auth_url='https://api.test/'),
657 'https://galaxy.server.com/api/automation-hub/v3/imports/collections/1234/'),
658 ])
659 def test_wait_import_task_timeout(server_url, api_version, token_type, token_ins, full_import_uri, monkeypatch):
660 api = get_test_galaxy_api(server_url, api_version, token_ins=token_ins)
661
662 mock_token_get = MagicMock()
663 mock_token_get.return_value = 'my token'
664 monkeypatch.setattr(token_ins, 'get', mock_token_get)
665
666 def return_response(*args, **kwargs):
667 return StringIO(u'{"state":"waiting"}')
668
669 mock_open = MagicMock()
670 mock_open.side_effect = return_response
671 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
672
673 mock_display = MagicMock()
674 monkeypatch.setattr(Display, 'display', mock_display)
675
676 mock_vvv = MagicMock()
677 monkeypatch.setattr(Display, 'vvv', mock_vvv)
678
679 monkeypatch.setattr(time, 'sleep', MagicMock())
680
681 expected = "Timeout while waiting for the Galaxy import process to finish, check progress at '%s'" % full_import_uri
682 with pytest.raises(AnsibleError, match=expected):
683 api.wait_import_task(full_import_uri, 1)
684
685 assert mock_open.call_count > 1
686 assert mock_open.mock_calls[0][1][0] == full_import_uri
687 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
688 assert mock_open.mock_calls[1][1][0] == full_import_uri
689 assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type
690
691 assert mock_display.call_count == 1
692 assert mock_display.mock_calls[0][1][0] == 'Waiting until Galaxy import task %s has completed' % full_import_uri
693
694 # expected_wait_msg = 'Galaxy import process has a status of waiting, wait {0} seconds before trying again'
695 assert mock_vvv.call_count > 9 # 1st is opening Galaxy token file.
696
697 # FIXME:
698 # assert mock_vvv.mock_calls[1][1][0] == expected_wait_msg.format(2)
699 # assert mock_vvv.mock_calls[2][1][0] == expected_wait_msg.format(3)
700 # assert mock_vvv.mock_calls[3][1][0] == expected_wait_msg.format(4)
701 # assert mock_vvv.mock_calls[4][1][0] == expected_wait_msg.format(6)
702 # assert mock_vvv.mock_calls[5][1][0] == expected_wait_msg.format(10)
703 # assert mock_vvv.mock_calls[6][1][0] == expected_wait_msg.format(15)
704 # assert mock_vvv.mock_calls[7][1][0] == expected_wait_msg.format(22)
705 # assert mock_vvv.mock_calls[8][1][0] == expected_wait_msg.format(30)
706
707
708 @pytest.mark.parametrize('api_version, token_type, version, token_ins', [
709 ('v3', 'Bearer', 'v1.0.0', KeycloakToken(auth_url='https://api.test/api/automation-hub/')),
710 ])
711 def test_get_collection_version_metadata_no_version(api_version, token_type, version, token_ins, monkeypatch):
712 api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version, token_ins=token_ins)
713
714 if token_ins:
715 mock_token_get = MagicMock()
716 mock_token_get.return_value = 'my token'
717 monkeypatch.setattr(token_ins, 'get', mock_token_get)
718
719 mock_open = MagicMock()
720 mock_open.side_effect = [
721 StringIO(to_text(json.dumps({
722 'href': 'https://galaxy.server.com/api/{api}/namespace/name/versions/{version}/'.format(api=api_version, version=version),
723 'download_url': 'https://downloadme.com',
724 'artifact': {
725 'sha256': 'ac47b6fac117d7c171812750dacda655b04533cf56b31080b82d1c0db3c9d80f',
726 },
727 'namespace': {
728 'name': 'namespace',
729 },
730 'collection': {
731 'name': 'collection',
732 },
733 'version': version,
734 'metadata': {
735 'dependencies': {},
736 }
737 }))),
738 ]
739 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
740
741 actual = api.get_collection_version_metadata('namespace', 'collection', version)
742
743 assert isinstance(actual, CollectionVersionMetadata)
744 assert actual.namespace == u'namespace'
745 assert actual.name == u'collection'
746 assert actual.download_url == u'https://downloadme.com'
747 assert actual.artifact_sha256 == u'ac47b6fac117d7c171812750dacda655b04533cf56b31080b82d1c0db3c9d80f'
748 assert actual.version == version
749 assert actual.dependencies == {}
750
751 assert mock_open.call_count == 1
752 assert mock_open.mock_calls[0][1][0] == '%s%s/collections/namespace/collection/versions/%s/' \
753 % (api.api_server, api_version, version)
754
755 # v2 calls dont need auth, so no authz header or token_type
756 if token_type:
757 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
758
759
760 @pytest.mark.parametrize('api_version, token_type, token_ins', [
761 ('v3', None, None),
762 ('v3', 'Bearer', KeycloakToken(auth_url='https://api.test/api/automation-hub/')),
763 ])
764 def test_get_collection_signatures_backwards_compat(api_version, token_type, token_ins, monkeypatch):
765 api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version, token_ins=token_ins)
766
767 if token_ins:
768 mock_token_get = MagicMock()
769 mock_token_get.return_value = 'my token'
770 monkeypatch.setattr(token_ins, 'get', mock_token_get)
771
772 mock_open = MagicMock()
773 mock_open.side_effect = [
774 StringIO("{}")
775 ]
776 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
777
778 actual = api.get_collection_signatures('namespace', 'collection', '1.0.0')
779 assert actual == []
780
781 assert mock_open.call_count == 1
782 assert mock_open.mock_calls[0][1][0] == '%s%s/collections/namespace/collection/versions/1.0.0/' \
783 % (api.api_server, api_version)
784
785 # v3 calls dont need auth, so no authz header or token_type
786 if token_type:
787 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
788
789
790 @pytest.mark.parametrize('api_version, token_type, token_ins', [
791 ('v3', None, None),
792 ('v3', 'Bearer', KeycloakToken(auth_url='https://api.test/api/automation-hub/')),
793 ])
794 def test_get_collection_signatures(api_version, token_type, token_ins, monkeypatch):
795 api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version, token_ins=token_ins)
796
797 if token_ins:
798 mock_token_get = MagicMock()
799 mock_token_get.return_value = 'my token'
800 monkeypatch.setattr(token_ins, 'get', mock_token_get)
801
802 mock_open = MagicMock()
803 mock_open.side_effect = [
804 StringIO(to_text(json.dumps({
805 'signatures': [
806 {
807 "signature": "-----BEGIN PGP SIGNATURE-----\nSIGNATURE1\n-----END PGP SIGNATURE-----\n",
808 "pubkey_fingerprint": "FINGERPRINT",
809 "signing_service": "ansible-default",
810 "pulp_created": "2022-01-14T14:05:53.835605Z",
811 },
812 {
813 "signature": "-----BEGIN PGP SIGNATURE-----\nSIGNATURE2\n-----END PGP SIGNATURE-----\n",
814 "pubkey_fingerprint": "FINGERPRINT",
815 "signing_service": "ansible-default",
816 "pulp_created": "2022-01-14T14:05:53.835605Z",
817 },
818 ],
819 }))),
820 ]
821 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
822
823 actual = api.get_collection_signatures('namespace', 'collection', '1.0.0')
824
825 assert actual == [
826 "-----BEGIN PGP SIGNATURE-----\nSIGNATURE1\n-----END PGP SIGNATURE-----\n",
827 "-----BEGIN PGP SIGNATURE-----\nSIGNATURE2\n-----END PGP SIGNATURE-----\n"
828 ]
829
830 assert mock_open.call_count == 1
831 assert mock_open.mock_calls[0][1][0] == '%s%s/collections/namespace/collection/versions/1.0.0/' \
832 % (api.api_server, api_version)
833
834 # v3 calls dont need auth, so no authz header or token_type
835 if token_type:
836 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
837
838
839 @pytest.mark.parametrize('api_version, token_type, token_ins', [
840 ('v3', None, None),
841 ('v3', 'Bearer', KeycloakToken(auth_url='https://ah.test/'))
842 ])
843 def test_get_collection_versions(api_version, token_type, token_ins, monkeypatch):
844 response = {
845 'meta': {
846 'count': 2
847 },
848 'links': {
849 'first': '/api/v3/plugin/ansible/content/published/collections/index/ns/col/versions/?limit=100&offset=0',
850 'previous': None,
851 'next': None,
852 'last': '/api/v3/plugin/ansible/content/published/collections/index/ns/col/versions/?limit=100&offset=0'
853 },
854 'data': [
855 {
856 'version': '1.0.0',
857 'href': '/api/v3/plugin/ansible/content/published/collections/index/ns/col/versions/1.0.0/',
858 },
859 {
860 'version': '1.0.1',
861 'href': '/api/v3/plugin/ansible/content/published/collections/index/ns/col/versions/1.0.1/',
862 },
863 ],
864 }
865
866 api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version, token_ins=token_ins)
867
868 if token_ins:
869 mock_token_get = MagicMock()
870 mock_token_get.return_value = 'my token'
871 monkeypatch.setattr(token_ins, 'get', mock_token_get)
872
873 mock_open = MagicMock()
874 mock_open.side_effect = [
875 StringIO(to_text(json.dumps(response))),
876 ]
877 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
878
879 actual = api.get_collection_versions('namespace', 'collection')
880 assert actual == [u'1.0.0', u'1.0.1']
881
882 page_query = '?limit=100'
883 assert mock_open.call_count == 1
884 assert mock_open.mock_calls[0][1][0] == 'https://galaxy.server.com/api/%s/collections/namespace/collection/' \
885 'versions/%s' % (api_version, page_query)
886 if token_ins:
887 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
888
889
890 @pytest.mark.parametrize('api_version, token_type, token_ins, responses', [
891 ('v3', 'Bearer', KeycloakToken(auth_url='https://api.test/'), [
892 {
893 'count': 6,
894 'links': {
895 # v3 links are relative and the limit is included during pagination
896 'next': '/api/v3/collections/namespace/collection/versions/?limit=100&offset=100',
897 'previous': None,
898 },
899 'data': [
900 {
901 'version': '1.0.0',
902 'href': '/api/v3/collections/namespace/collection/versions/1.0.0',
903 },
904 {
905 'version': '1.0.1',
906 'href': '/api/v3/collections/namespace/collection/versions/1.0.1',
907 },
908 ],
909 },
910 {
911 'count': 6,
912 'links': {
913 'next': '/api/v3/collections/namespace/collection/versions/?limit=100&offset=200',
914 'previous': '/api/v3/collections/namespace/collection/versions',
915 },
916 'data': [
917 {
918 'version': '1.0.2',
919 'href': '/api/v3/collections/namespace/collection/versions/1.0.2',
920 },
921 {
922 'version': '1.0.3',
923 'href': '/api/v3/collections/namespace/collection/versions/1.0.3',
924 },
925 ],
926 },
927 {
928 'count': 6,
929 'links': {
930 'next': None,
931 'previous': '/api/v3/collections/namespace/collection/versions/?limit=100&offset=100',
932 },
933 'data': [
934 {
935 'version': '1.0.4',
936 'href': '/api/v3/collections/namespace/collection/versions/1.0.4',
937 },
938 {
939 'version': '1.0.5',
940 'href': '/api/v3/collections/namespace/collection/versions/1.0.5',
941 },
942 ],
943 },
944 ]),
945 ])
946 def test_get_collection_versions_pagination(api_version, token_type, token_ins, responses, monkeypatch):
947 api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version, token_ins=token_ins)
948
949 if token_ins:
950 mock_token_get = MagicMock()
951 mock_token_get.return_value = 'my token'
952 monkeypatch.setattr(token_ins, 'get', mock_token_get)
953
954 mock_open = MagicMock()
955 mock_open.side_effect = [StringIO(to_text(json.dumps(r))) for r in responses]
956 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
957
958 actual = api.get_collection_versions('namespace', 'collection')
959 assert actual == [u'1.0.0', u'1.0.1', u'1.0.2', u'1.0.3', u'1.0.4', u'1.0.5']
960
961 assert mock_open.call_count == 3
962
963 query_1 = 'limit=100'
964 query_2 = 'limit=100&offset=100'
965 query_3 = 'limit=100&offset=200'
966
967 assert mock_open.mock_calls[0][1][0] == 'https://galaxy.server.com/api/%s/collections/namespace/collection/' \
968 'versions/?%s' % (api_version, query_1)
969 assert mock_open.mock_calls[1][1][0] == 'https://galaxy.server.com/api/%s/collections/namespace/collection/' \
970 'versions/?%s' % (api_version, query_2)
971 assert mock_open.mock_calls[2][1][0] == 'https://galaxy.server.com/api/%s/collections/namespace/collection/' \
972 'versions/?%s' % (api_version, query_3)
973
974 if token_type:
975 assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
976 assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type
977 assert mock_open.mock_calls[2][2]['headers']['Authorization'] == '%s my token' % token_type
978
979
980 @pytest.mark.parametrize('responses', [
981 [
982 {
983 'count': 2,
984 'results': [{'name': '3.5.1', }, {'name': '3.5.2'}],
985 'next_link': None,
986 'next': None,
987 'previous_link': None,
988 'previous': None
989 },
990 ],
991 [
992 {
993 'count': 2,
994 'results': [{'name': '3.5.1'}],
995 'next_link': '/api/v1/roles/432/versions/?page=2&page_size=50',
996 'next': '/roles/432/versions/?page=2&page_size=50',
997 'previous_link': None,
998 'previous': None
999 },
1000 {
1001 'count': 2,
1002 'results': [{'name': '3.5.2'}],
1003 'next_link': None,
1004 'next': None,
1005 'previous_link': '/api/v1/roles/432/versions/?&page_size=50',
1006 'previous': '/roles/432/versions/?page_size=50',
1007 },
1008 ]
1009 ])
1010 def test_get_role_versions_pagination(monkeypatch, responses):
1011 api = get_test_galaxy_api('https://galaxy.com/api/', 'v1')
1012
1013 mock_open = MagicMock()
1014 mock_open.side_effect = [StringIO(to_text(json.dumps(r))) for r in responses]
1015 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
1016
1017 actual = api.fetch_role_related('versions', 432)
1018 assert actual == [{'name': '3.5.1'}, {'name': '3.5.2'}]
1019
1020 assert mock_open.call_count == len(responses)
1021
1022 assert mock_open.mock_calls[0][1][0] == 'https://galaxy.com/api/v1/roles/432/versions/?page_size=50'
1023 if len(responses) == 2:
1024 assert mock_open.mock_calls[1][1][0] == 'https://galaxy.com/api/v1/roles/432/versions/?page=2&page_size=50'
1025
1026
1027 def test_missing_cache_dir(cache_dir):
1028 os.rmdir(cache_dir)
1029 GalaxyAPI(None, "test", 'https://galaxy.ansible.com/', no_cache=False)
1030
1031 assert os.path.isdir(cache_dir)
1032 assert stat.S_IMODE(os.stat(cache_dir).st_mode) == 0o700
1033
1034 cache_file = os.path.join(cache_dir, 'api.json')
1035 with open(cache_file) as fd:
1036 actual_cache = fd.read()
1037 assert actual_cache == '{"version": 1}'
1038 assert stat.S_IMODE(os.stat(cache_file).st_mode) == 0o600
1039
1040
1041 def test_existing_cache(cache_dir):
1042 cache_file = os.path.join(cache_dir, 'api.json')
1043 cache_file_contents = '{"version": 1, "test": "json"}'
1044 with open(cache_file, mode='w') as fd:
1045 fd.write(cache_file_contents)
1046 os.chmod(cache_file, 0o655)
1047
1048 GalaxyAPI(None, "test", 'https://galaxy.ansible.com/', no_cache=False)
1049
1050 assert os.path.isdir(cache_dir)
1051 with open(cache_file) as fd:
1052 actual_cache = fd.read()
1053 assert actual_cache == cache_file_contents
1054 assert stat.S_IMODE(os.stat(cache_file).st_mode) == 0o655
1055
1056
1057 @pytest.mark.parametrize('content', [
1058 '',
1059 'value',
1060 '{"de" "finit" "ely" [\'invalid"]}',
1061 '[]',
1062 '{"version": 2, "test": "json"}',
1063 '{"version": 2, "key": "ÅÑŚÌβŁÈ"}',
1064 ])
1065 def test_cache_invalid_cache_content(content, cache_dir):
1066 cache_file = os.path.join(cache_dir, 'api.json')
1067 with open(cache_file, mode='w') as fd:
1068 fd.write(content)
1069 os.chmod(cache_file, 0o664)
1070
1071 GalaxyAPI(None, "test", 'https://galaxy.ansible.com/', no_cache=False)
1072
1073 with open(cache_file) as fd:
1074 actual_cache = fd.read()
1075 assert actual_cache == '{"version": 1}'
1076 assert stat.S_IMODE(os.stat(cache_file).st_mode) == 0o664
1077
1078
1079 def test_cache_complete_pagination(cache_dir, monkeypatch):
1080
1081 responses = get_collection_versions()
1082 cache_file = os.path.join(cache_dir, 'api.json')
1083
1084 api = get_test_galaxy_api('https://galaxy.server.com/api/', 'v3', no_cache=False)
1085
1086 mock_open = MagicMock(
1087 side_effect=[
1088 StringIO(to_text(json.dumps(r)))
1089 for r in responses
1090 ]
1091 )
1092 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
1093
1094 actual_versions = api.get_collection_versions('namespace', 'collection')
1095 assert actual_versions == [u'1.0.0', u'1.0.1', u'1.0.2', u'1.0.3', u'1.0.4', u'1.0.5']
1096
1097 with open(cache_file) as fd:
1098 final_cache = json.loads(fd.read())
1099
1100 cached_server = final_cache['galaxy.server.com:']
1101 cached_collection = cached_server['/api/v3/collections/namespace/collection/versions/']
1102 cached_versions = [r['version'] for r in cached_collection['results']]
1103
1104 assert final_cache == api._cache
1105 assert cached_versions == actual_versions
1106
1107
1108 def test_cache_complete_pagination_v3(cache_dir, monkeypatch):
1109
1110 responses = get_v3_collection_versions()
1111 cache_file = os.path.join(cache_dir, 'api.json')
1112
1113 api = get_test_galaxy_api('https://galaxy.server.com/api/', 'v3', no_cache=False)
1114
1115 mock_open = MagicMock(
1116 side_effect=[
1117 StringIO(to_text(json.dumps(r)))
1118 for r in responses
1119 ]
1120 )
1121 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
1122
1123 actual_versions = api.get_collection_versions('namespace', 'collection')
1124 assert actual_versions == [u'1.0.0', u'1.0.1', u'1.0.2', u'1.0.3', u'1.0.4', u'1.0.5']
1125
1126 with open(cache_file) as fd:
1127 final_cache = json.loads(fd.read())
1128
1129 cached_server = final_cache['galaxy.server.com:']
1130 cached_collection = cached_server['/api/v3/collections/namespace/collection/versions/']
1131 cached_versions = [r['version'] for r in cached_collection['results']]
1132
1133 assert final_cache == api._cache
1134 assert cached_versions == actual_versions
1135
1136
1137 def test_cache_flaky_pagination(cache_dir, monkeypatch):
1138
1139 responses = get_collection_versions()
1140 cache_file = os.path.join(cache_dir, 'api.json')
1141
1142 api = get_test_galaxy_api('https://galaxy.server.com/api/', 'v3', no_cache=False)
1143
1144 # First attempt, fail midway through
1145 mock_open = MagicMock(
1146 side_effect=[
1147 StringIO(to_text(json.dumps(responses[0]))),
1148 StringIO(to_text(json.dumps(responses[1]))),
1149 urllib.error.HTTPError(responses[1]['links']['next'], 500, 'Error', {}, StringIO()),
1150 StringIO(to_text(json.dumps(responses[3]))),
1151 ]
1152 )
1153 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
1154
1155 expected = (
1156 r'Error when getting available collection versions for namespace\.collection '
1157 r'from test \(https://galaxy\.server\.com/api/\) '
1158 r'\(HTTP Code: 500, Message: Error Code: Unknown\)'
1159 )
1160 with pytest.raises(GalaxyError, match=expected):
1161 api.get_collection_versions('namespace', 'collection')
1162
1163 with open(cache_file) as fd:
1164 final_cache = json.loads(fd.read())
1165
1166 assert final_cache == {
1167 'version': 1,
1168 'galaxy.server.com:': {
1169 'modified': {
1170 'namespace.collection': responses[0]['updated_at']
1171 }
1172 }
1173 }
1174
1175 # Reset API
1176 api = get_test_galaxy_api('https://galaxy.server.com/api/', 'v3', no_cache=False)
1177
1178 # Second attempt is successful so cache should be populated
1179 mock_open = MagicMock(
1180 side_effect=[
1181 StringIO(to_text(json.dumps(r)))
1182 for r in responses
1183 ]
1184 )
1185 monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
1186
1187 actual_versions = api.get_collection_versions('namespace', 'collection')
1188 assert actual_versions == [u'1.0.0', u'1.0.1', u'1.0.2', u'1.0.3', u'1.0.4', u'1.0.5']
1189
1190 with open(cache_file) as fd:
1191 final_cache = json.loads(fd.read())
1192
1193 cached_server = final_cache['galaxy.server.com:']
1194 cached_collection = cached_server['/api/v3/collections/namespace/collection/versions/']
1195 cached_versions = [r['version'] for r in cached_collection['results']]
1196
1197 assert cached_versions == actual_versions
1198
1199
1200 def test_world_writable_cache(cache_dir, monkeypatch):
1201 mock_warning = MagicMock()
1202 monkeypatch.setattr(Display, 'warning', mock_warning)
1203
1204 cache_file = os.path.join(cache_dir, 'api.json')
1205 with open(cache_file, mode='w') as fd:
1206 fd.write('{"version": 2}')
1207 os.chmod(cache_file, 0o666)
1208
1209 api = GalaxyAPI(None, "test", 'https://galaxy.ansible.com/', no_cache=False)
1210 assert api._cache is None
1211
1212 with open(cache_file) as fd:
1213 actual_cache = fd.read()
1214 assert actual_cache == '{"version": 2}'
1215 assert stat.S_IMODE(os.stat(cache_file).st_mode) == 0o666
1216
1217 assert mock_warning.call_count == 1
1218 assert mock_warning.call_args[0][0] == \
1219 'Galaxy cache has world writable access (%s), ignoring it as a cache source.' % cache_file
1220
1221
1222 def test_no_cache(cache_dir):
1223 cache_file = os.path.join(cache_dir, 'api.json')
1224 with open(cache_file, mode='w') as fd:
1225 fd.write('random')
1226
1227 api = GalaxyAPI(None, "test", 'https://galaxy.ansible.com/')
1228 assert api._cache is None
1229
1230 with open(cache_file) as fd:
1231 actual_cache = fd.read()
1232 assert actual_cache == 'random'
1233
1234
1235 def test_clear_cache_with_no_cache(cache_dir):
1236 cache_file = os.path.join(cache_dir, 'api.json')
1237 with open(cache_file, mode='w') as fd:
1238 fd.write('{"version": 1, "key": "value"}')
1239
1240 GalaxyAPI(None, "test", 'https://galaxy.ansible.com/', clear_response_cache=True)
1241 assert not os.path.exists(cache_file)
1242
1243
1244 def test_clear_cache(cache_dir):
1245 cache_file = os.path.join(cache_dir, 'api.json')
1246 with open(cache_file, mode='w') as fd:
1247 fd.write('{"version": 1, "key": "value"}')
1248
1249 GalaxyAPI(None, "test", 'https://galaxy.ansible.com/', clear_response_cache=True, no_cache=False)
1250
1251 with open(cache_file) as fd:
1252 actual_cache = fd.read()
1253 assert actual_cache == '{"version": 1}'
1254 assert stat.S_IMODE(os.stat(cache_file).st_mode) == 0o600
1255
1256
1257 @pytest.mark.parametrize(['url', 'expected'], [
1258 ('http://hostname/path', 'hostname:'),
1259 ('http://hostname:80/path', 'hostname:80'),
1260 ('https://testing.com:invalid', 'testing.com:'),
1261 ('https://testing.com:1234', 'testing.com:1234'),
1262 ('https://username:[email protected]/path', 'testing.com:'),
1263 ('https://username:[email protected]:443/path', 'testing.com:443'),
1264 ])
1265 def test_cache_id(url, expected):
1266 actual = galaxy_api.get_cache_id(url)
1267 assert actual == expected
1268
1269
1270 def test_cache_missing_results_raises_descriptive_error(mocker):
1271 api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/")
1272
1273 mock_cache_entry = {
1274 'expires': '2023-01-02T12:00:00Z',
1275 'paginated': False
1276 }
1277
1278 api._cache = {'galaxy.ansible.com': {'/api/v1/roles/': mock_cache_entry}}
1279
1280 mocker.patch('ansible.galaxy.api.urlparse')
1281 mocker.patch('ansible.galaxy.api.parse_qs', return_value={})
1282 mocker.patch('ansible.galaxy.api.get_cache_id',
1283 return_value='galaxy.ansible.com')
1284
1285 mock_datetime = mocker.patch('ansible.galaxy.api.datetime')
1286
1287 mock_comparison = mocker.Mock()
1288 mock_comparison.__bool__ = mocker.Mock(return_value=True)
1289
1290 mock_now = mocker.Mock()
1291 mock_expires = mocker.Mock()
1292 mock_now.__lt__ = mocker.Mock(return_value=True)
1293 mock_datetime.datetime.now.return_value = mock_now
1294 mock_datetime.datetime.strptime.return_value = mock_expires
1295
1296 with pytest.raises(AnsibleError, match="Missing expected 'results' in ansible-galaxy cache"):
1297 api._call_galaxy(
1298 url='https://galaxy.ansible.com/api/v1/roles/',
1299 cache=True,
1300 cache_key='/api/v1/roles/'
1301 )