forked from konflux-ci/pulp-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_pulp_client.py
More file actions
1821 lines (1476 loc) · 83.6 KB
/
test_pulp_client.py
File metadata and controls
1821 lines (1476 loc) · 83.6 KB
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
"""
Tests for PulpClient class and its mixin components.
This module contains comprehensive tests for:
- PulpClient: Main client class (pulp_client.py)
- Content upload operations migrated to PulpClient
- Content querying and retrieval methods migrated to PulpClient
- RepositoryManagerMixin: Repository operations (repository_manager.py)
- TaskManagerMixin: Pulp task management (task_manager.py)
All mixin functionality is tested through the integrated PulpClient class,
which is the correct approach for testing mixin-based architecture.
"""
import json
import re
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
import httpx
from httpx import HTTPError
from pulp_tool.api import PulpClient, OAuth2ClientCredentialsAuth
from pulp_tool.models.artifacts import ExtraArtifactRef, PulpContentRow
from pulp_tool.models.pulp_api import RpmDistributionRequest, RpmRepositoryRequest
class TestPulpClient:
"""Test PulpClient class."""
def test_init(self, mock_config):
"""Test PulpClient initialization."""
client = PulpClient(mock_config)
assert client.config == mock_config
assert client.domain is None
# namespace is set from config["domain"] when domain parameter is not provided
assert client.namespace == "test-domain"
assert client.timeout == 120 # DEFAULT_TIMEOUT
assert client._auth is None
assert client.session is not None
def test_init_with_domain(self, mock_config):
"""Test PulpClient initialization with explicit domain."""
client = PulpClient(mock_config, domain="explicit-domain")
assert client.domain == "explicit-domain"
# namespace is set from the domain parameter
assert client.namespace == "explicit-domain"
def test_create_session(self, mock_config):
"""Test _create_session method."""
client = PulpClient(mock_config)
session = client._create_session()
# Should return an httpx.Client instance (not requests.Session)
assert isinstance(session, httpx.Client)
# Verify client is configured (limits not accessible after init, only timeout)
assert session.timeout is not None
assert not session.is_closed
def test_close(self, mock_pulp_client):
"""Test close method."""
mock_pulp_client.session.close = Mock()
mock_pulp_client.close()
mock_pulp_client.session.close.assert_called_once()
def test_context_manager(self, mock_config):
"""Test context manager functionality."""
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
with PulpClient(mock_config) as client:
assert client.session == mock_session
mock_session.close.assert_called_once()
def test_create_from_config_file(self, temp_config_file):
"""Test create_from_config_file class method."""
with patch("pulp_tool.utils.config_utils.load_config_content") as mock_load_content:
config_content = '[cli]\nbase_url = "https://test.com"'
mock_load_content.return_value = (config_content.encode(), False)
client = PulpClient.create_from_config_file(path=temp_config_file)
assert isinstance(client, PulpClient)
assert client.config["base_url"] == "https://test.com"
def test_create_from_config_file_default_path(self):
"""Test create_from_config_file with default path."""
with patch("pulp_tool.utils.config_utils.load_config_content") as mock_load_content:
config_content = '[cli]\nbase_url = "https://test.com"'
mock_load_content.return_value = (config_content.encode(), False)
client = PulpClient.create_from_config_file()
assert isinstance(client, PulpClient)
assert client.config["base_url"] == "https://test.com"
def test_create_from_config_file_with_base64(self):
"""Test create_from_config_file with base64-encoded config."""
import base64
config_content = '[cli]\nbase_url = "https://test.com"\ndomain = "test-domain"'
base64_config = base64.b64encode(config_content.encode()).decode()
with patch("pulp_tool.api.pulp_client.tomllib.loads") as mock_loads:
mock_loads.return_value = {"cli": {"base_url": "https://test.com", "domain": "test-domain"}}
client = PulpClient.create_from_config_file(path=base64_config)
assert isinstance(client, PulpClient)
assert client.config["base_url"] == "https://test.com"
assert client.config_path is None # Should be None for base64 config
mock_loads.assert_called_once()
def test_create_from_config_file_invalid_toml_raises_value_error(self, temp_config_file):
"""Test create_from_config_file raises ValueError with clear message for invalid TOML."""
import tomllib
with patch("pulp_tool.utils.config_utils.load_config_content") as mock_load_content:
mock_load_content.return_value = (b"invalid toml [cli\nbase_url", False)
with pytest.raises(ValueError, match=r"Invalid TOML in configuration .*: .*") as exc_info:
PulpClient.create_from_config_file(path=temp_config_file)
assert "Invalid TOML" in str(exc_info.value)
assert isinstance(exc_info.value.__cause__, tomllib.TOMLDecodeError)
def test_headers_property(self, mock_pulp_client):
"""Test headers property."""
assert mock_pulp_client.headers is None
def test_auth_property(self, mock_pulp_client):
"""Test auth property."""
auth = mock_pulp_client.auth
assert isinstance(auth, OAuth2ClientCredentialsAuth)
assert auth._token_url == "https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token"
def test_auth_property_cached(self, mock_pulp_client):
"""Test auth property caching."""
auth1 = mock_pulp_client.auth
auth2 = mock_pulp_client.auth
assert auth1 is auth2
def test_auth_property_missing_credentials_raises(self, mock_config):
"""Test auth property raises clear error when no credentials provided."""
config_no_creds = {
"base_url": mock_config["base_url"],
"api_root": mock_config["api_root"],
"domain": mock_config["domain"],
}
client = PulpClient(config_no_creds)
with pytest.raises(ValueError, match="Authentication credentials missing"):
_ = client.auth
def test_auth_property_empty_client_id_raises(self, mock_config):
"""Test auth property raises when client_id is empty and no username/password."""
config = {
"base_url": mock_config["base_url"],
"api_root": mock_config["api_root"],
"domain": mock_config["domain"],
"client_id": "",
"client_secret": "secret",
}
client = PulpClient(config)
with pytest.raises(ValueError, match="Authentication credentials missing"):
_ = client.auth
def test_auth_property_username_password_basic_auth(self, mock_config):
"""Test auth property uses Basic Auth when username/password provided."""
config = {
"base_url": mock_config["base_url"],
"api_root": mock_config["api_root"],
"domain": mock_config["domain"],
"username": "myuser",
"password": "mypass",
}
client = PulpClient(config)
auth = client.auth
assert isinstance(auth, httpx.BasicAuth)
def test_cert_property(self, mock_pulp_client):
"""Test cert property."""
cert_tuple = mock_pulp_client.cert
assert cert_tuple == ("/path/to/cert.pem", "/path/to/key.pem")
def test_cert_property_with_relative_paths(self, mock_config, tmp_path):
"""Test cert property with relative paths resolved from config_path."""
# Create a config file and cert/key files relative to it
config_file = tmp_path / "config.toml"
config_dir = config_file.parent
# Create cert and key files in the config directory
cert_file = config_dir / "cert.pem"
key_file = config_dir / "key.pem"
cert_file.write_text("cert content")
key_file.write_text("key content")
# Update config with relative paths
config_with_relative = mock_config.copy()
config_with_relative["cert"] = "cert.pem"
config_with_relative["key"] = "key.pem"
# Create client with config_path, mocking session creation to avoid SSL errors
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
client = PulpClient(config_with_relative, config_path=config_file)
# Cert property should resolve relative paths
cert_tuple = client.cert
assert cert_tuple == (str(cert_file), str(key_file))
def test_cert_property_with_absolute_paths(self, mock_config, tmp_path):
"""Test cert property with absolute paths (should not resolve relative to config)."""
# Create cert and key files in a different location
other_dir = tmp_path / "other"
other_dir.mkdir()
cert_file = other_dir / "cert.pem"
key_file = other_dir / "key.pem"
cert_file.write_text("cert content")
key_file.write_text("key content")
config_file = tmp_path / "config.toml"
# Update config with absolute paths
config_with_absolute = mock_config.copy()
config_with_absolute["cert"] = str(cert_file)
config_with_absolute["key"] = str(key_file)
# Create client with config_path, mocking session creation to avoid SSL errors
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
client = PulpClient(config_with_absolute, config_path=config_file)
# Cert property should return absolute paths as-is
cert_tuple = client.cert
assert cert_tuple == (str(cert_file), str(key_file))
def test_cert_property_with_base64_cert_and_key(self, mock_config, tmp_path):
"""Test cert property decodes base64-encoded cert/key file content."""
import base64
config_file = tmp_path / "config.toml"
config_dir = config_file.parent
cert_file = config_dir / "cert.pem"
key_file = config_dir / "key.pem"
cert_pem = b"-----BEGIN CERTIFICATE-----\nMIIBkTCB+wIJAK\n-----END CERTIFICATE-----"
key_pem = b"-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg\n-----END PRIVATE KEY-----"
cert_file.write_text(base64.b64encode(cert_pem).decode())
key_file.write_text(base64.b64encode(key_pem).decode())
config_with_relative = mock_config.copy()
config_with_relative["cert"] = "cert.pem"
config_with_relative["key"] = "key.pem"
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
client = PulpClient(config_with_relative, config_path=config_file)
cert_tuple = client.cert
assert client._cert_paths is not None
assert cert_tuple == client._cert_paths
assert Path(cert_tuple[0]).exists() and Path(cert_tuple[1]).exists()
assert Path(cert_tuple[0]).read_bytes() == cert_pem
assert Path(cert_tuple[1]).read_bytes() == key_pem
client.close()
assert client._cert_temp_dir is None
assert client._cert_paths is None
def test_close_handles_oserror_on_cert_temp_cleanup(self, mock_config, tmp_path):
"""Test close() catches OSError when cleaning up base64 cert temp dir."""
import base64
config_file = tmp_path / "config.toml"
cert_file = tmp_path / "cert.pem"
key_file = tmp_path / "key.pem"
cert_pem = b"-----BEGIN CERTIFICATE-----\nMIIBkTCB+wIJAK\n-----END CERTIFICATE-----"
key_pem = b"-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg\n-----END PRIVATE KEY-----"
cert_file.write_text(base64.b64encode(cert_pem).decode())
key_file.write_text(base64.b64encode(key_pem).decode())
config_with_relative = mock_config.copy()
config_with_relative["cert"] = "cert.pem"
config_with_relative["key"] = "key.pem"
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_create_session.return_value = Mock()
client = PulpClient(config_with_relative, config_path=config_file)
_ = client.cert
assert client._cert_temp_dir is not None
client._cert_temp_dir.cleanup = Mock(side_effect=OSError("cleanup failed"))
client.close()
assert client._cert_temp_dir is None
assert client._cert_paths is None
def test_cert_property_with_existing_relative_paths(self, mock_config, tmp_path):
"""Test cert property when relative paths exist in current directory."""
# Create cert and key files in current directory (not relative to config)
import os
original_cwd = os.getcwd()
try:
os.chdir(str(tmp_path))
cert_file = tmp_path / "cert.pem"
key_file = tmp_path / "key.pem"
cert_file.write_text("cert content")
key_file.write_text("key content")
config_file = tmp_path / "config.toml"
# Update config with relative paths
config_with_relative = mock_config.copy()
config_with_relative["cert"] = "cert.pem"
config_with_relative["key"] = "key.pem"
# Create client with config_path, mocking session creation to avoid SSL errors
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
client = PulpClient(config_with_relative, config_path=config_file)
# Cert property should return paths as-is since they exist in current directory
cert_tuple = client.cert
assert cert_tuple == ("cert.pem", "key.pem")
finally:
os.chdir(original_cwd)
def test_cert_property_without_config_path(self, mock_config):
"""Test cert property when config_path is None (should not resolve relative paths)."""
# Update config with relative paths
config_with_relative = mock_config.copy()
config_with_relative["cert"] = "cert.pem"
config_with_relative["key"] = "key.pem"
# Create client without config_path, mocking session creation to avoid SSL errors
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
client = PulpClient(config_with_relative, config_path=None)
# Cert property should return paths as-is
cert_tuple = client.cert
assert cert_tuple == ("cert.pem", "key.pem")
def test_cert_property_with_config_path_no_parent(self, mock_config):
"""Test cert property when config_path has no parent (root path)."""
# Update config with relative paths
config_with_relative = mock_config.copy()
config_with_relative["cert"] = "cert.pem"
config_with_relative["key"] = "key.pem"
# Create client with config_path that has no parent, mocking session creation
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
# Mock config_path to have no parent (like root path "/")
from pathlib import Path
mock_config_path = Mock(spec=Path)
mock_config_path.parent = None
client = PulpClient(config_with_relative, config_path=mock_config_path)
# Cert property should return paths as-is when parent is None
cert_tuple = client.cert
assert cert_tuple == ("cert.pem", "key.pem")
def test_cert_property_relative_path_not_found(self, mock_config, tmp_path):
"""Test cert property when relative paths don't exist in config dir or current dir."""
# Create a config file but don't create cert/key files
config_file = tmp_path / "config.toml"
# Update config with relative paths that don't exist anywhere
config_with_relative = mock_config.copy()
config_with_relative["cert"] = "nonexistent_cert.pem"
config_with_relative["key"] = "nonexistent_key.pem"
# Create client with config_path, mocking session creation to avoid SSL errors
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
client = PulpClient(config_with_relative, config_path=config_file)
# Cert property should return original paths when files don't exist
cert_tuple = client.cert
assert cert_tuple == ("nonexistent_cert.pem", "nonexistent_key.pem")
def test_cert_property_mixed_absolute_and_relative(self, mock_config, tmp_path):
"""Test cert property with one absolute path and one relative path."""
# Create cert file in a different location (absolute)
other_dir = tmp_path / "other"
other_dir.mkdir()
cert_file = other_dir / "cert.pem"
cert_file.write_text("cert content")
# Create key file relative to config
config_file = tmp_path / "config.toml"
config_dir = config_file.parent
key_file = config_dir / "key.pem"
key_file.write_text("key content")
# Update config with mixed paths
config_mixed = mock_config.copy()
config_mixed["cert"] = str(cert_file) # Absolute
config_mixed["key"] = "key.pem" # Relative
# Create client with config_path, mocking session creation to avoid SSL errors
with patch("pulp_tool.api.pulp_client.create_session_with_retry") as mock_create_session:
mock_session = Mock()
mock_create_session.return_value = mock_session
client = PulpClient(config_mixed, config_path=config_file)
# Cert property should return absolute cert as-is, resolve relative key
cert_tuple = client.cert
assert cert_tuple == (str(cert_file), str(key_file))
def test_request_params_with_cert(self, mock_pulp_client):
"""Test request_params property with certificate.
Note: With httpx, cert is passed to Client constructor, not per-request.
So request_params should NOT contain cert when using certificate auth.
"""
params = mock_pulp_client.request_params
# Cert is handled at Client level, not per-request
assert "cert" not in params
# When using cert auth, we don't add auth to request_params either
assert "auth" not in params
def test_request_params_without_cert(self, mock_config):
"""Test request_params property without certificate."""
config_no_cert = mock_config.copy()
del config_no_cert["cert"]
del config_no_cert["key"]
client = PulpClient(config_no_cert)
params = client.request_params
assert "auth" in params
assert "cert" not in params
def test_url_building(self, mock_pulp_client):
"""Test _url method."""
url = mock_pulp_client._url("api/v3/test/")
expected = "https://pulp.example.com/pulp/api/v3/test-domain/api/v3/test/"
assert url == expected
def test_url_building_with_domain(self, mock_config):
"""Test _url method with domain."""
client = PulpClient(mock_config, domain="custom-domain")
url = client._url("api/v3/test/")
expected = "https://pulp.example.com/pulp/api/v3/custom-domain/api/v3/test/"
assert url == expected
def test_url_building_with_explicit_domain(self, mock_config):
"""Test _url method with explicitly provided domain parameter."""
# Create config without domain field
config_without_domain = {k: v for k, v in mock_config.items() if k != "domain"}
# Pass domain explicitly
client = PulpClient(config_without_domain, domain="custom-domain")
url = client._url("api/v3/test/")
expected = "https://pulp.example.com/pulp/api/v3/custom-domain/api/v3/test/"
assert url == expected
def test_get_domain(self, mock_pulp_client):
"""Test get_domain method."""
domain = mock_pulp_client.get_domain()
assert domain == "test-domain"
def test_get_domain_with_tenant_suffix(self, mock_config):
"""Test get_domain method with tenant suffix (no longer removes -tenant)."""
client = PulpClient(mock_config, domain="test-domain-tenant")
domain = client.get_domain()
assert domain == "test-domain-tenant"
def test_get_single_resource(self, mock_pulp_client, httpx_mock):
"""Test _get_single_resource method."""
# Mock the API response - URL includes domain and query params
httpx_mock.get(
"https://pulp.example.com/pulp/api/v3/test-domain/api/v3/repositories/?name=test-repo&offset=0&limit=1"
).mock(return_value=httpx.Response(200, json={"pulp_href": "/pulp/api/v3/repositories/12345/"}))
result = mock_pulp_client._get_single_resource("api/v3/repositories/", "test-repo")
assert result.status_code == 200
assert result.json()["pulp_href"] == "/pulp/api/v3/repositories/12345/"
def test_check_response_success(self, mock_pulp_client, mock_response):
"""Test _check_response method with successful response."""
mock_pulp_client._check_response(mock_response, "test operation")
# Should not raise any exception
def test_check_response_error(self, mock_pulp_client, mock_error_response):
"""Test _check_response method with error response."""
with pytest.raises(HTTPError, match="Failed to test operation"):
mock_pulp_client._check_response(mock_error_response, "test operation")
def test_check_response_public(self, mock_pulp_client, mock_response):
"""Test check_response public method."""
mock_pulp_client.check_response(mock_response, "test operation")
# Should not raise any exception
def test_chunked_get_no_chunking(self, mock_pulp_client, httpx_mock):
"""Test _chunked_get method without chunking."""
# Mock the API response
httpx_mock.get("https://test.com/api").mock(
return_value=httpx.Response(200, json={"results": [{"id": 1}, {"id": 2}]})
)
result = mock_pulp_client._chunked_get("https://test.com/api", {"param": "value"})
assert result.status_code == 200
assert len(result.json()["results"]) == 2
def test_chunked_get_with_chunking(self, mock_pulp_client, httpx_mock):
"""Test _chunked_get method with chunking."""
# Create a large parameter list
large_param = ",".join([f"item{i}" for i in range(100)])
params = {"large_param": large_param}
# Mock multiple responses for chunking - each chunk returns 20 items
httpx_mock.get("https://test.com/api").mock(
return_value=httpx.Response(200, json={"results": [{"id": i} for i in range(20)]})
)
with patch.object(mock_pulp_client, "_check_response"):
result = mock_pulp_client._chunked_get(
"https://test.com/api", params, chunk_param="large_param", chunk_size=20
)
assert result.status_code == 200
# Should aggregate results from multiple chunks (5 chunks * 20 items = 100 items)
assert len(result.json()["results"]) == 100
def test_upload_content_rpm(self, mock_pulp_client, temp_rpm_file, httpx_mock):
"""Test upload_content method for RPM."""
# Mock the RPM upload endpoint
httpx_mock.post("https://pulp.example.com/pulp/api/v3/test-domain/api/v3/content/rpm/packages/upload/").mock(
return_value=httpx.Response(201, json={"pulp_href": "/pulp/api/v3/content/12345/"})
)
labels = {"build_id": "test-build", "arch": "x86_64"}
with patch("pulp_tool.utils.validation.file.validate_file_path"):
result = mock_pulp_client.upload_content(temp_rpm_file, labels, file_type="RPM", arch="x86_64")
assert result == "/pulp/api/v3/content/12345/"
def test_upload_content_file(self, mock_pulp_client, temp_file, httpx_mock):
"""Test upload_content method for file."""
# Mock the file content creation endpoint
httpx_mock.post("https://pulp.example.com/pulp/api/v3/test-domain/api/v3/content/file/files/").mock(
return_value=httpx.Response(202, json={"pulp_href": "/pulp/api/v3/content/12345/"})
)
labels = {"build_id": "test-build"}
with patch("pulp_tool.utils.validation.file.validate_file_path"):
result = mock_pulp_client.upload_content(temp_file, labels, file_type="File")
assert result == "/pulp/api/v3/content/12345/"
def test_upload_content_missing_arch(self, mock_pulp_client, temp_file):
"""Test upload_content method with missing arch for RPM."""
labels = {"build_id": "test-build"}
with patch("pulp_tool.utils.validation.file.validate_file_path"):
with pytest.raises(ValueError, match="arch parameter is required for RPM uploads"):
mock_pulp_client.upload_content(temp_file, labels, file_type="RPM")
def test_create_file_content_from_file(self, mock_pulp_client, temp_file, httpx_mock):
"""Test create_file_content method with file path."""
# Mock the file content creation endpoint
httpx_mock.post("https://pulp.example.com/pulp/api/v3/test-domain/api/v3/content/file/files/").mock(
return_value=httpx.Response(202, json={"task": "/pulp/api/v3/tasks/12345/"})
)
labels = {"build_id": "test-build"}
result = mock_pulp_client.create_file_content("test-repo", temp_file, build_id="test-build", pulp_label=labels)
assert result.status_code == 202
assert result.json()["task"] == "/pulp/api/v3/tasks/12345/"
def test_create_file_content_from_string(self, mock_pulp_client, httpx_mock):
"""Test create_file_content method with string content."""
# Mock the file content creation endpoint
httpx_mock.post("https://pulp.example.com/pulp/api/v3/test-domain/api/v3/content/file/files/").mock(
return_value=httpx.Response(202, json={"task": "/pulp/api/v3/tasks/12345/"})
)
labels = {"build_id": "test-build"}
content = '{"test": "data"}'
result = mock_pulp_client.create_file_content(
"test-repo", content, build_id="test-build", pulp_label=labels, filename="test.json"
)
assert result.status_code == 202
assert result.json()["task"] == "/pulp/api/v3/tasks/12345/"
def test_create_file_content_missing_filename(self, mock_pulp_client):
"""Test create_file_content method with missing filename for string content."""
labels = {"build_id": "test-build"}
content = '{"test": "data"}'
with pytest.raises(ValueError, match="filename is required when providing in-memory content"):
mock_pulp_client.create_file_content("test-repo", content, build_id="test-build", pulp_label=labels)
def test_add_content(self, mock_pulp_client, httpx_mock):
"""Test add_content method."""
# Mock the add content endpoint - repository href gets modify/ appended
httpx_mock.post("https://pulp.example.com/pulp/api/v3/repositories/rpm/rpm/12345/modify/").mock(
return_value=httpx.Response(202, json={"task": "/pulp/api/v3/tasks/67890/"})
)
# Mock the task endpoint (add_content now fetches the task)
httpx_mock.get("https://pulp.example.com/pulp/api/v3/tasks/67890/").mock(
return_value=httpx.Response(
200, json={"pulp_href": "/pulp/api/v3/tasks/67890/", "state": "completed", "created_resources": []}
)
)
artifacts = ["/pulp/api/v3/content/12345/", "/pulp/api/v3/content/67890/"]
result = mock_pulp_client.add_content("/pulp/api/v3/repositories/rpm/rpm/12345/", artifacts)
# Now returns a TaskResponse model
from pulp_tool.models.pulp_api import TaskResponse
assert isinstance(result, TaskResponse)
assert result.pulp_href == "/pulp/api/v3/tasks/67890/"
assert result.state == "completed"
def test_modify_repository_content_remove_only(self, mock_pulp_client, httpx_mock):
"""Test modify_repository_content with remove_content_units only."""
posted: dict = {}
def capture_modify(request: httpx.Request) -> httpx.Response:
posted["body"] = json.loads(request.content.decode())
return httpx.Response(202, json={"task": "/pulp/api/v3/tasks/99999/"})
httpx_mock.post("https://pulp.example.com/pulp/api/v3/repositories/rpm/rpm/12345/modify/").mock(
side_effect=capture_modify
)
httpx_mock.get("https://pulp.example.com/pulp/api/v3/tasks/99999/").mock(
return_value=httpx.Response(
200, json={"pulp_href": "/pulp/api/v3/tasks/99999/", "state": "completed", "created_resources": []}
)
)
removes = ["/pulp/api/v3/content/rpm/packages/old/"]
result = mock_pulp_client.modify_repository_content(
"/pulp/api/v3/repositories/rpm/rpm/12345/", remove_content_units=removes
)
from pulp_tool.models.pulp_api import TaskResponse
assert isinstance(result, TaskResponse)
assert posted["body"] == {"remove_content_units": removes}
assert "add_content_units" not in posted["body"]
def test_modify_repository_content_requires_add_or_remove(self, mock_pulp_client):
"""modify_repository_content raises if both add and remove are empty."""
with pytest.raises(ValueError, match="modify_repository_content requires"):
mock_pulp_client.modify_repository_content("/pulp/api/v3/repositories/rpm/rpm/1/")
def test_modify_repository_content_add_and_remove(self, mock_pulp_client, httpx_mock):
"""Test modify_repository_content with both add_content_units and remove_content_units."""
posted: dict = {}
def capture_modify(request: httpx.Request) -> httpx.Response:
posted["body"] = json.loads(request.content.decode())
return httpx.Response(202, json={"task": "/pulp/api/v3/tasks/88888/"})
httpx_mock.post("https://pulp.example.com/pulp/api/v3/repositories/rpm/rpm/99999/modify/").mock(
side_effect=capture_modify
)
httpx_mock.get("https://pulp.example.com/pulp/api/v3/tasks/88888/").mock(
return_value=httpx.Response(
200, json={"pulp_href": "/pulp/api/v3/tasks/88888/", "state": "completed", "created_resources": []}
)
)
mock_pulp_client.modify_repository_content(
"/pulp/api/v3/repositories/rpm/rpm/99999/",
add_content_units=["/add/1/"],
remove_content_units=["/rm/1/"],
)
assert posted["body"] == {"add_content_units": ["/add/1/"], "remove_content_units": ["/rm/1/"]}
def test_get_task(self, mock_pulp_client, httpx_mock):
"""Test _get_task method."""
# Mock the task endpoint
httpx_mock.get("https://pulp.example.com/pulp/api/v3/tasks/12345/").mock(
return_value=httpx.Response(
200,
json={"pulp_href": "/pulp/api/v3/tasks/12345/", "state": "completed", "result": {"status": "success"}},
)
)
result = mock_pulp_client.get_task("/pulp/api/v3/tasks/12345/")
# Now returns a TaskResponse model
from pulp_tool.models.pulp_api import TaskResponse
assert isinstance(result, TaskResponse)
assert result.state == "completed"
def test_wait_for_finished_task_success(self, mock_pulp_client, httpx_mock):
"""Test wait_for_finished_task method with successful completion."""
# Mock the task endpoint
httpx_mock.get("https://pulp.example.com/pulp/api/v3/tasks/12345/").mock(
return_value=httpx.Response(200, json={"pulp_href": "/pulp/api/v3/tasks/12345/", "state": "completed"})
)
with patch("time.sleep"):
result = mock_pulp_client.wait_for_finished_task("/pulp/api/v3/tasks/12345/")
# Now returns a TaskResponse model
from pulp_tool.models.pulp_api import TaskResponse
assert isinstance(result, TaskResponse)
assert result.state == "completed"
def test_wait_for_finished_task_timeout(self, mock_pulp_client, httpx_mock):
"""Test wait_for_finished_task method with timeout."""
# Mock the task endpoint to return running state
httpx_mock.get("https://pulp.example.com/pulp/api/v3/tasks/12345/").mock(
return_value=httpx.Response(200, json={"pulp_href": "/pulp/api/v3/tasks/12345/", "state": "running"})
)
# The method now raises TimeoutError instead of returning the last response
with patch("time.sleep"), patch("time.time", side_effect=[0, 0.5, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]):
with patch("pulp_tool.api.task_manager.logging"):
result = mock_pulp_client.wait_for_finished_task("/pulp/api/v3/tasks/12345/", timeout=1)
# Now returns a TaskResponse model even on timeout (last state)
from pulp_tool.models.pulp_api import TaskResponse
assert isinstance(result, TaskResponse)
assert result.state == "running"
def test_find_content_by_build_id(self, mock_pulp_client, httpx_mock):
"""Test find_content method by build_id."""
# Mock the content search endpoint
httpx_mock.get(
"https://pulp.example.com/pulp/api/v3/test-domain/api/v3/content/?pulp_label_select=build_id~test-build-123"
).mock(
return_value=httpx.Response(
200, json={"results": [{"pulp_href": "/pulp/api/v3/content/rpm/packages/12345/"}]}
)
)
result = mock_pulp_client.find_content("build_id", "test-build-123")
assert result.status_code == 200
assert len(result.json()["results"]) == 1
def test_find_content_by_href(self, mock_pulp_client, httpx_mock):
"""Test find_content method by href."""
# Mock the content search endpoint
httpx_mock.get(
"https://pulp.example.com/pulp/api/v3/test-domain/api/v3/content/?pulp_href__in=/pulp/api/v3/content/12345/"
).mock(return_value=httpx.Response(200, json={"results": [{"pulp_href": "/pulp/api/v3/content/12345/"}]}))
result = mock_pulp_client.find_content("href", "/pulp/api/v3/content/12345/")
assert result.status_code == 200
assert len(result.json()["results"]) == 1
def test_find_content_invalid_type(self, mock_pulp_client):
"""Test find_content method with invalid search type."""
with pytest.raises(ValueError, match="Unknown search type"):
mock_pulp_client.find_content("invalid", "test-value")
def test_get_file_locations(self, mock_pulp_client, httpx_mock):
"""Test get_file_locations method."""
# Mock the artifacts endpoint
httpx_mock.get(
"https://pulp.example.com/pulp/api/v3/test-domain/api/v3/artifacts/"
"?pulp_href__in=/pulp/api/v3/artifacts/12345/"
).mock(return_value=httpx.Response(200, json={"results": [{"pulp_href": "/pulp/api/v3/artifacts/12345/"}]}))
artifacts = [{"file": "/pulp/api/v3/artifacts/12345/"}]
result = mock_pulp_client.get_file_locations(artifacts)
assert result.status_code == 200
assert len(result.json()["results"]) == 1
def test_get_rpm_by_pkgIDs(self, mock_pulp_client, httpx_mock):
"""Test get_rpm_by_pkgIDs method."""
# Mock the RPM search endpoint - URL encoding uses %2C for comma
httpx_mock.get(
"https://pulp.example.com/pulp/api/v3/test-domain/api/v3/content/rpm/packages/"
"?pkgId__in=abcd1234%2Cefgh5678"
).mock(
return_value=httpx.Response(
200, json={"results": [{"pulp_href": "/pulp/api/v3/content/rpm/packages/12345/"}]}
)
)
pkg_ids = ["abcd1234", "efgh5678"]
result = mock_pulp_client.get_rpm_by_pkgIDs(pkg_ids)
assert result.status_code == 200
assert len(result.json()["results"]) == 1
def test_get_rpm_by_filenames(self, mock_pulp_client, httpx_mock):
"""Test get_rpm_by_filenames parses filename to NVR and searches by name+version+release."""
httpx_mock.post("https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token").mock(
return_value=httpx.Response(200, json={"access_token": "test-token", "expires_in": 3600})
)
httpx_mock.get(re.compile(r".*content/rpm/packages/.*name=pkg")).mock(
return_value=httpx.Response(
200,
json={
"results": [
{
"pulp_href": "/pulp/api/v3/content/rpm/packages/12345/",
"location_href": "pkg-1.0-1.x86_64.rpm",
}
]
},
)
)
result = mock_pulp_client.get_rpm_by_filenames(["pkg-1.0-1.x86_64.rpm"])
assert result.status_code == 200
assert len(result.json()["results"]) == 1
assert result.json()["results"][0]["location_href"] == "pkg-1.0-1.x86_64.rpm"
def test_get_rpm_by_signed_by(self, mock_pulp_client, httpx_mock):
"""Test get_rpm_by_signed_by method."""
httpx_mock.post("https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token").mock(
return_value=httpx.Response(200, json={"access_token": "test-token", "expires_in": 3600})
)
httpx_mock.get(re.compile(r".*content/rpm/packages/.*q=.*pulp_label_select.*signed_by")).mock(
return_value=httpx.Response(
200,
json={
"results": [
{
"pulp_href": "/pulp/api/v3/content/rpm/packages/12345/",
"pulp_labels": {"signed_by": "key-id-123"},
}
]
},
)
)
result = mock_pulp_client.get_rpm_by_signed_by(["key-id-123"])
assert result.status_code == 200
assert len(result.json()["results"]) == 1
assert result.json()["results"][0]["pulp_labels"]["signed_by"] == "key-id-123"
def test_get_rpm_by_checksums_and_signed_by_empty(self, mock_pulp_client):
"""Test get_rpm_by_checksums_and_signed_by with empty checksums returns empty (line 1436)."""
result = mock_pulp_client.get_rpm_by_checksums_and_signed_by([], "key-123")
assert result.status_code == 200
assert result.json()["results"] == []
assert result.json()["count"] == 0
def test_get_rpm_by_checksums_and_signed_by_multi_chunk(self, mock_pulp_client, httpx_mock):
"""Test get_rpm_by_checksums_and_signed_by with 4+ checksums uses multi-chunk path (lines 1454-1471)."""
httpx_mock.post("https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token").mock(
return_value=httpx.Response(200, json={"access_token": "test-token", "expires_in": 3600})
)
checksums = ["a" * 64, "b" * 64, "c" * 64, "d" * 64] # 4 checksums = 2 chunks (chunk_size=3)
httpx_mock.get(re.compile(r".*content/rpm/packages/.*q=.*pkgId.*signed_by")).mock(
return_value=httpx.Response(
200,
json={
"results": [
{"pulp_href": f"/pkg/{i}/", "pkgId": c, "pulp_labels": {"signed_by": "key-123"}}
for i, c in enumerate(checksums)
]
},
)
)
result = mock_pulp_client.get_rpm_by_checksums_and_signed_by(checksums, "key-123")
assert result.status_code == 200
assert len(result.json()["results"]) == 4
def test_get_rpm_by_checksums_and_signed_by(self, mock_pulp_client, httpx_mock):
"""Test get_rpm_by_checksums_and_signed_by combines filters in single query."""
httpx_mock.post("https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token").mock(
return_value=httpx.Response(200, json={"access_token": "test-token", "expires_in": 3600})
)
checksum = "a" * 64
httpx_mock.get(re.compile(r".*content/rpm/packages/.*q=.*pkgId.*signed_by")).mock(
return_value=httpx.Response(
200,
json={
"results": [
{
"pulp_href": "/pulp/api/v3/content/rpm/packages/12345/",
"pkgId": checksum,
"pulp_labels": {"signed_by": "key-123"},
}
]
},
)
)
result = mock_pulp_client.get_rpm_by_checksums_and_signed_by([checksum], "key-123")
assert result.status_code == 200
assert len(result.json()["results"]) == 1
assert result.json()["results"][0]["pulp_labels"]["signed_by"] == "key-123"
def test_get_rpm_by_filenames_and_signed_by_combined_multi_nvr(self, mock_pulp_client, httpx_mock):
"""Test get_rpm_by_filenames_and_signed_by combined path with 2 NVRs uses multi-chunk (lines 1535-1544)."""
httpx_mock.post("https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token").mock(
return_value=httpx.Response(200, json={"access_token": "test-token", "expires_in": 3600})
)
# 2 NVRs -> 2 chunks in _fetch_rpm_by_nvr_and_signed_by_combined
httpx_mock.get(re.compile(r".*content/rpm/packages/.*")).mock(
return_value=httpx.Response(
200,
json={
"results": [
{
"pulp_href": "/pkg/1/",
"name": "pkg1",
"version": "1.0",
"release": "1",
"pulp_labels": {"signed_by": "key-123"},
},
{
"pulp_href": "/pkg/2/",
"name": "pkg2",
"version": "1.0",
"release": "1",
"pulp_labels": {"signed_by": "key-123"},
},
]
},
)
)
result = mock_pulp_client.get_rpm_by_filenames_and_signed_by(
["pkg1-1.0-1.x86_64.rpm", "pkg2-1.0-1.x86_64.rpm"], "key-123"
)
assert result.status_code == 200
assert len(result.json()["results"]) == 2
def test_get_rpm_by_filenames_and_signed_by(self, mock_pulp_client, httpx_mock):
"""Test get_rpm_by_filenames_and_signed_by parses to NVR and combines with signed_by."""
httpx_mock.post("https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token").mock(
return_value=httpx.Response(200, json={"access_token": "test-token", "expires_in": 3600})
)
httpx_mock.get(re.compile(r".*content/rpm/packages/.*name=pkg")).mock(
return_value=httpx.Response(
200,
json={
"results": [
{
"pulp_href": "/pulp/api/v3/content/rpm/packages/12345/",
"location_href": "pkg-1.0-1.x86_64.rpm",
"pulp_labels": {"signed_by": "key-123"},
}
]
},
)
)
result = mock_pulp_client.get_rpm_by_filenames_and_signed_by(["pkg-1.0-1.x86_64.rpm"], "key-123")