tokmd-analysis 1.10.0

Analysis logic and enrichers for tokmd receipts.
Documentation
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
//! Wave-60 depth tests for analysis license module.
//!
//! Covers: BDD license detection across file types, SPDX parsing,
//! license-file detection, edge cases, property-based determinism tests.

use std::fs;
use std::path::PathBuf;

use crate::license::build_license_report;
use proptest::prelude::*;
use tempfile::tempdir;
use tokmd_analysis_types::AnalysisLimits;
use tokmd_analysis_types::LicenseSourceKind;

fn default_limits() -> AnalysisLimits {
    AnalysisLimits::default()
}

// ===========================================================================
// BDD: Cargo.toml metadata detection
// ===========================================================================

#[test]
fn given_cargo_toml_with_mit_or_apache_expression_then_spdx_is_verbatim() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = \"MIT OR Apache-2.0\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings.len(), 1);
    assert_eq!(report.findings[0].spdx, "MIT OR Apache-2.0");
    assert_eq!(report.findings[0].source_kind, LicenseSourceKind::Metadata);
    assert_eq!(report.effective.as_deref(), Some("MIT OR Apache-2.0"));
}

#[test]
fn given_cargo_toml_with_single_quoted_license_then_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = 'BSD-3-Clause'\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings.len(), 1);
    assert_eq!(report.findings[0].spdx, "BSD-3-Clause");
}

#[test]
fn given_cargo_toml_without_package_section_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[dependencies]\nserde = \"1.0\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

#[test]
fn given_cargo_toml_with_license_file_pointing_to_custom_path_then_text_scanned() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense-file = \"docs/MY-LICENSE.txt\"\n",
    )
    .unwrap();
    let docs = dir.path().join("docs");
    fs::create_dir_all(&docs).unwrap();
    fs::write(
        docs.join("MY-LICENSE.txt"),
        "Permission is hereby granted, free of charge, to any person.\n\
         The software is provided \"as is\".",
    )
    .unwrap();
    let files = vec![
        PathBuf::from("Cargo.toml"),
        PathBuf::from("docs/MY-LICENSE.txt"),
    ];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "MIT"
        && f.source_kind == LicenseSourceKind::Text
        && f.source_path.contains("MY-LICENSE")));
}

// ===========================================================================
// BDD: package.json detection
// ===========================================================================

#[test]
fn given_package_json_with_isc_then_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("package.json"),
        r#"{"name":"x","license":"ISC"}"#,
    )
    .unwrap();
    let files = vec![PathBuf::from("package.json")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings[0].spdx, "ISC");
}

#[test]
fn given_package_json_with_object_license_then_type_extracted() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("package.json"),
        r#"{"name":"x","license":{"type":"Artistic-2.0","url":"https://example.com"}}"#,
    )
    .unwrap();
    let files = vec![PathBuf::from("package.json")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings[0].spdx, "Artistic-2.0");
}

#[test]
fn given_package_json_without_license_field_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("package.json"),
        r#"{"name":"x","version":"1.0.0"}"#,
    )
    .unwrap();
    let files = vec![PathBuf::from("package.json")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

#[test]
fn given_package_json_with_null_license_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("package.json"),
        r#"{"name":"x","license":null}"#,
    )
    .unwrap();
    let files = vec![PathBuf::from("package.json")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

#[test]
fn given_package_json_with_license_array_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("package.json"),
        r#"{"name":"x","license":["MIT","Apache-2.0"]}"#,
    )
    .unwrap();
    let files = vec![PathBuf::from("package.json")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

// ===========================================================================
// BDD: pyproject.toml detection
// ===========================================================================

#[test]
fn given_pyproject_project_section_then_license_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("pyproject.toml"),
        "[project]\nname = \"pkg\"\nlicense = \"Apache-2.0\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("pyproject.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings[0].spdx, "Apache-2.0");
}

#[test]
fn given_pyproject_poetry_section_then_license_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("pyproject.toml"),
        "[tool.poetry]\nname = \"pkg\"\nlicense = \"LGPL-3.0\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("pyproject.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings[0].spdx, "LGPL-3.0");
}

#[test]
fn given_pyproject_with_both_sections_then_project_wins() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("pyproject.toml"),
        "[project]\nname = \"pkg\"\nlicense = \"MIT\"\n\n[tool.poetry]\nname = \"pkg\"\nlicense = \"GPL-2.0\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("pyproject.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    // project section is tried first; we expect MIT
    assert!(report.findings.iter().any(|f| f.spdx == "MIT"));
}

// ===========================================================================
// BDD: LICENSE text file detection across license families
// ===========================================================================

#[test]
fn given_mit_text_with_both_phrases_then_high_confidence() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Permission is hereby granted, free of charge, to any person obtaining a copy.\n\
         THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND.",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    let finding = report.findings.iter().find(|f| f.spdx == "MIT").unwrap();
    assert!(finding.confidence > 0.9);
}

#[test]
fn given_apache_text_then_apache_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE.txt"),
        "Apache License\nVersion 2.0, January 2004\n\
         http://www.apache.org/licenses/\n\
         Unless required by applicable law or agreed to in writing, software \
         distributed under the License is distributed on an \"AS IS\" BASIS.\n\
         Limitations under the License.",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE.txt")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "Apache-2.0"));
}

#[test]
fn given_gpl3_text_then_gpl_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("COPYING"),
        "GNU General Public License\nVersion 3, 29 June 2007\n\
         You may redistribute it under the terms of the GNU General Public License \
         as published by the Free Software Foundation, either version 3 of the License, \
         or (at your option) any later version.",
    )
    .unwrap();
    let files = vec![PathBuf::from("COPYING")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "GPL-3.0-or-later"));
}

#[test]
fn given_agpl3_text_then_agpl_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "GNU Affero General Public License\nVersion 3\n\
         You may redistribute it under the GNU Affero General Public License \
         any later version.",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(
        report
            .findings
            .iter()
            .any(|f| f.spdx == "AGPL-3.0-or-later")
    );
}

#[test]
fn given_bsd3_text_then_bsd3_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Redistribution and use in source and binary forms, with or without modification.\n\
         Neither the name of the copyright holder nor the names of its \
         contributors may be used to endorse or promote products.",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "BSD-3-Clause"));
}

#[test]
fn given_bsd2_text_then_bsd2_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Redistribution and use in source and binary forms, with or without modification.\n\
         This software is provided by the copyright holders and contributors \"as is\".",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    // BSD-2-Clause or BSD-3-Clause (both match "redistribution and use")
    assert!(report.findings.iter().any(|f| f.spdx.starts_with("BSD")));
}

#[test]
fn given_mpl2_text_then_mpl_detected() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Mozilla Public License Version 2.0\n\
         http://mozilla.org/MPL/2.0/\n\
         This Source Code Form is subject to the terms of the Mozilla Public License.",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "MPL-2.0"));
}

// ===========================================================================
// BDD: Edge cases – empty, binary, unrecognized, long files
// ===========================================================================

#[test]
fn given_empty_license_file_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("LICENSE"), "").unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
    assert!(report.effective.is_none());
}

#[test]
fn given_whitespace_only_license_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("LICENSE"), "   \n\n  \t  \n").unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

#[test]
fn given_binary_content_in_license_then_no_crash() {
    let dir = tempdir().unwrap();
    let binary: Vec<u8> = (0..256).map(|i| i as u8).collect();
    fs::write(dir.path().join("LICENSE"), &binary).unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    // Should not panic
    let result = build_license_report(dir.path(), &files, &default_limits());
    assert!(result.is_ok());
}

#[test]
fn given_proprietary_text_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "PROPRIETARY LICENSE\nAll rights reserved. Unauthorized copying is prohibited.",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

#[test]
fn given_very_long_license_text_then_still_detected() {
    let dir = tempdir().unwrap();
    let mut text = String::from(
        "Permission is hereby granted, free of charge, to any person.\n\
         The software is provided \"as is\".\n",
    );
    // Pad with lots of filler
    for _ in 0..1000 {
        text.push_str("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n");
    }
    fs::write(dir.path().join("LICENSE"), &text).unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "MIT"));
}

#[test]
fn given_no_files_at_all_then_empty_report() {
    let dir = tempdir().unwrap();
    let report = build_license_report(dir.path(), &[], &default_limits()).unwrap();
    assert!(report.findings.is_empty());
    assert!(report.effective.is_none());
}

#[test]
fn given_only_source_files_then_empty_report() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("main.rs"), "fn main() {}").unwrap();
    fs::write(dir.path().join("lib.rs"), "pub fn hello() {}").unwrap();
    let files = vec![PathBuf::from("main.rs"), PathBuf::from("lib.rs")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

// ===========================================================================
// BDD: License filename variants
// ===========================================================================

#[test]
fn given_license_mit_filename_then_scanned_as_text() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE-MIT"),
        "Permission is hereby granted, free of charge.\n\
         The software is provided \"as is\".",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE-MIT")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "MIT"));
}

#[test]
fn given_license_apache_filename_then_scanned() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE-APACHE"),
        "Apache License\nVersion 2.0\n\
         http://www.apache.org/licenses/\n\
         Limitations under the License.",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE-APACHE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "Apache-2.0"));
}

#[test]
fn given_copying_filename_then_scanned() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("COPYING"),
        "Permission is hereby granted, free of charge.\n\
         The software is provided \"as is\".",
    )
    .unwrap();
    let files = vec![PathBuf::from("COPYING")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.iter().any(|f| f.spdx == "MIT"));
}

// ===========================================================================
// BDD: Multiple sources – sorting and effective license
// ===========================================================================

#[test]
fn given_metadata_and_text_then_both_found_with_valid_confidence() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = \"MIT\"\n",
    )
    .unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Permission is hereby granted, free of charge.\n\
         The software is provided \"as is\".",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml"), PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.len() >= 2);
    let metadata = report
        .findings
        .iter()
        .find(|f| f.source_kind == LicenseSourceKind::Metadata)
        .unwrap();
    let text = report
        .findings
        .iter()
        .find(|f| f.source_kind == LicenseSourceKind::Text)
        .unwrap();
    assert!((metadata.confidence - 0.95).abs() < f32::EPSILON);
    assert!(text.confidence >= 0.6);
    assert!(text.confidence <= 1.0);
}

#[test]
fn findings_sorted_by_confidence_then_spdx_then_path() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = \"MIT\"\n",
    )
    .unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Permission is hereby granted, free of charge.\n\
         The software is provided \"as is\".",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml"), PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    for pair in report.findings.windows(2) {
        assert!(
            pair[0].confidence >= pair[1].confidence,
            "not sorted: {} >= {}",
            pair[0].confidence,
            pair[1].confidence
        );
    }
}

#[test]
fn effective_is_first_finding_spdx() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = \"Apache-2.0\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(
        report.effective,
        report.findings.first().map(|f| f.spdx.clone())
    );
}

// ===========================================================================
// BDD: Path normalization
// ===========================================================================

#[test]
fn source_paths_use_forward_slashes_for_nested_files() {
    let dir = tempdir().unwrap();
    let sub = dir.path().join("nested").join("dir");
    fs::create_dir_all(&sub).unwrap();
    fs::write(sub.join("package.json"), r#"{"name":"x","license":"MIT"}"#).unwrap();
    let files = vec![PathBuf::from("nested").join("dir").join("package.json")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    for f in &report.findings {
        assert!(
            !f.source_path.contains('\\'),
            "backslash in path: {}",
            f.source_path
        );
    }
}

// ===========================================================================
// BDD: Confidence bounds
// ===========================================================================

#[test]
fn text_confidence_is_between_0_6_and_1_0() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Permission is hereby granted, free of charge.\n\
         The software is provided \"as is\".",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    for f in &report.findings {
        if f.source_kind == LicenseSourceKind::Text {
            assert!(
                f.confidence >= 0.6,
                "text confidence too low: {}",
                f.confidence
            );
            assert!(
                f.confidence <= 1.0,
                "text confidence too high: {}",
                f.confidence
            );
        }
    }
}

#[test]
fn metadata_confidence_is_always_0_95() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = \"MIT\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    for f in &report.findings {
        if f.source_kind == LicenseSourceKind::Metadata {
            assert!(
                (f.confidence - 0.95).abs() < f32::EPSILON,
                "metadata confidence should be 0.95, got {}",
                f.confidence
            );
        }
    }
}

// ===========================================================================
// BDD: Cargo.toml with extra keys around license
// ===========================================================================

#[test]
fn given_cargo_toml_with_many_fields_then_license_still_found() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"big-project\"\nversion = \"1.2.3\"\n\
         edition = \"2021\"\nlicense = \"LGPL-2.1-only\"\n\
         description = \"A big project\"\nauthors = [\"dev\"]\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings[0].spdx, "LGPL-2.1-only");
}

#[test]
fn given_cargo_toml_with_workspace_section_then_only_package_parsed() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[workspace]\nmembers = [\"a\"]\n\n[package]\nname = \"x\"\nlicense = \"MIT\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(report.findings.len(), 1);
    assert_eq!(report.findings[0].spdx, "MIT");
}

// ===========================================================================
// BDD: Invalid/malformed metadata files
// ===========================================================================

#[test]
fn given_malformed_package_json_then_no_crash() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("package.json"), "NOT VALID JSON {{{").unwrap();
    let files = vec![PathBuf::from("package.json")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

#[test]
fn given_empty_cargo_toml_then_no_crash() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("Cargo.toml"), "").unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

#[test]
fn given_cargo_toml_with_empty_license_value_then_no_findings() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = \"\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert!(report.findings.is_empty());
}

// ===========================================================================
// BDD: Determinism – same input produces same output
// ===========================================================================

#[test]
fn deterministic_metadata_scanning() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nlicense = \"MIT\"\n",
    )
    .unwrap();
    let files = vec![PathBuf::from("Cargo.toml")];
    let r1 = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    let r2 = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(r1.findings.len(), r2.findings.len());
    assert_eq!(r1.effective, r2.effective);
    for (a, b) in r1.findings.iter().zip(r2.findings.iter()) {
        assert_eq!(a.spdx, b.spdx);
        assert!((a.confidence - b.confidence).abs() < f32::EPSILON);
        assert_eq!(a.source_path, b.source_path);
        assert_eq!(a.source_kind, b.source_kind);
    }
}

#[test]
fn deterministic_text_scanning() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("LICENSE"),
        "Permission is hereby granted, free of charge.\n\
         The software is provided \"as is\".",
    )
    .unwrap();
    let files = vec![PathBuf::from("LICENSE")];
    let r1 = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    let r2 = build_license_report(dir.path(), &files, &default_limits()).unwrap();
    assert_eq!(r1.findings.len(), r2.findings.len());
    for (a, b) in r1.findings.iter().zip(r2.findings.iter()) {
        assert_eq!(a.spdx, b.spdx);
        assert!((a.confidence - b.confidence).abs() < f32::EPSILON);
    }
}

// ===========================================================================
// Property tests
// ===========================================================================

fn spdx_strategy() -> impl Strategy<Value = String> {
    prop::sample::select(vec![
        "MIT".to_string(),
        "Apache-2.0".to_string(),
        "GPL-3.0-only".to_string(),
        "BSD-2-Clause".to_string(),
        "ISC".to_string(),
        "MPL-2.0".to_string(),
        "Unlicense".to_string(),
        "0BSD".to_string(),
        "Zlib".to_string(),
        "EUPL-1.2".to_string(),
    ])
}

proptest! {
    #[test]
    fn prop_cargo_spdx_roundtrips(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            format!("[package]\nname = \"t\"\nlicense = \"{spdx}\"\n"),
        ).unwrap();
        let files = vec![PathBuf::from("Cargo.toml")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        prop_assert!(!report.findings.is_empty());
        prop_assert_eq!(&report.findings[0].spdx, &spdx);
    }

    #[test]
    fn prop_package_json_spdx_roundtrips(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("package.json"),
            format!(r#"{{"name":"t","license":"{spdx}"}}"#),
        ).unwrap();
        let files = vec![PathBuf::from("package.json")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        prop_assert!(!report.findings.is_empty());
        prop_assert_eq!(&report.findings[0].spdx, &spdx);
    }

    #[test]
    fn prop_pyproject_spdx_roundtrips(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("pyproject.toml"),
            format!("[project]\nname = \"t\"\nlicense = \"{spdx}\"\n"),
        ).unwrap();
        let files = vec![PathBuf::from("pyproject.toml")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        prop_assert!(!report.findings.is_empty());
        prop_assert_eq!(&report.findings[0].spdx, &spdx);
    }

    #[test]
    fn prop_empty_file_list_always_empty(_seed in 0u64..1000) {
        let dir = tempdir().unwrap();
        let report = build_license_report(dir.path(), &[], &default_limits()).unwrap();
        prop_assert!(report.findings.is_empty());
        prop_assert!(report.effective.is_none());
    }

    #[test]
    fn prop_findings_always_sorted(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            format!("[package]\nname = \"t\"\nlicense = \"{spdx}\"\n"),
        ).unwrap();
        fs::write(
            dir.path().join("LICENSE"),
            "Permission is hereby granted, free of charge.\n\
             The software is provided \"as is\".",
        ).unwrap();
        let files = vec![PathBuf::from("Cargo.toml"), PathBuf::from("LICENSE")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        for pair in report.findings.windows(2) {
            prop_assert!(pair[0].confidence >= pair[1].confidence);
        }
    }

    #[test]
    fn prop_effective_equals_first_finding(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            format!("[package]\nname = \"t\"\nlicense = \"{spdx}\"\n"),
        ).unwrap();
        let files = vec![PathBuf::from("Cargo.toml")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        prop_assert_eq!(report.effective, report.findings.first().map(|f| f.spdx.clone()));
    }

    #[test]
    fn prop_confidence_in_valid_range(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            format!("[package]\nname = \"t\"\nlicense = \"{spdx}\"\n"),
        ).unwrap();
        fs::write(
            dir.path().join("LICENSE"),
            "Permission is hereby granted, free of charge.\n\
             The software is provided \"as is\".",
        ).unwrap();
        let files = vec![PathBuf::from("Cargo.toml"), PathBuf::from("LICENSE")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        for f in &report.findings {
            prop_assert!(f.confidence >= 0.0 && f.confidence <= 1.0);
        }
    }

    #[test]
    fn prop_no_backslash_in_paths(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        let sub = dir.path().join("a");
        fs::create_dir_all(&sub).unwrap();
        fs::write(
            sub.join("Cargo.toml"),
            format!("[package]\nname = \"t\"\nlicense = \"{spdx}\"\n"),
        ).unwrap();
        let files = vec![PathBuf::from("a").join("Cargo.toml")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        for f in &report.findings {
            prop_assert!(!f.source_path.contains('\\'));
        }
    }

    #[test]
    fn prop_metadata_confidence_always_0_95(spdx in spdx_strategy()) {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            format!("[package]\nname = \"t\"\nlicense = \"{spdx}\"\n"),
        ).unwrap();
        let files = vec![PathBuf::from("Cargo.toml")];
        let report = build_license_report(dir.path(), &files, &default_limits()).unwrap();
        for f in &report.findings {
            if f.source_kind == LicenseSourceKind::Metadata {
                prop_assert!((f.confidence - 0.95).abs() < f32::EPSILON);
            }
        }
    }
}