forked from pulp/pulpcore
/
__init__.py
1047 lines (760 loc) · 28.9 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import aiohttp
import asyncio
import os
import shutil
import socket
import ssl
import threading
import uuid
import trustme
import proxy
import pytest
from aiohttp import web
from contextlib import suppress
from dataclasses import dataclass
from packaging.version import parse as parse_version
from time import sleep
from yarl import URL
from pulpcore.tests.functional.utils import (
SLEEP_TIME,
PulpTaskError,
PulpTaskGroupError,
add_recording_route,
)
from pulpcore.client.pulpcore import (
Configuration,
AccessPoliciesApi,
ApiClient,
ApiException,
ArtifactsApi,
ContentApi,
ContentguardsApi,
ContentguardsRbacApi,
ContentguardsContentRedirectApi,
DomainsApi,
DistributionsApi,
ExportersPulpApi,
ExportersPulpExportsApi,
ExportersFilesystemApi,
ExportersFilesystemExportsApi,
GroupsApi,
GroupsRolesApi,
GroupsUsersApi,
ImportersPulpApi,
ImportersPulpImportsApi,
ImportersPulpImportCheckApi,
OrphansCleanupApi,
PublicationsApi,
RemotesApi,
RepairApi,
RepositoriesApi,
RepositoryVersionsApi,
RepositoriesReclaimSpaceApi,
RolesApi,
SigningServicesApi,
StatusApi,
TaskGroupsApi,
TasksApi,
TaskSchedulesApi,
UploadsApi,
UsersApi,
UsersRolesApi,
WorkersApi,
)
from .gpg_ascii_armor_signing_service import ( # noqa: F401
_ascii_armored_detached_signing_service_name,
ascii_armored_detached_signing_service,
sign_with_ascii_armored_detached_signing_service,
signing_gpg_metadata,
pulp_trusted_public_key,
pulp_trusted_public_key_fingerprint,
signing_gpg_homedir_path,
signing_script_path,
signing_script_temp_dir,
)
def get_bindings_config():
api_protocol = os.environ.get("API_PROTOCOL", "https")
api_host = os.environ.get("API_HOST", "pulp")
api_port = os.environ.get("API_PORT", "443")
configuration = Configuration(
host=f"{api_protocol}://{api_host}:{api_port}",
username=os.environ.get("ADMIN_USERNAME", "admin"),
password=os.environ.get("ADMIN_PASSWORD", "password"),
)
configuration.safe_chars_for_path_param = "/"
return configuration
@pytest.hookimpl(tryfirst=True)
def pytest_check_for_leftover_pulp_objects(config):
pulpcore_client = ApiClient(get_bindings_config())
tasks_api_client = TasksApi(pulpcore_client)
for task in tasks_api_client.list().results:
if task.state in ["running", "waiting"]:
raise Exception("This test left over a task in the running or waiting state.")
apis_to_check = [
ContentguardsApi(pulpcore_client),
DistributionsApi(pulpcore_client),
PublicationsApi(pulpcore_client),
RemotesApi(pulpcore_client),
RepositoriesApi(pulpcore_client),
]
for api_to_check in apis_to_check:
if api_to_check.list().count > 0:
raise Exception(f"This test left over a {api_to_check}.")
def pytest_configure(config):
config.addinivalue_line(
"markers",
"from_pulpcore_for_all_plugins: marks tests from pulpcore as beneficial for plugins to run",
)
@pytest.fixture(scope="session")
def fixtures_cfg():
@dataclass
class FixturesConfig:
aiohttp_fixtures_origin: str = "127.0.0.1"
remote_fixtures_origin: str = os.environ.get(
"REMOTE_FIXTURES_ORIGIN", "https://fixtures.pulpproject.org/"
)
return FixturesConfig()
# API Clients
@pytest.fixture(scope="session")
def bindings_cfg():
return get_bindings_config()
@pytest.fixture(scope="session")
def _api_client_set():
return set()
@pytest.fixture
def cid(_api_client_set, monkeypatch):
value = str(uuid.uuid4())
yield value
print(f"Correlation-ID = {value}")
@pytest.fixture(autouse=True)
def _patch_cid_user_agent(_api_client_set, cid, monkeypatch):
for api_client in _api_client_set:
monkeypatch.setitem(api_client.default_headers, "Correlation-ID", cid)
monkeypatch.setattr(
api_client, "user_agent", os.environ.get("PYTEST_CURRENT_TEST").split(" ")[0]
)
@pytest.fixture(scope="session")
def pulpcore_client(_api_client_set, bindings_cfg):
api_client = ApiClient(bindings_cfg)
_api_client_set.add(api_client)
yield api_client
_api_client_set.remove(api_client)
@pytest.fixture(scope="session")
def access_policies_api_client(pulpcore_client):
return AccessPoliciesApi(pulpcore_client)
@pytest.fixture(scope="session")
def tasks_api_client(pulpcore_client):
return TasksApi(pulpcore_client)
@pytest.fixture(scope="session")
def task_groups_api_client(pulpcore_client):
return TaskGroupsApi(pulpcore_client)
@pytest.fixture(scope="session")
def workers_api_client(pulpcore_client):
return WorkersApi(pulpcore_client)
@pytest.fixture(scope="session")
def artifacts_api_client(pulpcore_client):
return ArtifactsApi(pulpcore_client)
@pytest.fixture(scope="session")
def uploads_api_client(pulpcore_client):
return UploadsApi(pulpcore_client)
@pytest.fixture(scope="session")
def task_schedules_api_client(pulpcore_client):
return TaskSchedulesApi(pulpcore_client)
@pytest.fixture(scope="session")
def status_api_client(pulpcore_client):
return StatusApi(pulpcore_client)
@pytest.fixture(scope="session")
def groups_api_client(pulpcore_client):
return GroupsApi(pulpcore_client)
@pytest.fixture(scope="session")
def groups_users_api_client(pulpcore_client):
return GroupsUsersApi(pulpcore_client)
@pytest.fixture(scope="session")
def groups_roles_api_client(pulpcore_client):
return GroupsRolesApi(pulpcore_client)
@pytest.fixture(scope="session")
def users_api_client(pulpcore_client):
return UsersApi(pulpcore_client)
@pytest.fixture(scope="session")
def users_roles_api_client(pulpcore_client):
return UsersRolesApi(pulpcore_client)
@pytest.fixture(scope="session")
def roles_api_client(pulpcore_client):
"Provies the pulp core Roles API client object."
return RolesApi(pulpcore_client)
@pytest.fixture(scope="session")
def content_api_client(pulpcore_client):
return ContentApi(pulpcore_client)
@pytest.fixture(scope="session")
def domains_api_client(pulpcore_client):
return DomainsApi(pulpcore_client)
@pytest.fixture(scope="session")
def distributions_api_client(pulpcore_client):
return DistributionsApi(pulpcore_client)
@pytest.fixture(scope="session")
def remotes_api_client(pulpcore_client):
return RemotesApi(pulpcore_client)
@pytest.fixture(scope="session")
def repositories_api_client(pulpcore_client):
return RepositoriesApi(pulpcore_client)
@pytest.fixture(scope="session")
def repository_versions_api_client(pulpcore_client):
return RepositoryVersionsApi(pulpcore_client)
@pytest.fixture(scope="session")
def publications_api_client(pulpcore_client):
return PublicationsApi(pulpcore_client)
@pytest.fixture(scope="session")
def exporters_pulp_api_client(pulpcore_client):
return ExportersPulpApi(pulpcore_client)
@pytest.fixture(scope="session")
def exporters_pulp_exports_api_client(pulpcore_client):
return ExportersPulpExportsApi(pulpcore_client)
@pytest.fixture(scope="session")
def exporters_filesystem_api_client(pulpcore_client):
return ExportersFilesystemApi(pulpcore_client)
@pytest.fixture(scope="session")
def exporters_filesystem_exports_api_client(pulpcore_client):
return ExportersFilesystemExportsApi(pulpcore_client)
@pytest.fixture(scope="session")
def importers_pulp_api_client(pulpcore_client):
return ImportersPulpApi(pulpcore_client)
@pytest.fixture(scope="session")
def importers_pulp_imports_api_client(pulpcore_client):
return ImportersPulpImportsApi(pulpcore_client)
@pytest.fixture(scope="session")
def importers_pulp_imports_check_api_client(pulpcore_client):
return ImportersPulpImportCheckApi(pulpcore_client)
@pytest.fixture(scope="session")
def signing_service_api_client(pulpcore_client):
return SigningServicesApi(pulpcore_client)
@pytest.fixture(scope="session")
def content_guards_api_client(pulpcore_client):
return ContentguardsApi(pulpcore_client)
@pytest.fixture(scope="session")
def rbac_contentguard_api_client(pulpcore_client):
return ContentguardsRbacApi(pulpcore_client)
@pytest.fixture(scope="session")
def redirect_contentguard_api_client(pulpcore_client):
return ContentguardsContentRedirectApi(pulpcore_client)
@pytest.fixture(scope="session")
def orphans_cleanup_api_client(pulpcore_client):
return OrphansCleanupApi(pulpcore_client)
@pytest.fixture(scope="session")
def repositories_reclaim_space_api_client(pulpcore_client):
return RepositoriesReclaimSpaceApi(pulpcore_client)
@pytest.fixture(scope="session")
def repair_api_client(pulpcore_client):
return RepairApi(pulpcore_client)
# Threaded local fixture servers
class ThreadedAiohttpServer(threading.Thread):
def __init__(self, app, host, port, ssl_ctx):
super().__init__()
self.app = app
self.host = host
self.port = port
self.ssl_ctx = ssl_ctx
self.loop = asyncio.new_event_loop()
async def arun(self):
runner = web.AppRunner(self.app)
await runner.setup()
site = web.TCPSite(runner, host=self.host, port=self.port, ssl_context=self.ssl_ctx)
await site.start()
async with self.shutdown_condition:
await self.shutdown_condition.wait()
await runner.cleanup()
def run(self):
asyncio.set_event_loop(self.loop)
self.shutdown_condition = asyncio.Condition()
self.loop.run_until_complete(self.arun())
async def astop(self):
async with self.shutdown_condition:
self.shutdown_condition.notify_all()
def stop(self):
asyncio.run_coroutine_threadsafe(self.astop(), self.loop)
class ThreadedAiohttpServerData:
def __init__(
self,
host,
port,
thread,
ssl_ctx,
requests_record,
):
self.host = host
self.port = port
self.thread = thread
self.ssl_ctx = ssl_ctx
self.requests_record = requests_record
def make_url(self, path):
if path[0] != "/":
raise ValueError("The `path` argument should start with a '/'")
if self.ssl_ctx is None:
protocol_handler = "http://"
else:
protocol_handler = "https://"
return f"{protocol_handler}{self.host}:{self.port}{path}"
# Webserver Fixtures
@pytest.fixture
def unused_port():
def _unused_port():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
return _unused_port
@pytest.fixture
def gen_threaded_aiohttp_server(fixtures_cfg, unused_port):
fixture_servers_data = []
def _gen_threaded_aiohttp_server(app, ssl_ctx, call_record):
host = fixtures_cfg.aiohttp_fixtures_origin
port = unused_port()
fixture_server = ThreadedAiohttpServer(app, host, port, ssl_ctx)
fixture_server.daemon = True
fixture_server.start()
fixture_server_data = ThreadedAiohttpServerData(
host=host,
port=port,
thread=fixture_server,
requests_record=call_record,
ssl_ctx=ssl_ctx,
)
fixture_servers_data.append(fixture_server_data)
return fixture_server_data
yield _gen_threaded_aiohttp_server
for fixture_server_data in fixture_servers_data:
fixture_server_data.thread.stop()
for fixture_server_data in fixture_servers_data:
fixture_server_data.thread.join()
@pytest.fixture
def gen_fixture_server(gen_threaded_aiohttp_server):
def _gen_fixture_server(fixtures_root, ssl_ctx):
app = web.Application()
call_record = add_recording_route(app, fixtures_root)
return gen_threaded_aiohttp_server(app, ssl_ctx, call_record)
yield _gen_fixture_server
# Proxy Fixtures
@pytest.fixture
def http_proxy(fixtures_cfg, unused_port):
host = fixtures_cfg.aiohttp_fixtures_origin
port = unused_port()
proxypy_args = [
"--num-workers",
"4",
"--hostname",
host,
"--port",
str(port),
]
proxy_data = ProxyData(host=host, port=port)
with proxy.Proxy(input_args=proxypy_args):
yield proxy_data
@pytest.fixture
def http_proxy_with_auth(fixtures_cfg, unused_port):
host = fixtures_cfg.aiohttp_fixtures_origin
port = unused_port()
username = str(uuid.uuid4())
password = str(uuid.uuid4())
proxypy_args = [
"--num-workers",
"4",
"--hostname",
host,
"--port",
str(port),
"--basic-auth",
f"{username}:{password}",
]
proxy_data = ProxyData(host=host, port=port, username=username, password=password)
with proxy.Proxy(input_args=proxypy_args):
yield proxy_data
@pytest.fixture
def https_proxy(fixtures_cfg, unused_port, proxy_tls_certificate_pem_path):
host = fixtures_cfg.aiohttp_fixtures_origin
port = unused_port()
proxypy_args = [
"--num-workers",
"4",
"--hostname",
host,
"--port",
str(port),
"--cert-file",
proxy_tls_certificate_pem_path, # contains both key and cert
"--key-file",
proxy_tls_certificate_pem_path, # contains both key and cert
]
proxy_data = ProxyData(host=host, port=port, ssl=True) # TODO update me
with proxy.Proxy(input_args=proxypy_args):
yield proxy_data
class ProxyData:
def __init__(self, *, host, port, username=None, password=None, ssl=False):
self.host = host
self.port = port
self.username = username
self.password = password
self.ssl = ssl
if ssl:
scheme = "https"
else:
scheme = "http"
self.proxy_url = str(
URL.build(
scheme=scheme,
host=self.host,
port=self.port,
)
)
# Server Side TLS Fixtures
@pytest.fixture(scope="session")
def tls_certificate_authority():
return trustme.CA()
@pytest.fixture
def tls_certificate_authority_cert(tls_certificate_authority):
return tls_certificate_authority.cert_pem.bytes().decode()
@pytest.fixture
def tls_certificate(fixtures_cfg, tls_certificate_authority):
return tls_certificate_authority.issue_cert(
fixtures_cfg.aiohttp_fixtures_origin,
)
# Proxy TLS Fixtures
@pytest.fixture(scope="session")
def proxy_tls_certificate_authority():
return trustme.CA()
@pytest.fixture
def proxy_tls_certificate(fixtures_cfg, client_tls_certificate_authority):
return client_tls_certificate_authority.issue_cert(
fixtures_cfg.aiohttp_fixtures_origin,
)
@pytest.fixture
def proxy_tls_certificate_pem_path(proxy_tls_certificate):
with proxy_tls_certificate.private_key_and_cert_chain_pem.tempfile() as cert_pem:
yield cert_pem
# Client Side TLS Fixtures
@pytest.fixture(scope="session")
def client_tls_certificate_authority():
return trustme.CA()
@pytest.fixture
def client_tls_certificate_authority_pem_path(client_tls_certificate_authority):
with client_tls_certificate_authority.cert_pem.tempfile() as client_ca_pem:
yield client_ca_pem
@pytest.fixture
def client_tls_certificate(fixtures_cfg, client_tls_certificate_authority):
return client_tls_certificate_authority.issue_cert(
fixtures_cfg.aiohttp_fixtures_origin,
)
@pytest.fixture
def client_tls_certificate_cert_pem(client_tls_certificate):
return client_tls_certificate.cert_chain_pems[0].bytes().decode()
@pytest.fixture
def client_tls_certificate_key_pem(client_tls_certificate):
return client_tls_certificate.private_key_pem.bytes().decode()
# SSL Context Fixtures
@pytest.fixture
def ssl_ctx(tls_certificate):
ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
tls_certificate.configure_cert(ssl_ctx)
return ssl_ctx
@pytest.fixture
def ssl_ctx_req_client_auth(
tls_certificate, client_tls_certificate, client_tls_certificate_authority_pem_path
):
ssl_ctx = ssl.create_default_context(
purpose=ssl.Purpose.CLIENT_AUTH, cafile=client_tls_certificate_authority_pem_path
)
ssl_ctx.verify_mode = ssl.CERT_REQUIRED
tls_certificate.configure_cert(ssl_ctx)
return ssl_ctx
# Object factories
@pytest.fixture
def role_factory(roles_api_client, gen_object_with_cleanup):
def _role_factory(**kwargs):
return gen_object_with_cleanup(roles_api_client, kwargs)
return _role_factory
@pytest.fixture
def gen_user(bindings_cfg, users_api_client, users_roles_api_client, gen_object_with_cleanup):
class user_context:
def __init__(self, username=None, model_roles=None, object_roles=None, domain_roles=None):
self.username = username or str(uuid.uuid4())
self.password = str(uuid.uuid4())
self.user = gen_object_with_cleanup(
users_api_client, {"username": self.username, "password": self.password}
)
self._saved_credentials = []
if model_roles:
for role in model_roles:
users_roles_api_client.create(
auth_user_href=self.user.pulp_href,
user_role={"role": role, "domain": None, "content_object": None},
)
if domain_roles:
for role, domain in domain_roles:
users_roles_api_client.create(
auth_user_href=self.user.pulp_href,
user_role={"role": role, "domain": domain, "content_object": None},
)
if object_roles:
for role, content_object in object_roles:
users_roles_api_client.create(
auth_user_href=self.user.pulp_href,
user_role={"role": role, "domain": None, "content_object": content_object},
)
def __enter__(self):
self._saved_credentials.append((bindings_cfg.username, bindings_cfg.password))
bindings_cfg.username, bindings_cfg.password = self.username, self.password
return self
def __exit__(self, exc_type, exc_value, traceback):
bindings_cfg.username, bindings_cfg.password = self._saved_credentials.pop()
return user_context
@pytest.fixture(scope="session")
def anonymous_user(bindings_cfg):
class AnonymousUser:
def __init__(self):
self._saved_credentials = []
def __enter__(self):
self._saved_credentials.append((bindings_cfg.username, bindings_cfg.password))
bindings_cfg.username, bindings_cfg.password = None, None
return self
def __exit__(self, exc_type, exc_value, traceback):
bindings_cfg.username, bindings_cfg.password = self._saved_credentials.pop()
return AnonymousUser()
@pytest.fixture(scope="session")
def invalid_user(bindings_cfg):
class InvalidUser:
def __init__(self):
self._saved_credentials = []
def __enter__(self):
self._saved_credentials.append((bindings_cfg.username, bindings_cfg.password))
bindings_cfg.username, bindings_cfg.password = str(uuid.uuid4()), str(uuid.uuid4())
return self
def __exit__(self, exc_type, exc_value, traceback):
bindings_cfg.username, bindings_cfg.password = self._saved_credentials.pop()
return InvalidUser()
@pytest.fixture(scope="session")
def pulp_admin_user(bindings_cfg):
class AdminUser:
def __init__(self):
self.username = bindings_cfg.username
self.password = bindings_cfg.password
self._saved_credentials = []
def __enter__(self):
self._saved_credentials.append((bindings_cfg.username, bindings_cfg.password))
bindings_cfg.username, bindings_cfg.password = self.username, self.password
return self
def __exit__(self, exc_type, exc_value, traceback):
bindings_cfg.username, bindings_cfg.password = self._saved_credentials.pop()
return AdminUser()
@pytest.fixture
def random_artifact_factory(
artifacts_api_client, tmp_path, gen_object_with_cleanup, pulp_domain_enabled
):
def _random_artifact_factory(pulp_domain=None):
kwargs = {}
if pulp_domain:
if not pulp_domain_enabled:
raise RuntimeError("Server does not have domains enabled.")
kwargs["pulp_domain"] = pulp_domain
temp_file = tmp_path / str(uuid.uuid4())
temp_file.write_bytes(uuid.uuid4().bytes)
return gen_object_with_cleanup(artifacts_api_client, temp_file, **kwargs)
return _random_artifact_factory
@pytest.fixture
def random_artifact(random_artifact_factory):
return random_artifact_factory()
# Random other fixtures
@pytest.fixture
def delete_orphans_pre(request, orphans_cleanup_api_client, monitor_task):
if request.node.get_closest_marker("parallel") is not None:
raise pytest.UsageError("This test is not suitable to be marked parallel.")
monitor_task(orphans_cleanup_api_client.cleanup({"orphan_protection_time": 0}).task)
yield
@pytest.fixture(scope="session")
def monitor_task(tasks_api_client, pulp_domain_enabled):
def _monitor_task(task_href):
while True:
try:
task = tasks_api_client.read(task_href)
except ApiException as e:
if pulp_domain_enabled and e.status == 404:
# Task's domain has been deleted, nothing to show anymore
return {}
raise e
if task.state in ["completed", "failed", "canceled"]:
break
sleep(SLEEP_TIME)
if task.state != "completed":
raise PulpTaskError(task=task)
return task
return _monitor_task
@pytest.fixture(scope="session")
def monitor_task_group(task_groups_api_client):
def _monitor_task_group(task_group_href):
def tasks_open(tg):
return (tg.waiting + tg.running) > 0
def group_wait(tg):
return not tg.all_tasks_dispatched or tasks_open(tg)
def group_fail(tg):
return tg.failed > 0 and not tasks_open(tg)
task_group = task_groups_api_client.read(task_group_href)
while group_wait(task_group) and not group_fail(task_group):
sleep(SLEEP_TIME)
task_group = task_groups_api_client.read(task_group_href)
if (task_group.failed + task_group.skipped + task_group.canceled) > 0:
raise PulpTaskGroupError(task_group=task_group)
return task_group
return _monitor_task_group
@pytest.fixture(scope="session")
def pulp_settings():
import django
django.setup()
from django.conf import settings
return settings
@pytest.fixture(scope="session")
def pulp_domain_enabled(pulp_settings):
return pulp_settings.DOMAIN_ENABLED
@pytest.fixture(scope="session")
def pulp_api_v3_path(pulp_settings, pulp_domain_enabled):
if pulp_domain_enabled:
v3_api_root = pulp_settings.V3_DOMAIN_API_ROOT
v3_api_root = v3_api_root.replace("<slug:pulp_domain>", "default")
else:
v3_api_root = pulp_settings.V3_API_ROOT
if v3_api_root is None:
raise RuntimeError(
"This fixture requires the server to have the `V3_API_ROOT` setting set."
)
return v3_api_root
@pytest.fixture(scope="session")
def pulp_api_v3_url(bindings_cfg, pulp_api_v3_path):
return f"{bindings_cfg.host}{pulp_api_v3_path}"
@pytest.fixture(scope="session")
def pulp_content_url(pulp_settings, pulp_domain_enabled):
url = f"{pulp_settings.CONTENT_ORIGIN}{pulp_settings.CONTENT_PATH_PREFIX}"
if pulp_domain_enabled:
url += "default/"
return url
# Pulp status information fixtures
@pytest.fixture(scope="session")
def pulp_status(status_api_client):
return status_api_client.status_read()
@pytest.fixture(scope="session")
def pulp_versions(pulp_status):
"""A dictionary containing pulp plugin versions."""
return {item.component: parse_version(item.version) for item in pulp_status.versions}
@pytest.fixture
def needs_pulp_plugin(pulp_versions):
"""Skip test if a component is not available in the specified version range"""
def _needs_pulp_plugin(plugin, min=None, max=None):
if plugin not in pulp_versions:
pytest.skip(f"Plugin {plugin} is not installed.")
if min is not None and pulp_versions[plugin] < parse_version(min):
pytest.skip(f"Plugin {plugin} too old (<{min}).")
if max is not None and pulp_versions[plugin] >= parse_version(max):
pytest.skip(f"Plugin {plugin} too new (>={max}).")
return _needs_pulp_plugin
@pytest.fixture
def has_pulp_plugin(pulp_versions):
def _has_pulp_plugin(plugin, min=None, max=None):
if plugin not in pulp_versions:
return False
if min is not None and pulp_versions[plugin] < parse_version(min):
return False
if max is not None and pulp_versions[plugin] >= parse_version(max):
return False
return True
return _has_pulp_plugin
@pytest.fixture(scope="session")
def redis_status(pulp_status):
"""A boolean value which tells whether the connection to redis was established or not."""
return pulp_status.redis_connection.connected
# Object Cleanup fixtures
@pytest.fixture(scope="class")
def add_to_cleanup(monitor_task):
"""Fixture to allow pulp objects to be deleted in reverse order after the test module."""
obj_refs = []
def _add_to_cleanup(api_client, pulp_href):
obj_refs.append((api_client, pulp_href))
yield _add_to_cleanup
delete_task_hrefs = []
# Delete newest items first to avoid dependency lockups
for api_client, pulp_href in reversed(obj_refs):
try:
task_url = api_client.delete(pulp_href).task
delete_task_hrefs.append(task_url)
except Exception:
# There was no delete task for this unit or the unit may already have been deleted.
# Also we can never be sure which one is the right ApiException to catch.
pass
for deleted_task_href in delete_task_hrefs:
with suppress(ApiException):
# The task itself may be gone at this point (e.g. by being part of a deleted domain).
monitor_task(deleted_task_href)
@pytest.fixture(scope="class")
def gen_object_with_cleanup(add_to_cleanup, monitor_task):
def _gen_object_with_cleanup(api_client, *args, **kwargs):
new_obj = api_client.create(*args, **kwargs)
try:
add_to_cleanup(api_client, new_obj.pulp_href)
except AttributeError:
# This is a task and the real object href comes from monitoring it
task_data = monitor_task(new_obj.task)
for created_resource in task_data.created_resources:
try:
new_obj = api_client.read(created_resource)
except Exception:
pass # This isn't the right created_resource for this api_client
else:
add_to_cleanup(api_client, new_obj.pulp_href)
return new_obj
msg = f"No appropriate created_resource could be found in task data {task_data}"
raise TypeError(msg)
return new_obj
return _gen_object_with_cleanup
@pytest.fixture(scope="class")
def add_to_filesystem_cleanup():
obj_paths = []
def _add_to_filesystem_cleanup(path):
obj_paths.append(path)
yield _add_to_filesystem_cleanup
for path in reversed(obj_paths):
if os.path.isdir(path):
shutil.rmtree(path, ignore_errors=True)
else:
try: