Repository navigation
Expand file tree
/
Copy pathtest_sdk_methods.py
More file actions
693 lines (553 loc) · 25.5 KB
/
Copy pathtest_sdk_methods.py
File metadata and controls
693 lines (553 loc) · 25.5 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
import logging
import pytest
from socketdev.exceptions import (
APIAccessDenied,
APIFailure,
APIInsufficientPermissions,
APIInsufficientQuota,
APIResourceNotFound,
)
from socketdev.fullscans import FullScanParams, FullScanStreamResponse, ScanType
from socketsecurity.config import CliConfig
from socketsecurity.core import ANCESTOR_SCAN_LOOKUP_LIMIT, SCAN_LOOKUP_PAGE_SIZE, Core
from socketsecurity.core.socket_config import SocketConfig
@pytest.fixture
def core(mock_sdk_with_responses):
config = SocketConfig(api_key="test_key")
return Core(config=config, sdk=mock_sdk_with_responses)
def make_cli_config(*extra_args):
return CliConfig.from_args(["--api-token", "test-token", "--repo", "test", *extra_args])
def make_full_scan_params(**overrides):
values = {
"repo": "test",
"branch": "main",
"commit_hash": "head123",
"scan_type": "socket",
"workspace": None,
}
values.update(overrides)
return FullScanParams(**values)
def test_get_repo_info(core, mock_sdk_with_responses):
"""Test getting repository information"""
repo_info = core.get_repo_info("test")
# Assert SDK called correctly
mock_sdk_with_responses.repos.repo.assert_called_once_with(
core.config.org_slug,
"test",
use_types=True,
)
# Assert response processed correctly
assert repo_info.id == "f639d6c9-acc3-4d8a-9fb5-2090ad651c7e"
assert repo_info.head_full_scan_id == "head"
def test_get_repo_info_logs_why_repo_creation_failed(core, mock_sdk_with_responses, caplog):
"""A repo that isn't in Socket yet and can't be created exits 2 with the reason logged"""
mock_sdk_with_responses.repos.repo.side_effect = APIResourceNotFound(status_code=404)
# Mirrors the SDK, which appends the request path and response headers to the message
mock_sdk_with_responses.repos.post.side_effect = APIAccessDenied(
"Insufficient permissions\nPath: https://api.socket.dev/v0/orgs/test/repos\n\nHeaders:\nx-req: 1",
status_code=403,
)
with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit) as exit_info:
core.get_repo_info("new-repo")
assert exit_info.value.code == 2
messages = [record.getMessage() for record in caplog.records]
assert "Failed to get repository new-repo, attempting to create it" in messages
assert "API failure while creating repository new-repo (HTTP 403): Insufficient permissions" in messages
assert any("repo:create" in message for message in messages)
@pytest.mark.parametrize(
("error", "expected_reason", "expects_scope_hint"),
[
(APIInsufficientPermissions(status_code=403), "APIInsufficientPermissions", True),
(APIInsufficientQuota(status_code=403), "APIInsufficientQuota", False),
],
)
def test_get_repo_info_repo_creation_failure_reason(
core, mock_sdk_with_responses, caplog, error, expected_reason, expects_scope_hint
):
"""Message-less SDK errors still name a reason, and only permission 403s get the scope hint"""
mock_sdk_with_responses.repos.repo.side_effect = APIResourceNotFound(status_code=404)
mock_sdk_with_responses.repos.post.side_effect = error
with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit):
core.get_repo_info("new-repo")
messages = [record.getMessage() for record in caplog.records]
assert f"API failure while creating repository new-repo (HTTP 403): {expected_reason}" in messages
assert any("repo:create" in message for message in messages) is expects_scope_hint
def test_get_repo_info_restores_log_level_after_creating_repo(
core, mock_sdk_with_responses, repo_info_response, caplog
):
"""Creating a missing repo must not leave the socketdev logger muted for the rest of the run"""
mock_sdk_with_responses.repos.repo.side_effect = [
APIResourceNotFound(status_code=404),
repo_info_response,
]
mock_sdk_with_responses.repos.post.return_value = {"id": "created"}
with caplog.at_level(logging.INFO, logger="socketdev"):
repo_info = core.get_repo_info("new-repo")
assert logging.getLogger("socketdev").level == logging.INFO
assert repo_info.id == "f639d6c9-acc3-4d8a-9fb5-2090ad651c7e"
def test_get_head_scan_for_repo(core, mock_sdk_with_responses):
"""Test getting head scan ID for a repository"""
head_scan_id = core.get_head_scan_for_repo("test")
# Assert SDK method called correctly
mock_sdk_with_responses.repos.repo.assert_called_once_with(
core.config.org_slug,
"test",
use_types=True,
)
# Assert we got the expected head scan ID
assert head_scan_id == "head"
def test_get_head_scan_for_repo_no_head(core, mock_sdk_with_responses):
"""Test getting head scan ID for repo with no head scan"""
head_scan_id = core.get_head_scan_for_repo("no-head")
assert head_scan_id is None
def test_get_head_scan_for_repo_scopes_workspace_to_default_branch(
core, mock_sdk_with_responses
):
mock_sdk_with_responses.fullscans.get.return_value = {
"results": [{"id": "workspace-head"}],
"nextPage": None,
}
head_scan_id = core.get_head_scan_for_repo(
"test",
workspace="customer-a",
scan_type="socket_tier1",
)
assert head_scan_id == "workspace-head"
mock_sdk_with_responses.fullscans.get.assert_called_once_with(
core.config.org_slug,
{
"repo": "test",
"workspace": "customer-a",
"branch": "main",
"sort": "created_at",
"direction": "desc",
"per_page": SCAN_LOOKUP_PAGE_SIZE,
"scan_type": "socket_tier1",
},
)
def test_get_head_scan_for_repo_scopes_scan_type_without_workspace(
core, mock_sdk_with_responses
):
"""Reachability and standard scans must not share one unscoped head pointer"""
mock_sdk_with_responses.fullscans.get.return_value = {
"results": [{"id": "standard-head"}],
"nextPage": None,
}
head_scan_id = core.get_head_scan_for_repo("test", scan_type="socket")
assert head_scan_id == "standard-head"
mock_sdk_with_responses.fullscans.get.assert_called_once_with(
core.config.org_slug,
{
"repo": "test",
"branch": "main",
"sort": "created_at",
"direction": "desc",
"per_page": SCAN_LOOKUP_PAGE_SIZE,
"scan_type": "socket",
},
)
def test_get_head_scan_for_repo_workspace_lookup_failure_raises(core, mock_sdk_with_responses):
"""A failed listing is not the same as an empty one and must not resolve to None"""
mock_sdk_with_responses.fullscans.get.return_value = {}
with pytest.raises(APIFailure):
core.get_head_scan_for_repo("test", workspace="customer-a")
def test_get_head_scan_for_repo_workspace_no_scans_yet(core, mock_sdk_with_responses):
"""An empty listing is a real answer: the workspace has no baseline yet"""
mock_sdk_with_responses.fullscans.get.return_value = {"results": [], "nextPage": None}
assert core.get_head_scan_for_repo("test", workspace="customer-a") is None
def test_get_head_scan_for_repo_skips_temporary_scans(core, mock_sdk_with_responses):
"""A leftover empty tmp scan must not be picked up as the baseline"""
mock_sdk_with_responses.fullscans.get.return_value = {
"results": [
{"id": "leftover-tmp-scan", "tmp": True},
{"id": "workspace-head", "tmp": False},
],
"nextPage": None,
}
assert core.get_head_scan_for_repo("test", workspace="customer-a") == "workspace-head"
def test_get_head_scan_for_repo_normalizes_enum_scan_type(core, mock_sdk_with_responses):
"""ScanType members must be sent as their value, not their repr-style name"""
mock_sdk_with_responses.fullscans.get.return_value = {
"results": [{"id": "workspace-head"}],
"nextPage": None,
}
core.get_head_scan_for_repo(
"test",
workspace="customer-a",
scan_type=ScanType.SOCKET_TIER1,
)
query_params = mock_sdk_with_responses.fullscans.get.call_args.args[1]
assert query_params["scan_type"] == "socket_tier1"
def test_get_full_scan_id_by_commit(core, mock_sdk_with_responses):
"""Looks up the newest full scan for a repo + commit via the list endpoint"""
mock_sdk_with_responses.fullscans.get.return_value = {
"results": [{"id": "base-scan-id", "commit_hash": "abc123"}],
"nextPage": None,
}
scan_id = core.get_full_scan_id_by_commit("test", "abc123")
assert scan_id == "base-scan-id"
mock_sdk_with_responses.fullscans.get.assert_called_once_with(
core.config.org_slug,
{
"repo": "test",
"commit_hash": "abc123",
"sort": "created_at",
"direction": "desc",
"per_page": SCAN_LOOKUP_PAGE_SIZE,
},
)
def test_get_full_scan_id_by_commit_scopes_to_workspace_and_scan_type(core, mock_sdk_with_responses):
"""Looks up a baseline scan from the same workspace and scan type as the new scan"""
mock_sdk_with_responses.fullscans.get.return_value = {
"results": [{"id": "workspace-reach-base", "commit_hash": "abc123"}],
"nextPage": None,
}
scan_id = core.get_full_scan_id_by_commit(
"test",
"abc123",
workspace="customer-a",
scan_type="socket_tier1",
)
assert scan_id == "workspace-reach-base"
mock_sdk_with_responses.fullscans.get.assert_called_once_with(
core.config.org_slug,
{
"repo": "test",
"commit_hash": "abc123",
"sort": "created_at",
"direction": "desc",
"per_page": SCAN_LOOKUP_PAGE_SIZE,
"workspace": "customer-a",
"scan_type": "socket_tier1",
},
)
def test_get_full_scan_id_by_commit_skips_temporary_scans(core, mock_sdk_with_responses):
"""A tmp scan carries the commit hash of the run that created it, so skip it too"""
mock_sdk_with_responses.fullscans.get.return_value = {
"results": [
{"id": "leftover-tmp-scan", "commit_hash": "abc123", "tmp": True},
{"id": "base-scan-id", "commit_hash": "abc123"},
],
"nextPage": None,
}
assert core.get_full_scan_id_by_commit("test", "abc123") == "base-scan-id"
def test_get_full_scan_id_by_commit_not_found(core, mock_sdk_with_responses):
"""A successful empty listing means the commit has no scan"""
mock_sdk_with_responses.fullscans.get.return_value = {"results": [], "nextPage": None}
assert core.get_full_scan_id_by_commit("test", "abc123") is None
def test_get_full_scan_id_by_commit_lookup_failure_raises(core, mock_sdk_with_responses):
"""An SDK error dict must not trigger fallback to an older ancestor"""
mock_sdk_with_responses.fullscans.get.return_value = {}
with pytest.raises(APIFailure):
core.get_full_scan_id_by_commit("test", "abc123")
def test_resolve_base_full_scan_id_defaults_to_head_scan(core):
"""Without base overrides the matching scan type's head scan is the baseline"""
core.sdk.fullscans.get.return_value = {
"results": [{"id": "standard-head"}],
"nextPage": None,
}
assert core.resolve_base_full_scan_id(make_full_scan_params()) == "standard-head"
def test_resolve_base_full_scan_id_scopes_head_to_workspace(core):
core.sdk.fullscans.get.return_value = {
"results": [{"id": "workspace-head"}],
"nextPage": None,
}
params = make_full_scan_params(workspace="customer-a", scan_type="socket_tier1")
assert core.resolve_base_full_scan_id(params) == "workspace-head"
core.sdk.fullscans.get.assert_called_once_with(
core.config.org_slug,
{
"repo": "test",
"workspace": "customer-a",
"branch": "main",
"sort": "created_at",
"direction": "desc",
"per_page": SCAN_LOOKUP_PAGE_SIZE,
"scan_type": "socket_tier1",
},
)
def test_resolve_base_full_scan_id_workspace_lookup_failure_exits(core):
"""A failed workspace lookup fails the run instead of diffing against an empty scan"""
core.cli_config = make_cli_config()
core.sdk.fullscans.get.return_value = {}
params = make_full_scan_params(workspace="customer-a")
with pytest.raises(SystemExit) as exc_info:
core.resolve_base_full_scan_id(params)
assert exc_info.value.code == core.cli_config.exit_code_on_api_error
def test_resolve_base_full_scan_id_workspace_lookup_failure_disable_blocking(core):
"""--disable-blocking keeps the failed lookup from failing the build"""
core.cli_config = make_cli_config("--disable-blocking")
core.sdk.fullscans.get.return_value = {}
params = make_full_scan_params(workspace="customer-a")
with pytest.raises(SystemExit) as exc_info:
core.resolve_base_full_scan_id(params)
assert exc_info.value.code == 0
def test_resolve_base_full_scan_id_workspace_lookup_failure_without_cli_config(core):
"""Library callers with no CliConfig see the APIFailure rather than a process exit"""
core.cli_config = None
core.sdk.fullscans.get.return_value = {}
params = make_full_scan_params(workspace="customer-a")
with pytest.raises(APIFailure):
core.resolve_base_full_scan_id(params)
def test_resolve_base_full_scan_id_uses_base_scan_id(core):
"""--base-scan-id is used verbatim, without touching the repo endpoint"""
core.cli_config = make_cli_config("--base-scan-id", "explicit-base")
assert core.resolve_base_full_scan_id(make_full_scan_params()) == "explicit-base"
core.sdk.repos.repo.assert_not_called()
def test_resolve_base_full_scan_id_uses_base_commit_sha(core):
"""--base-commit-sha resolves through the full-scans list endpoint"""
core.cli_config = make_cli_config("--base-commit-sha", "abc123")
core.sdk.fullscans.get.return_value = {
"results": [{"id": "merge-base-scan"}],
"nextPage": None,
}
params = make_full_scan_params(workspace="customer-a", scan_type="socket_tier1")
assert core.resolve_base_full_scan_id(params) == "merge-base-scan"
core.sdk.repos.repo.assert_not_called()
core.sdk.fullscans.get.assert_called_once_with(
core.config.org_slug,
{
"repo": "test",
"commit_hash": "abc123",
"sort": "created_at",
"direction": "desc",
"per_page": SCAN_LOOKUP_PAGE_SIZE,
"workspace": "customer-a",
"scan_type": "socket_tier1",
},
)
def test_resolve_base_full_scan_id_falls_back_to_scanned_ancestor(core, monkeypatch):
"""An unscanned merge base degrades to the nearest scanned ancestor"""
core.cli_config = make_cli_config("--base-commit-sha", "unscanned-sha")
core.sdk.fullscans.get.side_effect = [
{"results": [], "nextPage": None}, # exact commit
{"results": [ # recent scans
{"id": "tmp-scan", "commit_hash": "ancestor-1", "tmp": True},
{"id": "ancestor-scan", "commit_hash": "ancestor-2"},
], "nextPage": None},
]
monkeypatch.setattr(
Core, "first_parent_commits",
lambda self, sha, depth: ["unscanned-sha", "ancestor-1", "ancestor-2"],
)
params = make_full_scan_params()
assert core.resolve_base_full_scan_id(params) == "ancestor-scan"
def test_find_baseline_scan_for_ancestor_paginates_and_selects_nearest(
core, monkeypatch
):
"""Reruns can fill page one while a closer scanned ancestor is on page two"""
first_page = [
{"id": "farther-scan", "commit_hash": "ancestor-2"},
*[
{"id": f"unrelated-{index}", "commit_hash": f"other-{index}"}
for index in range(ANCESTOR_SCAN_LOOKUP_LIMIT - 1)
],
]
core.sdk.fullscans.get.side_effect = [
{"results": first_page, "nextPage": 2},
{
"results": [{"id": "nearest-scan", "commit_hash": "ancestor-1"}],
"nextPage": 0,
},
]
monkeypatch.setattr(
Core,
"first_parent_commits",
lambda self, sha, depth: ["unscanned-sha", "ancestor-1", "ancestor-2"],
)
assert core.find_baseline_scan_for_ancestor(
"test",
"unscanned-sha",
scan_type="socket",
) == ("nearest-scan", "ancestor-1", 1)
assert core.sdk.fullscans.get.call_args_list[1].args[1]["page"] == 2
def test_resolve_base_full_scan_id_exact_lookup_failure_does_not_fallback(
core, monkeypatch
):
core.cli_config = make_cli_config("--base-commit-sha", "abc123")
core.sdk.fullscans.get.return_value = {}
fallback_calls = []
monkeypatch.setattr(
Core,
"find_baseline_scan_for_ancestor",
lambda *args, **kwargs: fallback_calls.append((args, kwargs)),
)
with pytest.raises(APIFailure):
core.resolve_base_full_scan_id(make_full_scan_params())
assert fallback_calls == []
def test_resolve_base_full_scan_id_ancestor_fallback_skips_temporary_scans(core, monkeypatch):
"""A tmp scan on an ancestor is not a usable baseline either"""
core.cli_config = make_cli_config("--base-commit-sha", "unscanned-sha")
core.sdk.fullscans.get.side_effect = [
{"results": [], "nextPage": None},
{"results": [{"id": "tmp-scan", "commit_hash": "ancestor-1", "tmp": True}], "nextPage": None},
]
monkeypatch.setattr(
Core, "first_parent_commits",
lambda self, sha, depth: ["unscanned-sha", "ancestor-1"],
)
with pytest.raises(SystemExit):
core.resolve_base_full_scan_id(make_full_scan_params())
def test_resolve_base_full_scan_id_ancestor_fallback_needs_local_history(core, monkeypatch):
"""Without local history there is nothing to match scans against"""
core.cli_config = make_cli_config("--base-commit-sha", "unscanned-sha")
core.sdk.fullscans.get.side_effect = [
{"results": [], "nextPage": None},
{"results": [{"id": "ancestor-scan", "commit_hash": "ancestor-2"}], "nextPage": None},
]
monkeypatch.setattr(Core, "first_parent_commits", lambda self, sha, depth: [])
with pytest.raises(SystemExit):
core.resolve_base_full_scan_id(make_full_scan_params())
def test_resolve_base_full_scan_id_commit_sha_not_found_exits(core):
"""A --base-commit-sha with no scan is a hard error (exit_code_on_api_error)"""
core.cli_config = make_cli_config("--base-commit-sha", "abc123")
core.sdk.fullscans.get.return_value = {"results": [], "nextPage": None}
with pytest.raises(SystemExit) as exc_info:
core.resolve_base_full_scan_id(make_full_scan_params())
assert exc_info.value.code == core.cli_config.exit_code_on_api_error
def test_resolve_base_full_scan_id_commit_sha_not_found_disable_blocking(core):
"""--disable-blocking keeps the missing-base error from failing the build"""
core.cli_config = make_cli_config("--base-commit-sha", "abc123", "--disable-blocking")
core.sdk.fullscans.get.return_value = {"results": [], "nextPage": None}
with pytest.raises(SystemExit) as exc_info:
core.resolve_base_full_scan_id(make_full_scan_params())
assert exc_info.value.code == 0
def test_get_full_scan(core, mock_sdk_with_responses, head_scan_metadata, head_scan_stream):
"""Test getting an existing full scan"""
full_scan = core.get_full_scan("head")
# Assert SDK methods called correctly
mock_sdk_with_responses.fullscans.metadata.assert_called_once_with(
core.config.org_slug,
"head",
use_types=True,
)
mock_sdk_with_responses.fullscans.stream.assert_called_once_with(
core.config.org_slug,
"head",
use_types=True,
)
# Assert response processed correctly
assert full_scan.id == head_scan_metadata["data"]["id"]
assert len(full_scan.sbom_artifacts) == len(head_scan_stream.artifacts)
assert len(full_scan.packages) == len(head_scan_stream.artifacts)
assert full_scan.packages["dp1"].transitives == 2
def test_create_full_scan(core, mock_sdk_with_responses, new_scan_metadata):
"""Test creating a new full scan"""
# Setup test data
files = ["requirements.txt"]
params = FullScanParams(
repo="test-repo",
branch="main",
commit_hash="abc123",
)
# Create the full scan
full_scan = core.create_full_scan(files, params)
# Verify the response
assert full_scan.id == new_scan_metadata["data"]["id"]
mock_sdk_with_responses.fullscans.post.assert_called_once_with(
files,
params,
use_types=True,
use_lazy_loading=True,
max_open_files=50,
base_paths=None,
)
def test_get_added_and_removed_packages(core):
"""Test getting added and removed packages between two scans"""
# Get two different scans to compare
added, removed, all_packages = core.get_added_and_removed_packages("head", "new")
# Verify SDK was called correctly: the comparison goes through the diff-scans
# endpoints (create + poll) rather than the legacy streaming diff, so no
# connection is left idle while the backend computes.
create_args = core.sdk.diffscans.create_from_ids.call_args
assert create_args[0][0] == core.config.org_slug
create_params = create_args[0][1]
assert create_params["before"] == "head"
assert create_params["after"] == "new"
assert "on_duplicate" not in create_params
# cached=true is the polling contract (202 while computing, 200 when ready).
# No omit_license_details param: the API ignores it for cached reads (cached
# results always embed license details), so sending it would only suggest a
# leanness guarantee this path doesn't have.
core.sdk.diffscans.get.assert_called_once_with(
core.config.org_slug,
"diff-scan-123",
params={"cached": "true"},
)
core.sdk.fullscans.stream_diff.assert_not_called()
# Verify the results
# Added packages
assert len(added) > 0 # We should have some added packages
assert "dp3" in added # Verify specific package we know was added
assert "dp4" in added
# Removed packages
assert len(removed) > 0 # We should have some removed packages
assert "dp2" in removed # Verify specific package we know was removed
assert "dp2_t1" in removed # Verify transitive dependencies are also tracked
assert "pypi/direct_package_1@1.6.0" in all_packages # Unchanged package is in full package map
def test_get_added_and_removed_packages_license_override(core):
"""include_license_details only governs the legacy fallback path now: the
diff-scans path always receives embedded license details (the API ignores
omit_license_details for cached reads), so the seam must survive through to
the stream_diff call when the primary path is unavailable."""
from socketdev.exceptions import APIFailure
core.sdk.diffscans.create_from_ids.side_effect = APIFailure("forbidden", status_code=403)
core.get_added_and_removed_packages("head", "new", include_license_details=True)
core.sdk.fullscans.stream_diff.assert_called_once_with(
core.config.org_slug,
"head",
"new",
use_types=True,
include_license_details="true",
)
def test_get_sbom_data_failure_raises(core):
"""A failed SBOM stream fetch raises instead of returning {}.
Returning {} let report generation continue and emit empty results with
exit code 0; raising routes the failure through the CLI's API-error
handling instead.
"""
core.sdk.fullscans.stream.side_effect = None
core.sdk.fullscans.stream.return_value = FullScanStreamResponse.from_dict({
"success": False,
"status": 200,
"message": "Error parsing stream response",
})
with pytest.raises(APIFailure, match="Failed to get SBOM data"):
core.get_sbom_data("head")
def test_empty_alerts_preserved(core):
"""Test that empty alerts arrays stay as empty arrays and don't become None"""
# Get the scan that contains dp2 (which has empty alerts array)
head_scan = core.get_full_scan("head")
# Check the raw artifact first
artifacts = core.get_sbom_data("head")
assert artifacts["dp2"].alerts == [] # Should be empty list, not None
# Check the final package
assert head_scan.packages["dp2"].alerts == [] # Should still be empty list
def test_repository_head_baseline_log(core, caplog):
core.sdk.fullscans.get.return_value = {
"results": [{"id": "standard-head"}],
"nextPage": None,
}
with caplog.at_level("INFO", logger="socketdev"):
assert core.resolve_base_full_scan_id(make_full_scan_params()) == "standard-head"
assert (
'Baseline selected: source=repository-head scan_id="standard-head"'
in caplog.messages
)
def test_explicit_scan_baseline_log(core, caplog):
core.cli_config = make_cli_config("--base-scan-id", "explicit-base")
with caplog.at_level("INFO", logger="socketdev"):
assert core.resolve_base_full_scan_id(make_full_scan_params()) == "explicit-base"
assert 'Baseline selected: source=explicit-scan scan_id="explicit-base"' in caplog.messages
def test_explicit_commit_baseline_log(core, caplog):
core.cli_config = make_cli_config("--base-commit-sha", "abc123")
core.sdk.fullscans.get.return_value = {
"results": [{"id": "merge-base-scan"}],
"nextPage": None,
}
with caplog.at_level("INFO", logger="socketdev"):
assert core.resolve_base_full_scan_id(make_full_scan_params()) == "merge-base-scan"
assert (
'Baseline selected: source=explicit-commit scan_id="merge-base-scan" '
'commit="abc123"'
) in caplog.messages