-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathtest_github_downloader.py
More file actions
1606 lines (1264 loc) · 72.3 KB
/
test_github_downloader.py
File metadata and controls
1606 lines (1264 loc) · 72.3 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 GitHub package downloader."""
import os
import pytest
import stat
import tempfile
import shutil
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
from urllib.parse import urlparse
import requests as requests_lib
from apm_cli.deps.github_downloader import GitHubPackageDownloader
from apm_cli.models.apm_package import (
DependencyReference,
ResolvedReference,
GitReferenceType,
ValidationResult,
APMPackage
)
_CRED_FILL_PATCH = patch(
'apm_cli.core.token_manager.GitHubTokenManager.resolve_credential_from_git',
return_value=None,
)
class TestGitHubPackageDownloader:
"""Test cases for GitHubPackageDownloader."""
def setup_method(self):
"""Set up test fixtures."""
self.downloader = GitHubPackageDownloader()
self.temp_dir = Path(tempfile.mkdtemp())
def teardown_method(self):
"""Clean up test fixtures."""
if self.temp_dir.exists():
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_setup_git_environment_with_github_apm_pat(self):
"""Test Git environment setup with GITHUB_APM_PAT."""
with patch.dict(os.environ, {'GITHUB_APM_PAT': 'test-token'}, clear=True):
downloader = GitHubPackageDownloader()
env = downloader.git_env
# GITHUB_APM_PAT should be used for github_token property (modules purpose)
assert downloader.github_token == 'test-token'
assert downloader.has_github_token is True
# But GITHUB_TOKEN should not be set in env since it wasn't there originally
assert 'GITHUB_TOKEN' not in env or env.get('GITHUB_TOKEN') == 'test-token'
assert env['GH_TOKEN'] == 'test-token'
def test_setup_git_environment_with_github_token(self):
"""Test Git environment setup with GITHUB_TOKEN fallback."""
with patch.dict(os.environ, {'GITHUB_TOKEN': 'fallback-token'}, clear=True):
downloader = GitHubPackageDownloader()
env = downloader.git_env
assert env['GH_TOKEN'] == 'fallback-token'
def test_setup_git_environment_no_token(self):
"""Test Git environment setup with no GitHub token."""
with patch.dict(os.environ, {}, clear=True):
downloader = GitHubPackageDownloader()
env = downloader.git_env
# Should not have GitHub tokens in environment
assert 'GITHUB_TOKEN' not in env or not env['GITHUB_TOKEN']
assert 'GH_TOKEN' not in env or not env['GH_TOKEN']
def test_setup_git_environment_does_not_eagerly_call_credential_helper(self):
"""Constructor should not invoke git credential helper (lazy per-dep auth)."""
with patch.dict(os.environ, {}, clear=True):
with patch(
'apm_cli.core.token_manager.GitHubTokenManager.resolve_credential_from_git'
) as mock_cred:
GitHubPackageDownloader()
mock_cred.assert_not_called()
@patch('apm_cli.deps.github_downloader.Repo')
@patch('tempfile.mkdtemp')
def test_resolve_git_reference_branch(self, mock_mkdtemp, mock_repo_class):
"""Test resolving a branch reference."""
# Setup mocks
mock_temp_dir = '/tmp/test'
mock_mkdtemp.return_value = mock_temp_dir
mock_repo = Mock()
mock_repo.head.commit.hexsha = 'abc123def456'
mock_repo_class.clone_from.return_value = mock_repo
with patch('pathlib.Path.exists', return_value=True), \
patch('shutil.rmtree'):
result = self.downloader.resolve_git_reference('user/repo#main')
assert isinstance(result, ResolvedReference)
assert result.original_ref == 'github.com/user/repo#main'
assert result.ref_type == GitReferenceType.BRANCH
assert result.resolved_commit == 'abc123def456'
assert result.ref_name == 'main'
@patch('apm_cli.deps.github_downloader.Repo')
@patch('tempfile.mkdtemp')
def test_resolve_git_reference_commit(self, mock_mkdtemp, mock_repo_class):
"""Test resolving a commit SHA reference."""
# Setup mocks for failed shallow clone, successful full clone
mock_temp_dir = '/tmp/test'
mock_mkdtemp.return_value = mock_temp_dir
from git.exc import GitCommandError
# First call (shallow clone) fails, second call (full clone) succeeds
mock_repo = Mock()
mock_commit = Mock()
mock_commit.hexsha = 'abcdef123456'
mock_repo.commit.return_value = mock_commit
mock_repo_class.clone_from.side_effect = [
GitCommandError('shallow clone failed'),
mock_repo
]
with patch('pathlib.Path.exists', return_value=True), \
patch('shutil.rmtree'):
result = self.downloader.resolve_git_reference('user/repo#abcdef1')
assert result.ref_type == GitReferenceType.COMMIT
assert result.resolved_commit == 'abcdef123456'
assert result.ref_name == 'abcdef1'
def test_resolve_git_reference_invalid_format(self):
"""Test resolving an invalid repository reference."""
with pytest.raises(ValueError, match="Invalid repository reference"):
self.downloader.resolve_git_reference('invalid-repo-format')
@patch('apm_cli.deps.github_downloader.Repo')
@patch('apm_cli.deps.github_downloader.validate_apm_package')
@patch('apm_cli.deps.github_downloader.shutil.rmtree')
def test_download_package_success(self, mock_rmtree, mock_validate, mock_repo_class):
"""Test successful package download and validation."""
# Setup target directory
target_path = self.temp_dir / "test_package"
# Setup mocks
mock_repo = Mock()
mock_repo_class.clone_from.return_value = mock_repo
# Mock successful validation
mock_validation_result = ValidationResult()
mock_validation_result.is_valid = True
mock_package = APMPackage(name="test-package", version="1.0.0")
mock_validation_result.package = mock_package
mock_validate.return_value = mock_validation_result
# Mock resolve_git_reference
mock_resolved_ref = ResolvedReference(
original_ref="user/repo#main",
ref_type=GitReferenceType.BRANCH,
resolved_commit="abc123",
ref_name="main"
)
with patch.object(self.downloader, 'resolve_git_reference', return_value=mock_resolved_ref):
result = self.downloader.download_package('user/repo#main', target_path)
assert result.package.name == "test-package"
assert result.package.version == "1.0.0"
assert result.install_path == target_path
assert result.resolved_reference == mock_resolved_ref
assert result.installed_at is not None
@patch('apm_cli.deps.github_downloader.Repo')
@patch('apm_cli.deps.github_downloader.validate_apm_package')
@patch('apm_cli.deps.github_downloader.shutil.rmtree')
def test_download_package_validation_failure(self, mock_rmtree, mock_validate, mock_repo_class):
"""Test package download with validation failure."""
# Setup target directory
target_path = self.temp_dir / "test_package"
# Setup mocks
mock_repo = Mock()
mock_repo_class.clone_from.return_value = mock_repo
# Mock validation failure
mock_validation_result = ValidationResult()
mock_validation_result.is_valid = False
mock_validation_result.add_error("Missing apm.yml")
mock_validate.return_value = mock_validation_result
# Mock resolve_git_reference
mock_resolved_ref = ResolvedReference(
original_ref="user/repo#main",
ref_type=GitReferenceType.BRANCH,
resolved_commit="abc123",
ref_name="main"
)
with patch.object(self.downloader, 'resolve_git_reference', return_value=mock_resolved_ref):
with pytest.raises(RuntimeError, match="Invalid APM package"):
self.downloader.download_package('user/repo#main', target_path)
@patch('apm_cli.deps.github_downloader.Repo')
def test_download_package_git_failure(self, mock_repo_class):
"""Test package download with Git clone failure."""
# Setup target directory
target_path = self.temp_dir / "test_package"
# Setup mocks
from git.exc import GitCommandError
mock_repo_class.clone_from.side_effect = GitCommandError("Clone failed")
# Mock resolve_git_reference
mock_resolved_ref = ResolvedReference(
original_ref="user/repo#main",
ref_type=GitReferenceType.BRANCH,
resolved_commit="abc123",
ref_name="main"
)
with patch.object(self.downloader, 'resolve_git_reference', return_value=mock_resolved_ref):
with pytest.raises(RuntimeError, match="Failed to clone repository"):
self.downloader.download_package('user/repo#main', target_path)
def test_download_package_invalid_repo_ref(self):
"""Test package download with invalid repository reference."""
target_path = self.temp_dir / "test_package"
with pytest.raises(ValueError, match="Invalid repository reference"):
self.downloader.download_package('invalid-repo-format', target_path)
@patch('apm_cli.deps.github_downloader.Repo')
@patch('apm_cli.deps.github_downloader.validate_apm_package')
@patch('apm_cli.deps.github_downloader.shutil.rmtree')
def test_download_package_commit_checkout(self, mock_rmtree, mock_validate, mock_repo_class):
"""Test package download with commit checkout."""
# Setup target directory
target_path = self.temp_dir / "test_package"
# Setup mocks
mock_repo = Mock()
mock_repo.git = Mock()
mock_repo_class.clone_from.return_value = mock_repo
# Mock successful validation
mock_validation_result = ValidationResult()
mock_validation_result.is_valid = True
mock_package = APMPackage(name="test-package", version="1.0.0")
mock_validation_result.package = mock_package
mock_validate.return_value = mock_validation_result
# Mock resolve_git_reference returning a commit
mock_resolved_ref = ResolvedReference(
original_ref="user/repo#abc123",
ref_type=GitReferenceType.COMMIT,
resolved_commit="abc123def456",
ref_name="abc123"
)
with patch.object(self.downloader, 'resolve_git_reference', return_value=mock_resolved_ref):
result = self.downloader.download_package('user/repo#abc123', target_path)
# Verify that git checkout was called for commit
mock_repo.git.checkout.assert_called_once_with("abc123def456")
assert result.package.name == "test-package"
def test_get_clone_progress_callback(self):
"""Test the progress callback for Git clone operations."""
callback = self.downloader._get_clone_progress_callback()
# Test with max_count
with patch('builtins.print') as mock_print:
callback(1, 50, 100, "Cloning")
mock_print.assert_called_with("\r Cloning: 50% (50/100) Cloning", end='', flush=True)
# Test without max_count
with patch('builtins.print') as mock_print:
callback(1, 25, None, "Receiving objects")
mock_print.assert_called_with("\r Cloning: Receiving objects (25)", end='', flush=True)
class TestGitHubPackageDownloaderIntegration:
"""Integration tests that require actual Git operations (to be run with network access)."""
def setup_method(self):
"""Set up test fixtures."""
self.downloader = GitHubPackageDownloader()
self.temp_dir = Path(tempfile.mkdtemp())
def teardown_method(self):
"""Clean up test fixtures."""
if self.temp_dir.exists():
shutil.rmtree(self.temp_dir, ignore_errors=True)
@pytest.mark.integration
def test_resolve_reference_real_repo(self):
"""Test resolving references on a real repository (requires network)."""
# This test would require a real repository - skip in CI
pytest.skip("Integration test requiring network access")
@pytest.mark.integration
def test_download_real_package(self):
"""Test downloading a real APM package (requires network)."""
# This test would require a real APM package repository - skip in CI
pytest.skip("Integration test requiring network access")
class TestEnterpriseHostHandling:
"""Test enterprise GitHub host handling (PR #33 bug fixes)."""
@patch('apm_cli.deps.github_downloader.Repo')
def test_clone_fallback_respects_enterprise_host(self, mock_repo_class, monkeypatch):
"""Test that fallback clone uses enterprise host, not hardcoded github.com.
This tests the bug fix from PR #33 where Method 3 fallback was hardcoded
to github.com instead of respecting the configured host.
"""
from git.exc import GitCommandError
monkeypatch.setenv("GITHUB_HOST", "company.ghe.com")
monkeypatch.setenv("GITHUB_APM_PAT", "test-enterprise-token")
downloader = GitHubPackageDownloader()
downloader.github_host = "company.ghe.com"
# Mock clone attempts: first two fail, third succeeds
mock_repo = Mock()
mock_repo.head.commit.hexsha = "abc123"
mock_repo_class.clone_from.side_effect = [
GitCommandError("auth", "Authentication failed"), # Method 1 fails
GitCommandError("ssh", "SSH failed"), # Method 2 fails
mock_repo # Method 3 succeeds
]
target_path = Path("/tmp/test_enterprise")
with patch('pathlib.Path.exists', return_value=False):
result = downloader._clone_with_fallback("team/internal-repo", target_path)
# Verify Method 3 used enterprise host, NOT github.com
calls = mock_repo_class.clone_from.call_args_list
assert len(calls) == 3
third_call_url = calls[2][0][0] # First positional arg of third call
# Should use company.ghe.com, NOT github.com
assert "company.ghe.com" in third_call_url
assert "team/internal-repo" in third_call_url
# Ensure it's NOT using github.com
assert "github.com" not in third_call_url or "company.ghe.com" in third_call_url
def test_host_persists_through_clone_attempts(self, monkeypatch):
"""Test that github_host attribute persists across fallback attempts."""
monkeypatch.setenv("GITHUB_HOST", "custom.ghe.com")
downloader = GitHubPackageDownloader()
downloader.github_host = "custom.ghe.com"
# Build URLs for both SSH and HTTPS methods
url_ssh = downloader._build_repo_url("owner/repo", use_ssh=True)
url_https = downloader._build_repo_url("owner/repo", use_ssh=False)
assert "custom.ghe.com" in url_ssh
assert "custom.ghe.com" in url_https
assert "owner/repo" in url_https
# Should NOT fall back to github.com
assert "github.com" not in url_https or "custom.ghe.com" in url_https
def test_multiple_hosts_resolution(self, monkeypatch):
"""Test installing packages from multiple GitHub hosts."""
monkeypatch.setenv("GITHUB_HOST", "company.ghe.com")
# Test bare dependency uses GITHUB_HOST
dep1 = DependencyReference.parse("team/internal-package")
assert dep1.repo_url == "team/internal-package"
# Host should be set when downloader processes it
# Test explicit github.com
dep2 = DependencyReference.parse("github.com/public/open-source")
assert dep2.host == "github.com"
assert dep2.repo_url == "public/open-source"
# Test explicit partner GHE
dep3 = DependencyReference.parse("partner.ghe.com/external/tool")
assert dep3.host == "partner.ghe.com"
assert dep3.repo_url == "external/tool"
class TestErrorHandling:
"""Test error handling scenarios."""
def test_network_timeout_handling(self):
"""Test handling of network timeouts."""
# Would require mocking network timeouts
pass
def test_authentication_failure_handling(self):
"""Test handling of authentication failures."""
# Would require mocking authentication failures
pass
def test_download_raw_file_saml_fallback_retries_without_token(self):
"""Test that download_raw_file retries without token on 401/403 (SAML/SSO)."""
with patch.dict(os.environ, {'GITHUB_APM_PAT': 'saml-blocked-token'}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('microsoft/some-public-repo/sub/dir')
# First call (with token) returns 401, second call (without token) returns 200
mock_response_401 = Mock()
mock_response_401.status_code = 401
mock_response_401.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_401)
)
mock_response_200 = Mock()
mock_response_200.status_code = 200
mock_response_200.content = b'# SKILL.md content'
mock_response_200.raise_for_status = Mock()
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get:
mock_get.side_effect = [mock_response_401, mock_response_200]
result = downloader.download_raw_file(dep_ref, 'sub/dir/SKILL.md', 'main')
assert result == b'# SKILL.md content'
# First call should include auth header
first_call_headers = mock_get.call_args_list[0][1].get('headers', {})
assert 'Authorization' in first_call_headers
# Second (retry) call should NOT include auth header
second_call_headers = mock_get.call_args_list[1][1].get('headers', {})
assert 'Authorization' not in second_call_headers
def test_download_raw_file_saml_fallback_not_used_for_ghe_cloud_dr(self):
"""Test that SAML fallback does NOT apply to *.ghe.com (no public repos)."""
with patch.dict(os.environ, {'GITHUB_APM_PAT': 'ghe-token'}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('company.ghe.com/owner/repo/sub/path')
mock_response_403 = Mock()
mock_response_403.status_code = 403
mock_response_403.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_403)
)
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get:
mock_get.return_value = mock_response_403
with pytest.raises(RuntimeError, match="Authentication failed"):
downloader.download_raw_file(dep_ref, 'sub/path/file.md', 'main')
# Should only have been called once — no retry for *.ghe.com
assert mock_get.call_count == 1
def test_download_raw_file_saml_fallback_applies_to_ghes(self):
"""Test that SAML fallback DOES apply to GHES custom domains (can have public repos)."""
with patch.dict(os.environ, {'GITHUB_APM_PAT': 'ghes-token', 'GITHUB_HOST': 'github.mycompany.com'}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('github.mycompany.com/owner/repo/sub/path')
mock_response_401 = Mock()
mock_response_401.status_code = 401
mock_response_401.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_401)
)
mock_response_200 = Mock()
mock_response_200.status_code = 200
mock_response_200.content = b'# Public GHES content'
mock_response_200.raise_for_status = Mock()
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get:
mock_get.side_effect = [mock_response_401, mock_response_200]
result = downloader.download_raw_file(dep_ref, 'sub/path/SKILL.md', 'main')
assert result == b'# Public GHES content'
# Should have retried without auth
assert mock_get.call_count == 2
second_call_headers = mock_get.call_args_list[1][1].get('headers', {})
assert 'Authorization' not in second_call_headers
def test_download_raw_file_saml_fallback_retries_and_still_fails(self):
"""Test that when both authenticated and unauthenticated attempts fail, an error is raised."""
with patch.dict(os.environ, {'GITHUB_APM_PAT': 'saml-blocked-token'}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('microsoft/private-repo/sub/dir')
mock_response_401_first = Mock()
mock_response_401_first.status_code = 401
mock_response_401_first.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_401_first)
)
mock_response_401_second = Mock()
mock_response_401_second.status_code = 401
mock_response_401_second.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_401_second)
)
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get:
mock_get.side_effect = [mock_response_401_first, mock_response_401_second]
with pytest.raises(RuntimeError, match="Authentication failed"):
downloader.download_raw_file(dep_ref, 'sub/dir/SKILL.md', 'main')
# Both attempts should have been made
assert mock_get.call_count == 2
# First call should include auth header
first_call_headers = mock_get.call_args_list[0][1].get('headers', {})
assert 'Authorization' in first_call_headers
# Second (retry) call should NOT include auth header
second_call_headers = mock_get.call_args_list[1][1].get('headers', {})
assert 'Authorization' not in second_call_headers
def test_repository_not_found_handling(self):
"""Test handling of repository not found errors."""
# Would require mocking 404 errors
pass
def test_download_github_file_403_rate_limit_no_token(self):
"""Test that 403 with X-RateLimit-Remaining: 0 and no token gives a rate-limit error."""
with patch.dict(os.environ, {}, clear=True), _CRED_FILL_PATCH:
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('github/awesome-copilot/agents/api-architect.agent.md')
mock_response_403 = Mock()
mock_response_403.status_code = 403
mock_response_403.headers = {'X-RateLimit-Remaining': '0', 'X-RateLimit-Reset': '0'}
mock_response_403.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_403)
)
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get, \
patch('apm_cli.deps.github_downloader.time.sleep'):
# _resilient_get retries 3 times on rate-limit 403, all return same
mock_get.return_value = mock_response_403
with pytest.raises(RuntimeError, match="rate limit exceeded") as exc_info:
downloader.download_raw_file(dep_ref, 'agents/api-architect.agent.md', 'main')
# Must NOT mention "private repository" — that's the old misleading message
assert "private repository" not in str(exc_info.value).lower()
assert "60/hour" in str(exc_info.value)
def test_download_github_file_403_rate_limit_with_token(self):
"""Test that 403 with X-RateLimit-Remaining: 0 and a token gives a rate-limit error."""
with patch.dict(os.environ, {'GITHUB_APM_PAT': 'my-token'}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('github/awesome-copilot/agents/api-architect.agent.md')
mock_response_403 = Mock()
mock_response_403.status_code = 403
mock_response_403.headers = {'X-RateLimit-Remaining': '0', 'X-RateLimit-Reset': '0'}
mock_response_403.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_403)
)
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get, \
patch('apm_cli.deps.github_downloader.time.sleep'):
mock_get.return_value = mock_response_403
with pytest.raises(RuntimeError, match="rate limit exceeded") as exc_info:
downloader.download_raw_file(dep_ref, 'agents/api-architect.agent.md', 'main')
assert "Authenticated rate limit exhausted" in str(exc_info.value)
assert "SSO/SAML" not in str(exc_info.value)
def test_download_github_file_403_non_rate_limit_still_auth_error(self):
"""Test that 403 WITHOUT rate-limit headers still produces the auth error."""
with patch.dict(os.environ, {}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('owner/private-repo/sub/file.agent.md')
mock_response_403 = Mock()
mock_response_403.status_code = 403
# No rate-limit headers — this is a genuine auth failure
mock_response_403.headers = {}
mock_response_403.raise_for_status = Mock(
side_effect=requests_lib.exceptions.HTTPError(response=mock_response_403)
)
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get:
mock_get.return_value = mock_response_403
with pytest.raises(RuntimeError, match="Authentication failed"):
downloader.download_raw_file(dep_ref, 'sub/file.agent.md', 'main')
def test_resilient_get_retries_on_403_rate_limit(self):
"""Test that _resilient_get retries when 403 has X-RateLimit-Remaining: 0."""
with patch.dict(os.environ, {}, clear=True):
downloader = GitHubPackageDownloader()
mock_response_403 = Mock()
mock_response_403.status_code = 403
mock_response_403.headers = {'X-RateLimit-Remaining': '0', 'X-RateLimit-Reset': '0'}
mock_response_200 = Mock()
mock_response_200.status_code = 200
mock_response_200.headers = {'X-RateLimit-Remaining': '50'}
mock_response_200.content = b'success'
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get, \
patch('apm_cli.deps.github_downloader.time.sleep'):
mock_get.side_effect = [mock_response_403, mock_response_200]
response = downloader._resilient_get('https://api.github.com/repos/test', {})
assert response.status_code == 200
assert mock_get.call_count == 2
def test_resilient_get_does_not_retry_403_without_rate_limit_header(self):
"""Test that _resilient_get does NOT retry 403 without rate-limit exhaustion."""
with patch.dict(os.environ, {}, clear=True):
downloader = GitHubPackageDownloader()
mock_response_403 = Mock()
mock_response_403.status_code = 403
mock_response_403.headers = {} # No rate-limit headers
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get:
mock_get.return_value = mock_response_403
response = downloader._resilient_get('https://api.github.com/repos/test', {})
# Should return immediately — no retry for non-rate-limit 403
assert response.status_code == 403
assert mock_get.call_count == 1
def test_resilient_get_403_with_nonzero_remaining_not_retried(self):
"""Test that 403 with X-RateLimit-Remaining > 0 is NOT retried as rate limiting."""
with patch.dict(os.environ, {}, clear=True):
downloader = GitHubPackageDownloader()
mock_response_403 = Mock()
mock_response_403.status_code = 403
mock_response_403.headers = {'X-RateLimit-Remaining': '42'}
with patch('apm_cli.deps.github_downloader.requests.get') as mock_get:
mock_get.return_value = mock_response_403
response = downloader._resilient_get('https://api.github.com/repos/test', {})
assert response.status_code == 403
assert mock_get.call_count == 1
class TestAzureDevOpsSupport:
"""Test Azure DevOps package support."""
def setup_method(self):
"""Set up test fixtures."""
self.temp_dir = Path(tempfile.mkdtemp())
def teardown_method(self):
"""Clean up test fixtures."""
if self.temp_dir.exists():
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_setup_git_environment_with_ado_token(self):
"""Test Git environment setup picks up ADO_APM_PAT."""
with patch.dict(os.environ, {'ADO_APM_PAT': 'ado-test-token'}, clear=True):
downloader = GitHubPackageDownloader()
assert downloader.ado_token == 'ado-test-token'
assert downloader.has_ado_token is True
def test_setup_git_environment_no_ado_token(self):
"""Test Git environment setup without ADO token."""
with patch.dict(os.environ, {'GITHUB_APM_PAT': 'github-token'}, clear=True):
downloader = GitHubPackageDownloader()
assert downloader.ado_token is None
assert downloader.has_ado_token is False
# GitHub token should still work
assert downloader.github_token == 'github-token'
assert downloader.has_github_token is True
def test_build_repo_url_for_ado_with_token(self):
"""Test URL building for ADO packages with token."""
with patch.dict(os.environ, {'ADO_APM_PAT': 'ado-token'}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('dev.azure.com/myorg/myproject/_git/myrepo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
# Should build ADO URL with token embedded in userinfo
assert parsed.hostname == 'dev.azure.com'
assert 'myorg' in parsed.path
assert 'myproject' in parsed.path
assert '_git' in parsed.path
assert 'myrepo' in parsed.path
# Token should be in the URL (as username in https://token@host format)
assert parsed.username == 'ado-token' or 'ado-token' in (parsed.password or '')
def test_build_repo_url_for_ado_without_token(self):
"""Test URL building for ADO packages without token."""
with patch.dict(os.environ, {}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('dev.azure.com/myorg/myproject/_git/myrepo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
# Should build ADO URL without token
assert parsed.hostname == 'dev.azure.com'
assert 'myorg/myproject/_git/myrepo' in parsed.path
# No credentials in URL
assert parsed.username is None
assert parsed.password is None
def test_build_repo_url_for_ado_ssh(self):
"""Test SSH URL building for ADO packages."""
with patch.dict(os.environ, {}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('dev.azure.com/myorg/myproject/_git/myrepo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=True, dep_ref=dep_ref)
# Should build ADO SSH URL (git@ssh.dev.azure.com:v3/org/project/repo)
assert url.startswith('git@ssh.dev.azure.com:')
def test_build_ado_urls_with_spaces_in_project(self):
"""Test that URL builders properly encode spaces in ADO project names."""
from apm_cli.utils.github_host import (
build_ado_https_clone_url,
build_ado_ssh_url,
build_ado_api_url,
)
# HTTPS clone URL with token
url = build_ado_https_clone_url("myorg", "My Project", "myrepo", token="tok")
assert "My%20Project" in url
assert "My Project" not in url
assert url == "https://tok@dev.azure.com/myorg/My%20Project/_git/myrepo"
# HTTPS clone URL without token
url = build_ado_https_clone_url("myorg", "My Project", "myrepo")
assert url == "https://dev.azure.com/myorg/My%20Project/_git/myrepo"
# SSH cloud URL
url = build_ado_ssh_url("myorg", "My Project", "myrepo")
assert "My%20Project" in url
assert url == "git@ssh.dev.azure.com:v3/myorg/My%20Project/myrepo"
# SSH server URL
url = build_ado_ssh_url("myorg", "My Project", "myrepo", host="ado.company.com")
assert "My%20Project" in url
# API URL
url = build_ado_api_url("myorg", "My Project", "myrepo", "path/file.md")
assert "My%20Project" in url
assert "My Project" not in url
def test_build_repo_url_github_not_affected_by_ado_token(self):
"""Test that GitHub URL building uses GitHub token, not ADO token."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('owner/repo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
# Should use GitHub token, not ADO token
assert parsed.hostname == 'github.com'
# Verify ADO token is not used for GitHub URLs
assert 'ado-token' not in url and 'ado-token' != parsed.username
def test_clone_with_fallback_selects_ado_token(self):
"""Test that _clone_with_fallback uses ADO token for ADO packages."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('dev.azure.com/myorg/myproject/_git/myrepo')
# Mock _build_repo_url to capture what's passed
with patch.object(downloader, '_build_repo_url') as mock_build:
mock_build.return_value = 'https://ado-token@dev.azure.com/myorg/myproject/_git/myrepo'
with patch('apm_cli.deps.github_downloader.Repo') as mock_repo:
mock_repo.clone_from.return_value = Mock()
try:
downloader._clone_with_fallback(
dep_ref.repo_url,
self.temp_dir,
dep_ref=dep_ref
)
except Exception:
pass # May fail due to mocking, we just want to check the call
# Verify _build_repo_url was called with dep_ref
if mock_build.called:
call_args = mock_build.call_args
assert call_args[1].get('dep_ref') is not None
def test_clone_with_fallback_selects_github_token(self):
"""Test that _clone_with_fallback uses GitHub token for GitHub packages."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token'
}, clear=True):
dep_ref = DependencyReference.parse('owner/repo')
# The is_ado check should be False for GitHub packages
assert not dep_ref.is_azure_devops()
class TestMixedSourceTokenSelection:
"""Test token selection for mixed-source installations (GitHub.com + GHE + ADO)."""
def setup_method(self):
"""Set up test fixtures."""
self.temp_dir = Path(tempfile.mkdtemp())
def teardown_method(self):
"""Clean up test fixtures."""
if self.temp_dir.exists():
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_mixed_tokens_github_com(self):
"""Test that github.com packages use GITHUB_APM_PAT."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('github.com/owner/repo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
assert parsed.hostname == 'github.com'
# GitHub token should be present, ADO token should not
assert 'ado-token' not in url and parsed.username != 'ado-token'
def test_mixed_tokens_ghe(self):
"""Test that GHE packages use GITHUB_APM_PAT."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('octodemo-eu.ghe.com/owner/repo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
assert parsed.hostname == 'octodemo-eu.ghe.com'
# ADO token should not be used for GHE
assert 'ado-token' not in url and parsed.username != 'ado-token'
def test_mixed_tokens_ado(self):
"""Test that ADO packages use ADO_APM_PAT."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('dev.azure.com/myorg/myproject/_git/myrepo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
assert parsed.hostname == 'dev.azure.com'
# ADO token should be used (as username), GitHub token should not
assert parsed.username == 'ado-token' or 'ado-token' in (parsed.password or '')
assert 'github-token' not in url
def test_mixed_tokens_bare_owner_repo_with_github_host(self):
"""Test bare owner/repo uses GITHUB_HOST and GITHUB_APM_PAT."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token',
'GITHUB_HOST': 'company.ghe.com'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('owner/repo')
# Simulate resolution to custom host
# The dep_ref.host will be github.com by default, but GITHUB_HOST
# affects the actual URL building in the downloader
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
# Should use GitHub token for GitHub-family hosts, not ADO token
assert 'ado-token' not in url and parsed.username != 'ado-token'
def test_mixed_installation_token_isolation(self):
"""Test that tokens are isolated per platform in mixed installation."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token',
'ADO_APM_PAT': 'ado-token'
}, clear=True):
downloader = GitHubPackageDownloader()
# Parse multiple deps from different sources
github_dep = DependencyReference.parse('github.com/owner/repo')
ghe_dep = DependencyReference.parse('company.ghe.com/owner/repo')
ado_dep = DependencyReference.parse('dev.azure.com/org/proj/_git/repo')
# Build URLs for each
github_url = downloader._build_repo_url(github_dep.repo_url, use_ssh=False, dep_ref=github_dep)
ghe_url = downloader._build_repo_url(ghe_dep.repo_url, use_ssh=False, dep_ref=ghe_dep)
ado_url = downloader._build_repo_url(ado_dep.repo_url, use_ssh=False, dep_ref=ado_dep)
github_parsed = urlparse(github_url)
ghe_parsed = urlparse(ghe_url)
ado_parsed = urlparse(ado_url)
# Verify correct hosts
assert github_parsed.hostname == 'github.com'
assert ghe_parsed.hostname == 'company.ghe.com'
assert ado_parsed.hostname == 'dev.azure.com'
# Verify token isolation - ADO token only in ADO URL
assert 'ado-token' not in github_url
assert 'ado-token' not in ghe_url
assert ado_parsed.username == 'ado-token' or 'ado-token' in (ado_parsed.password or '')
# Verify GitHub token not in ADO URL
assert 'github-token' not in ado_url
def test_github_ado_without_ado_token_falls_back(self):
"""Test ADO without token still builds valid URL."""
with patch.dict(os.environ, {
'GITHUB_APM_PAT': 'github-token'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('dev.azure.com/myorg/myproject/_git/myrepo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
# Should build valid ADO URL without auth
assert parsed.hostname == 'dev.azure.com'
assert 'myorg/myproject/_git/myrepo' in parsed.path
# GitHub token should NOT be used for ADO - no credentials at all
assert parsed.username is None or parsed.username != 'github-token'
assert 'github-token' not in url
def test_ghe_without_github_token_falls_back(self):
"""Test GHE without token still builds valid URL."""
with patch.dict(os.environ, {
'ADO_APM_PAT': 'ado-token'
}, clear=True):
downloader = GitHubPackageDownloader()
dep_ref = DependencyReference.parse('company.ghe.com/owner/repo')
url = downloader._build_repo_url(dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref)
parsed = urlparse(url)
# Should build valid GHE URL without auth
assert parsed.hostname == 'company.ghe.com'
assert 'owner/repo' in parsed.path
# ADO token should NOT be used for GHE - no credentials at all
assert parsed.username is None or parsed.username != 'ado-token'
assert 'ado-token' not in url
class TestSubdirectoryPackageCommitSHA:
"""Test commit SHA handling in download_subdirectory_package."""
def setup_method(self):
self.temp_dir = Path(tempfile.mkdtemp())
def teardown_method(self):
if self.temp_dir.exists():
shutil.rmtree(self.temp_dir, ignore_errors=True)
def _make_dep_ref(self, ref=None):
"""Create a virtual subdirectory DependencyReference."""
dep = DependencyReference(
repo_url='owner/monorepo',
host='github.com',
reference=ref,
virtual_path='packages/my-skill',
is_virtual=True,
)
return dep
@patch('apm_cli.deps.github_downloader.Repo')
@patch('apm_cli.deps.github_downloader.validate_apm_package')
def test_sha_ref_clones_without_depth_and_checks_out(self, mock_validate, mock_repo_class):
"""Commit SHA refs must clone with no_checkout (no depth/branch) then checkout the SHA."""
sha = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2'
dep_ref = self._make_dep_ref(ref=sha)
mock_repo = Mock()
mock_repo_class.return_value = mock_repo