-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtest_cli.py
More file actions
1601 lines (1281 loc) · 55.9 KB
/
test_cli.py
File metadata and controls
1601 lines (1281 loc) · 55.9 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
import json
import os
import re
from unittest.mock import patch
import pytest
from click.testing import CliRunner
from modelaudit import __version__
from modelaudit.cli import cli, expand_paths, format_text_output
from modelaudit.core import scan_model_directory_or_file
from modelaudit.models import create_initial_audit_result
def strip_ansi(text):
"""Strip ANSI color codes from text for testing."""
return re.sub(r"\x1b\[[0-9;]*m", "", text)
def create_mock_scan_result(**kwargs):
"""Create a mock ModelAuditResultModel for testing."""
result = create_initial_audit_result()
# Set default values
result.bytes_scanned = kwargs.get("bytes_scanned", 1024)
result.files_scanned = kwargs.get("files_scanned", 1)
result.has_errors = kwargs.get("has_errors", False)
result.success = kwargs.get("success", True)
# Add issues if provided
if "issues" in kwargs:
import time
from modelaudit.scanners.base import Issue
issues = []
for issue_dict in kwargs["issues"]:
issue = Issue(
message=issue_dict.get("message", "Test issue"),
severity=issue_dict.get("severity", "warning"),
location=issue_dict.get("location"),
timestamp=time.time(),
details=issue_dict.get("details", {}),
why=None,
type=None,
)
issues.append(issue)
result.issues = issues
# Add assets if provided
if "assets" in kwargs:
from modelaudit.models import AssetModel
assets = []
for asset_dict in kwargs["assets"]:
asset = AssetModel(
path=asset_dict.get("path", "/test/path"),
type=asset_dict.get("type", "test"),
size=asset_dict.get("size", 0),
tensors=asset_dict.get("tensors"),
keys=asset_dict.get("keys"),
contents=asset_dict.get("contents"),
)
assets.append(asset)
result.assets = assets
# Add scanners if provided
if "scanners" in kwargs:
result.scanner_names = kwargs["scanners"]
# Add file metadata if provided
if "file_metadata" in kwargs:
from modelaudit.models import FileMetadataModel
result.file_metadata = {
path: metadata if isinstance(metadata, FileMetadataModel) else FileMetadataModel(**metadata)
for path, metadata in kwargs["file_metadata"].items()
}
result.finalize_statistics()
return result
def test_cli_help():
"""Test the CLI help command."""
runner = CliRunner()
result = runner.invoke(cli, ["--help"])
assert result.exit_code == 0
assert "Usage:" in result.output
assert "scan" in result.output # Should list the scan command
def test_cli_version():
"""Test the CLI version command."""
runner = CliRunner()
result = runner.invoke(cli, ["--version"])
assert result.exit_code == 0
assert __version__ in result.output
def test_scan_command_help():
"""Test the scan command help."""
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--help"])
assert result.exit_code == 0
assert "Usage:" in result.output
assert "--blacklist" in result.output
assert "--format" in result.output
assert "--output" in result.output
assert "--timeout" in result.output
assert "--verbose" in result.output
assert "--max-size" in result.output # Updated from --max-file-size
assert "--strict" in result.output # New consolidated flag
assert "--dry-run" in result.output # New flag
assert "Defaults:" in result.output or "Automatic defaults:" in result.output
def test_scan_invalid_severity_level_option(tmp_path):
"""Invalid severity override values should fail fast."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file), "--severity", "S101=SEVERE"])
assert result.exit_code == 2
assert "Invalid severity level" in result.output
assert "CRITICAL" in result.output
def test_scan_unknown_rule_code_in_severity_option(tmp_path):
"""Unknown rule codes in --severity should fail fast."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file), "--severity", "S9999=CRITICAL"])
assert result.exit_code == 2
assert "Unknown rule code" in result.output
assert "S9999" in result.output
def test_scan_unknown_rule_code_in_suppress_option(tmp_path):
"""Unknown rule codes in --suppress should fail fast."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file), "--suppress", "S9999"])
assert result.exit_code == 2
assert "Unknown rule code" in result.output
assert "S9999" in result.output
def test_scan_nonexistent_file():
"""Test scanning a nonexistent file."""
runner = CliRunner()
result = runner.invoke(cli, ["scan", "nonexistent_file.pkl"])
# The CLI might exit with a non-zero code for errors
# But it should mention the error in the output
assert "Error" in result.output
assert "not exist" in result.output.lower() or "not found" in result.output.lower()
def test_scan_file(tmp_path):
"""Test scanning a file."""
# Create a test file
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file)], catch_exceptions=True)
# Just check that the command ran and produced some output
assert result.output # Should have some output
# With automatic defaults, non-model files may be skipped or shown differently
# Just check that it completed successfully
assert result.exit_code == 0
def test_scan_directory(tmp_path):
"""Test scanning a directory."""
# Create a test directory with files
test_dir = tmp_path / "test_dir"
test_dir.mkdir()
(test_dir / "file1.pkl").write_bytes(b"test content 1")
(test_dir / "file2.bin").write_bytes(b"test content 2")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_dir)], catch_exceptions=True)
# Just check that the command ran and produced some output
assert result.output # Should have some output
# Verify that the scan produced results (works with both text and JSON formats)
assert (
"Files:" in result.output
or "Size:" in result.output
or "bytes_scanned" in result.output
or "files_scanned" in result.output
)
def test_scan_multiple_paths(tmp_path):
"""Test scanning multiple paths."""
# Create test files
file1 = tmp_path / "file1.dat"
file1.write_bytes(b"test content 1")
file2 = tmp_path / "file2.dat"
file2.write_bytes(b"test content 2")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(file1), str(file2)], catch_exceptions=True)
# Just check that the command ran and produced some output
assert result.output # Should have some output
# Verify that the scan produced results (works with both text and JSON formats)
assert (
"Files:" in result.output
or "Size:" in result.output
or "bytes_scanned" in result.output
or "files_scanned" in result.output
)
def test_scan_with_blacklist(tmp_path):
"""Test scanning with blacklist patterns."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
result = runner.invoke(
cli,
["scan", str(test_file), "--blacklist", "pattern1", "--blacklist", "pattern2"],
catch_exceptions=True,
)
# Just check that the command ran and produced some output
assert result.output # Should have some output
assert result.exit_code == 0 # Command should complete successfully
# With automatic defaults, the specific output format may vary
def test_scan_json_output(tmp_path):
"""Test scanning with JSON output format."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file), "--format", "json"])
# For JSON output, we should be able to parse the output as JSON
# regardless of the exit code
try:
output_json = json.loads(result.output)
assert "files_scanned" in output_json
assert "issues" in output_json
assert output_json["files_scanned"] == 1
except json.JSONDecodeError:
pytest.fail("Output is not valid JSON")
def test_scan_output_file(tmp_path):
"""Test scanning with output to a file."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
output_file = tmp_path / "output.txt"
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file), "--output", str(output_file)])
# The file should be created regardless of the exit code
assert output_file.exists()
assert output_file.read_text() # Should not be empty
assert f"Results written to {output_file}" in result.output
def test_scan_json_output_to_file(tmp_path):
"""Test scanning with JSON output to a file - JSON should be valid and not mixed with progress."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
output_file = tmp_path / "output.json"
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file), "--format", "json", "--output", str(output_file)])
# The file should be created
assert output_file.exists()
# JSON in file should be valid and parseable
try:
output_json = json.loads(output_file.read_text())
assert "files_scanned" in output_json
assert "issues" in output_json
assert output_json["files_scanned"] == 1
except json.JSONDecodeError:
pytest.fail("JSON output file is not valid JSON")
# Stdout should contain confirmation message (and potentially progress output)
assert f"Results written to {output_file}" in result.output
def test_scan_json_to_stdout_no_progress_interference(tmp_path):
"""Test that JSON to stdout remains valid (no progress output mixed in)."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
result = runner.invoke(cli, ["scan", str(test_file), "--format", "json"])
# Output should be valid JSON when going to stdout (no progress interference)
try:
output_json = json.loads(result.output)
assert "files_scanned" in output_json
assert "issues" in output_json
except json.JSONDecodeError:
pytest.fail("JSON output to stdout is not valid JSON - may be corrupted by progress")
def test_scan_sbom_output(tmp_path):
"""Test scanning with SBOM output."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
sbom_file = tmp_path / "sbom.json"
runner = CliRunner()
runner.invoke(cli, ["scan", str(test_file), "--sbom", str(sbom_file)])
assert sbom_file.exists()
try:
json.loads(sbom_file.read_text())
except json.JSONDecodeError:
pytest.fail("SBOM output is not valid JSON")
def test_scan_output_utf8_locale(tmp_path):
"""Ensure output file is valid UTF-8 even with ASCII locale."""
test_file = tmp_path / "utf8_test.dat"
test_file.write_bytes(b"test content")
output_file = tmp_path / "output.txt"
runner = CliRunner()
env = os.environ.copy()
env.update({"LC_ALL": "C", "LANG": "C"})
runner.invoke(cli, ["scan", str(test_file), "--output", str(output_file)], env=env)
assert output_file.exists()
try:
output_file.read_bytes().decode("utf-8")
except UnicodeDecodeError:
pytest.fail("Output file is not valid UTF-8")
def test_scan_sbom_utf8_locale(tmp_path):
"""Ensure SBOM file is valid UTF-8 even with ASCII locale."""
test_file = tmp_path / "utf8_test.dat"
test_file.write_bytes(b"test content")
sbom_file = tmp_path / "sbom.json"
runner = CliRunner()
env = os.environ.copy()
env.update({"LC_ALL": "C", "LANG": "C"})
runner.invoke(cli, ["scan", str(test_file), "--sbom", str(sbom_file)], env=env)
assert sbom_file.exists()
try:
sbom_file.read_bytes().decode("utf-8")
except UnicodeDecodeError:
pytest.fail("SBOM file is not valid UTF-8")
def test_scan_verbose_mode(tmp_path):
"""Test scanning in verbose mode."""
test_file = tmp_path / "test_file.dat"
test_file.write_bytes(b"test content")
runner = CliRunner()
# Use catch_exceptions=True to handle any errors in the CLI
result = runner.invoke(
cli,
["scan", str(test_file), "--verbose"],
catch_exceptions=True,
)
# In verbose mode, we should see more output
# With automatic defaults and new output format, check for successful completion
assert result.output # Should have some output
assert result.exit_code == 0 # Should complete successfully
# New output format may not contain "Scanning" text
def test_scan_max_file_size(tmp_path):
"""Test scanning with max file size limit."""
# Create a file larger than our limit
test_file = tmp_path / "large_file.dat"
test_file.write_bytes(b"x" * 1000) # 1000 bytes
runner = CliRunner()
result = runner.invoke(
cli,
[
"scan",
str(test_file),
"--max-size",
"500", # 500 bytes limit
],
catch_exceptions=True,
)
# Just check that the command ran and produced some output
assert result.output # Should have some output
# Note: JSON output format doesn't include file paths
assert "500" in result.output or "File too large" in result.output # Should mention the max file size or error
def test_format_text_output():
"""Test the format_text_output function."""
# Create a sample results dictionary
results = {
"path": "/path/to/model",
"files_scanned": 5,
"bytes_scanned": 1024,
"duration": 0.5,
"issues": [
{
"message": "Test issue",
"severity": "warning",
"location": "test.pkl",
"details": {"test": "value"},
},
],
"has_errors": False,
}
# Test normal output
output = format_text_output(results, verbose=False)
clean_output = strip_ansi(output)
assert "Files:" in clean_output and "5" in clean_output
assert "Test issue" in clean_output
assert "warning" in clean_output.lower()
# Test verbose output
output = format_text_output(results, verbose=True)
clean_output = strip_ansi(output)
assert "Files:" in clean_output and "5" in clean_output
assert "Test issue" in clean_output
assert "warning" in clean_output.lower()
# Verbose might include details, but we can't guarantee it
def test_format_text_output_only_debug_issues():
"""Ensure debug-only issues result in a success status."""
results = {
"files_scanned": 1,
"bytes_scanned": 10,
"duration": 0.1,
"issues": [
{"message": "Debug info", "severity": "debug", "location": "file.pkl"},
],
"has_errors": False,
}
output = format_text_output(results, verbose=False)
clean_output = strip_ansi(output)
assert "No security issues detected" in clean_output
assert "NO ISSUES FOUND" in clean_output
def test_format_text_output_operational_errors_status():
"""Ensure operational errors are surfaced in final text status."""
results = {
"files_scanned": 1,
"bytes_scanned": 10,
"duration": 0.1,
"issues": [],
"has_errors": True,
}
output = format_text_output(results, verbose=False)
clean_output = strip_ansi(output)
assert "SCAN COMPLETED WITH OPERATIONAL ERRORS" in clean_output
assert "NO ISSUES FOUND" not in clean_output
def test_format_text_output_only_info_issues():
"""Ensure info-only issues result in a success status."""
results = {
"files_scanned": 1,
"bytes_scanned": 10,
"duration": 0.1,
"issues": [
{"message": "Info message", "severity": "info", "location": "file.pkl"},
],
"has_errors": False,
}
output = format_text_output(results, verbose=False)
clean_output = strip_ansi(output)
assert "1 Info" in clean_output
assert "INFORMATIONAL FINDINGS" in clean_output # Info issues show INFORMATIONAL FINDINGS
assert "WARNINGS DETECTED" not in clean_output
def test_format_text_output_debug_and_info_issues():
"""Ensure debug and info issues (no warnings) result in a success status."""
results = {
"files_scanned": 1,
"bytes_scanned": 10,
"duration": 0.1,
"issues": [
{"message": "Debug info", "severity": "debug", "location": "file1.pkl"},
{"message": "Info message", "severity": "info", "location": "file2.pkl"},
],
"has_errors": False,
}
output = format_text_output(results, verbose=True)
clean_output = strip_ansi(output)
assert "1 Info" in clean_output
assert "1 Debug" in clean_output
assert "INFORMATIONAL FINDINGS" in clean_output # Info issues show INFORMATIONAL FINDINGS
assert "WARNINGS DETECTED" not in clean_output
def test_format_text_output_fast_scan_duration():
"""Test duration formatting for very fast scans (< 0.01 seconds)."""
results = {
"path": "/path/to/model",
"files_scanned": 1,
"bytes_scanned": 512,
"duration": 0.005, # Very fast scan < 0.01 seconds
"issues": [],
"has_errors": False,
}
output = format_text_output(results, verbose=False)
clean_output = strip_ansi(output)
# Should show 3 decimal places for very fast scans
assert "Duration:" in clean_output and "0.005s" in clean_output
assert "Files:" in clean_output and "1" in clean_output
assert "No security issues detected" in clean_output
def test_scan_huggingface_url_help():
"""Test that HuggingFace URL examples are in the help text."""
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--help"])
assert result.exit_code == 0
assert "hf://user/llama" in result.output # Updated to new example format
assert "s3://bucket/models/" in result.output
assert "models:/model/v1" in result.output
def test_scan_jfrog_url_help():
"""Test that JFrog authentication is mentioned in the help text."""
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--help"])
assert result.exit_code == 0
assert "JFROG_API_TOKEN" in result.output # Updated to check for auth info instead of URL example
def test_scan_mlflow_url_help():
"""Test that MLflow URL examples are in the help text."""
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--help"])
assert result.exit_code == 0
assert "models:/model/v1" in result.output # Updated to match new example format
assert "MLFLOW_TRACKING_URI" in result.output # Check for auth info
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.cli.download_model")
@patch("modelaudit.cli.scan_model_directory_or_file")
@patch("shutil.rmtree")
def test_scan_huggingface_url_success(mock_rmtree, mock_scan, mock_download, mock_is_hf_url, tmp_path):
"""Test successful scanning of a HuggingFace URL."""
# Setup mocks
mock_is_hf_url.return_value = True
# Create a real temp directory for the test
test_model_dir = tmp_path / "test_model"
test_model_dir.mkdir()
# Create a dummy file inside to make it look like a real model
(test_model_dir / "model.bin").write_text("dummy model")
mock_download.return_value = test_model_dir
mock_scan.return_value = create_mock_scan_result(
bytes_scanned=1024, issues=[], files_scanned=1, assets=[], has_errors=False, scanners=["test_scanner"]
)
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--no-cache", "--format", "text", "https://huggingface.co/test/model"])
# Should succeed
assert result.exit_code == 0
# With automatic defaults and new output format, check for successful completion
assert (
"SCAN SUMMARY" in result.output
or "Files:" in result.output
or "Duration:" in result.output
or "Clean" in result.output
or "Downloaded" in result.output
)
# Verify download was called
mock_download.assert_called_once()
# Verify scan was called with downloaded path
mock_scan.assert_called_once()
call_args = mock_scan.call_args
assert call_args[0][0] == str(test_model_dir)
# Verify cleanup was attempted (only when not using cache)
mock_rmtree.assert_called()
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.cli.download_model")
def test_scan_huggingface_url_download_failure(mock_download, mock_is_hf_url):
"""Test handling of download failure for HuggingFace URL."""
# Setup mocks
mock_is_hf_url.return_value = True
mock_download.side_effect = Exception("Download failed")
runner = CliRunner()
result = runner.invoke(cli, ["scan", "https://huggingface.co/test/model"])
# Should fail with error code 2
assert result.exit_code == 2
assert "Error processing model" in result.output or "Error downloading model" in result.output
assert "Download failed" in result.output
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.cli.download_model")
@patch("modelaudit.cli.scan_model_directory_or_file")
@patch("shutil.rmtree")
def test_scan_huggingface_url_with_issues(mock_rmtree, mock_scan, mock_download, mock_is_hf_url, tmp_path):
"""Test scanning a HuggingFace URL that has security issues."""
# Setup mocks
mock_is_hf_url.return_value = True
# Create a real temp directory for the test
test_model_dir = tmp_path / "test_model"
test_model_dir.mkdir()
# Create a dummy file inside to make it look like a real model
(test_model_dir / "model.pkl").write_text("dummy model")
mock_download.return_value = test_model_dir
mock_scan.return_value = create_mock_scan_result(
bytes_scanned=2048,
issues=[
{
"message": "Dangerous import detected",
"severity": "critical",
"location": "model.pkl",
}
],
files_scanned=1,
assets=[],
has_errors=False,
scanners=["pickle_scanner"],
)
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--format", "text", "--no-cache", "hf://test/malicious-model"])
# Should exit with code 1 (security issues found)
assert result.exit_code == 1
assert (
"Downloaded" in result.output
or "issue" in result.output.lower()
or "Downloaded successfully" in result.output
or "Downloading from" in result.output
)
# Verify cleanup was still attempted
mock_rmtree.assert_called()
@patch("modelaudit.cli.scan_model_directory_or_file")
def test_scan_mixed_paths_and_urls(mock_scan):
"""Test scanning both local paths and HuggingFace URLs in one command."""
runner = CliRunner()
with patch("modelaudit.cli.is_huggingface_url") as mock_is_hf, patch("os.path.exists") as mock_exists:
# Setup mocks - first arg is local path, second is URL
mock_is_hf.side_effect = [False, True]
mock_exists.return_value = False # Local path doesn't exist
result = runner.invoke(cli, ["scan", "/local/path/model.pkl", "https://huggingface.co/test/model"])
# Should report error for missing local file
assert "Path does not exist: /local/path/model.pkl" in result.output
@patch("modelaudit.cli.is_pytorch_hub_url")
@patch("modelaudit.cli.download_pytorch_hub_model")
@patch("modelaudit.cli.scan_model_directory_or_file")
@patch("shutil.rmtree")
def test_scan_pytorchhub_url_success(mock_rmtree, mock_scan, mock_download, mock_is_ph_url, tmp_path):
"""Test scanning a PyTorch Hub URL successfully."""
mock_is_ph_url.return_value = True
test_dir = tmp_path / "hub"
test_dir.mkdir()
(test_dir / "model.pt").write_text("dummy")
mock_download.return_value = test_dir
mock_scan.return_value = create_mock_scan_result(
bytes_scanned=1, issues=[], files_scanned=1, assets=[], has_errors=False, scanners=["test"]
)
runner = CliRunner()
result = runner.invoke(cli, ["scan", "https://pytorch.org/hub/pytorch_vision_resnet/"])
assert result.exit_code == 0
mock_download.assert_called_once()
mock_scan.assert_called_once()
# With automatic defaults, PyTorch Hub URLs enable caching by default, so no cleanup
mock_rmtree.assert_not_called()
@patch("modelaudit.cli.is_pytorch_hub_url")
@patch("modelaudit.cli.download_pytorch_hub_model")
def test_scan_pytorchhub_url_download_failure(mock_download, mock_is_ph_url):
"""Test download failure for PyTorch Hub URL."""
mock_is_ph_url.return_value = True
mock_download.side_effect = Exception("boom")
runner = CliRunner()
result = runner.invoke(cli, ["scan", "https://pytorch.org/hub/pytorch_vision_resnet/"])
assert result.exit_code == 2
assert "Error downloading model" in result.output
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.utils.sources.huggingface.download_model_streaming")
@patch("modelaudit.core.scan_model_streaming")
def test_scan_huggingface_streaming_success(mock_scan_streaming, mock_download_streaming, mock_is_hf_url, tmp_path):
"""Test streaming scan with --stream flag."""
# Setup mocks
mock_is_hf_url.return_value = True
# Create temporary files for streaming
test_files = []
for i in range(3):
test_file = tmp_path / f"model_shard_{i}.bin"
test_file.write_text(f"dummy content {i}")
test_files.append(test_file)
# Mock file generator
def file_generator():
for i, f in enumerate(test_files):
yield (f, i == len(test_files) - 1)
mock_download_streaming.return_value = file_generator()
# Mock streaming scan result with content_hash
mock_result = create_mock_scan_result(bytes_scanned=300, files_scanned=3, has_errors=False)
mock_result.content_hash = "a" * 64 # Mock SHA256 hash
mock_scan_streaming.return_value = mock_result
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--stream", "--format", "json", "https://huggingface.co/test/streaming-model"])
# Should succeed
assert result.exit_code == 0
# Verify streaming functions were called
mock_download_streaming.assert_called_once()
mock_scan_streaming.assert_called_once()
# Verify content_hash is in JSON output
try:
output_json = json.loads(result.output)
assert "content_hash" in output_json
assert output_json["content_hash"] == "a" * 64
assert output_json["files_scanned"] == 3
except json.JSONDecodeError:
pytest.fail("Output is not valid JSON")
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.utils.sources.huggingface.download_model_streaming")
@patch("modelaudit.core.scan_model_streaming")
def test_scan_huggingface_streaming_sbom_includes_streamed_assets(
mock_scan_streaming, mock_download_streaming, mock_is_hf_url, tmp_path
):
"""Streaming scans should build SBOM components from discovered artifacts."""
mock_is_hf_url.return_value = True
streamed_files = []
file_hashes = {}
file_sizes = {}
for name in ("config.json", "model.safetensors", "tokenizer.json"):
file_path = tmp_path / name
content = f"streamed content for {name}".encode()
file_path.write_bytes(content)
streamed_files.append(file_path)
import hashlib
file_hashes[str(file_path)] = hashlib.sha256(content).hexdigest()
file_sizes[str(file_path)] = len(content)
def file_generator():
for index, file_path in enumerate(streamed_files):
yield (file_path, index == len(streamed_files) - 1)
mock_download_streaming.return_value = file_generator()
mock_result = create_mock_scan_result(
bytes_scanned=sum(file_path.stat().st_size for file_path in streamed_files),
files_scanned=len(streamed_files),
has_errors=False,
assets=[
{
"path": str(file_path),
"type": "streamed",
"size": file_sizes[str(file_path)],
}
for file_path in streamed_files
],
file_metadata={
str(file_path): {
"file_size": file_sizes[str(file_path)],
"file_hashes": {"sha256": file_hashes[str(file_path)]},
}
for file_path in streamed_files
},
)
mock_scan_streaming.return_value = mock_result
for file_path in streamed_files:
file_path.unlink()
sbom_file = tmp_path / "streamed.sbom.json"
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--stream", "--quiet", "--sbom", str(sbom_file), "hf://test/model"])
assert result.exit_code == 0
assert sbom_file.exists()
sbom_data = json.loads(sbom_file.read_text())
components = {component["name"]: component for component in sbom_data["components"]}
assert set(components) == {file_path.name for file_path in streamed_files}
assert "model" not in components
for file_path in streamed_files:
component = components[file_path.name]
properties = {prop["name"]: prop["value"] for prop in component["properties"]}
assert properties["size"] == str(file_sizes[str(file_path)])
assert component["hashes"][0]["alg"] == "SHA-256"
assert component["hashes"][0]["content"] == file_hashes[str(file_path)]
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.cli.is_huggingface_file_url", return_value=False)
@patch("modelaudit.cli.download_model")
@patch("modelaudit.cli.scan_model_directory_or_file")
def test_scan_huggingface_sbom_excludes_download_cache_files(
mock_scan, mock_download, mock_is_hf_file_url, mock_is_hf_url, tmp_path
):
"""Remote SBOM generation should ignore HuggingFace cache bookkeeping files."""
mock_is_hf_url.return_value = True
downloaded_dir = tmp_path / "gpt2"
downloaded_dir.mkdir()
real_files = {
downloaded_dir / "config.json": b'{"model_type":"gpt2"}',
downloaded_dir / "merges.txt": b"merge rules",
downloaded_dir / "model.safetensors": b"weights",
}
for file_path, content in real_files.items():
file_path.write_bytes(content)
cache_dir = downloaded_dir / ".cache" / "huggingface" / "download"
cache_dir.mkdir(parents=True)
(cache_dir / "config.json.metadata").write_text("{}")
(cache_dir / ".gitignore").write_text("*\n")
mock_download.return_value = downloaded_dir
mock_scan.return_value = create_mock_scan_result(
bytes_scanned=sum(len(content) for content in real_files.values()),
files_scanned=len(real_files),
has_errors=False,
assets=[
{
"path": str(file_path),
"type": "streamed",
"size": len(content),
}
for file_path, content in real_files.items()
],
)
sbom_file = tmp_path / "downloaded.sbom.json"
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--quiet", "--sbom", str(sbom_file), "hf://test/model"])
assert result.exit_code == 0
sbom_data = json.loads(sbom_file.read_text())
component_names = {component["name"] for component in sbom_data["components"]}
assert component_names == {file_path.name for file_path in real_files}
assert "config.json.metadata" not in component_names
assert ".gitignore" not in component_names
def test_scan_directory_skips_huggingface_cache_bookkeeping(tmp_path):
"""Directory scans should not surface HuggingFace cache bookkeeping files as assets."""
model_dir = tmp_path / "model"
model_dir.mkdir()
(model_dir / "config.json").write_text('{"model_type":"gpt2"}')
(model_dir / "model.safetensors").write_bytes(b"weights")
cache_dir = model_dir / ".cache" / "huggingface" / "download"
cache_dir.mkdir(parents=True)
(cache_dir / "config.json.metadata").write_text("{}")
(cache_dir / ".gitignore").write_text("*\n")
result = scan_model_directory_or_file(str(model_dir))
asset_names = {os.path.basename(asset.path) for asset in result.assets}
assert "config.json" in asset_names
assert "model.safetensors" in asset_names
assert "config.json.metadata" not in asset_names
assert ".gitignore" not in asset_names
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.utils.sources.huggingface.download_model_streaming")
@patch("modelaudit.core.scan_model_streaming")
def test_scan_huggingface_streaming_with_issues(mock_scan_streaming, mock_download_streaming, mock_is_hf_url, tmp_path):
"""Test streaming scan with security issues detected."""
mock_is_hf_url.return_value = True
# Mock file generator
test_file = tmp_path / "malicious.pkl"
test_file.write_text("malicious content")
def file_generator():
yield (test_file, True)
mock_download_streaming.return_value = file_generator()
# Mock scan result with issues
mock_result = create_mock_scan_result(
bytes_scanned=100,
files_scanned=1,
issues=[{"message": "Dangerous import detected", "severity": "critical", "location": "malicious.pkl"}],
has_errors=False,
)
mock_result.content_hash = "b" * 64
mock_scan_streaming.return_value = mock_result
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--stream", "hf://test/malicious-model"])
# Should exit with code 1 (security issues found)
assert result.exit_code == 1
# Verify streaming functions were called
mock_download_streaming.assert_called_once()
mock_scan_streaming.assert_called_once()
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.utils.sources.huggingface.download_model_streaming")
def test_scan_huggingface_streaming_download_failure(mock_download_streaming, mock_is_hf_url):
"""Test handling of download failure in streaming mode."""
mock_is_hf_url.return_value = True
mock_download_streaming.side_effect = Exception("Streaming download failed")
runner = CliRunner()
result = runner.invoke(cli, ["scan", "--stream", "https://huggingface.co/test/model"])
# Should fail with error code 2
assert result.exit_code == 2
assert "Error" in result.output
@patch("modelaudit.cli.is_huggingface_url")
@patch("modelaudit.utils.sources.huggingface.download_model_streaming")
@patch("modelaudit.core.scan_model_streaming")
def test_scan_huggingface_streaming_scan_errors(mock_scan_streaming, mock_download_streaming, mock_is_hf_url, tmp_path):
"""Test handling of scan errors during streaming."""
mock_is_hf_url.return_value = True
# Mock file generator
test_file = tmp_path / "test.bin"
test_file.write_text("test content")