oinkie 0.8.1

Detects software theft by comparing birthmarks extracted from binaries
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
use assert_cmd::Command;
use predicates::prelude::*;
use serial_test::serial;
use std::fs;
use tempfile::tempdir;

// Tests marked `#[serial(ghidra)]` start a real Ghidra. They are serialised
// against each other because Ghidra compiles its SLEIGH language definitions
// on first use and caches them *inside its own installation*, so two headless
// runs against an installation nobody has used yet write the same file at the
// same time and the loser reads a half-written one. analyzeHeadless exits
// successfully regardless, so it arrives as a missing output rather than an
// error.
//
// The group is named for what is shared rather than left anonymous, so that a
// future test needing the same exclusion knows which one to join.

#[test]
fn test_info_command() {
    let mut cmd = Command::cargo_bin("oinkie").unwrap();
    cmd.arg("info")
        .assert()
        .success()
        .stdout(predicate::str::contains("Oinkie Info"))
        .stdout(predicate::str::contains("Birthmarks"))
        .stdout(predicate::str::contains("Compare Algorithms"));
}

#[test]
#[serial(ghidra)]
fn test_lift_command() {
    let temp_dir = tempdir().unwrap();
    let dest = temp_dir.path().join("lifted");

    let mut cmd = Command::cargo_bin("oinkie").unwrap();
    let result = cmd
        .arg("lift")
        .arg("-d")
        .arg(&dest)
        .arg("-r")
        .arg("ghidra-pcode")
        .arg("testdata/bin/hello_clang")
        .assert();

    result.success();
    let out_file = dest.join("hello_clang.json");
    assert!(out_file.exists(), "hello_clang.json was not generated");
}

/// Nothing inside the library can check that the environment variable is
/// actually read: the search takes its environment as a parameter, so that
/// tests do not write to the process' own, and a test that injects the lookup
/// cannot also prove the real one is wired to it.
///
/// A child process can. `GHIDRA_HOME` is set for that process alone, which is
/// hermetic in a way `set_var` cannot be, and pointing it at a directory
/// with no `support/analyzeHeadless` makes the run fail while naming the path
/// it was given -- so the assertion is that the value reached Ghidra's home,
/// not merely that the run failed. No Ghidra starts, so this does not join
/// the `ghidra` group.
///
/// The home is a fixed absolute path rather than one under the temporary
/// directory. It only has to be somewhere Ghidra is not, and naming it
/// literally keeps the expected string a literal too. Derived from `TMPDIR`,
/// it would have to survive both `to_str` and the `{:?}` the error message
/// formats it with -- a non-UTF-8 `TMPDIR` panics on the first, and one
/// holding a quote or a backslash comes back escaped from the second. Either
/// way the test would report the environment variable as broken on a machine
/// where the only unusual thing is where it puts its temporary files.
///
/// The two halves are asserted separately rather than as the joined path,
/// because both the separator and the entry point's name belong to the
/// platform: `join` writes a backslash on Windows, `{:?}` then escapes it, and
/// the entry point there is `analyzeHeadless.bat`. What the test is
/// about is that the value arrived -- the home in the message -- and that
/// Ghidra is what was looked for, and neither of those is a question about
/// path syntax.
#[test]
fn test_the_lifter_home_is_read_from_the_environment() {
    let temp_dir = tempdir().unwrap();
    let dest = temp_dir.path().join("lifted");

    Command::cargo_bin("oinkie")
        .unwrap()
        .env("GHIDRA_HOME", "/oinkie-no-such-ghidra")
        .arg("lift")
        .arg("-d")
        .arg(&dest)
        .arg("testdata/bin/hello_clang")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("oinkie-no-such-ghidra")
                .and(predicate::str::contains("analyzeHeadless")),
        );
}

/// clap's own message begins "error: ", so `main` prints it as it is rather
/// than behind "Error: ", which would read "Error: error: ...". oinkie's own
/// errors carry no prefix of their own and keep theirs.
///
/// End to end because the prefix is added in `main`, which no unit test
/// reaches.
#[test]
fn test_a_usage_error_is_not_prefixed_twice() {
    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("run")
        .arg("--bogus-flag")
        .assert()
        .failure()
        .stderr(predicate::str::starts_with("error: "))
        .stderr(predicate::str::contains("Error: error:").not());

    // and the other arm still says whose error it is
    let temp_dir = tempdir().unwrap();
    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("extract")
        .arg("-d")
        .arg(temp_dir.path().join("birthmarks"))
        .arg("no-such-file.json")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Error: IO error for"));
}

#[test]
fn test_extract_command() {
    let temp_dir = tempdir().unwrap();
    let dest = temp_dir.path().join("birthmarks");

    let mut cmd = Command::cargo_bin("oinkie").unwrap();
    cmd.arg("extract")
        .arg("-d")
        .arg(&dest)
        .arg("-b")
        .arg("op-seq")
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .arg("testdata/lifted/pcodes/hello_gcc.json")
        .assert()
        .success();

    // Verify the output files were created
    let entries: Vec<_> = fs::read_dir(&dest)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();
    assert_eq!(
        entries.len(),
        2,
        "Expected 2 birthmark files to be generated"
    );
}

/// `-b` names a birthmark the way the library does: `op-3gram-set`, the
/// spelling the docs use and the library parses.
///
/// End to end rather than at the parser, because this is the half a user
/// types: the new spelling has to reach an extracted file, and the old one
/// has to fail rather than silently mean something else.
#[test]
fn test_extract_names_a_kgram_the_way_the_library_does() {
    let temp_dir = tempdir().unwrap();
    let dest = temp_dir.path().join("birthmarks");

    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("extract")
        .arg("-d")
        .arg(&dest)
        .arg("-b")
        .arg("op-3gram-set")
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .assert()
        .success();
    assert_eq!(fs::read_dir(&dest).unwrap().count(), 1);

    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("extract")
        .arg("-d")
        .arg(temp_dir.path().join("unused"))
        .arg("-b")
        .arg("op-tri-gram-set")
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown birthmark type"));
}

/// An `op-*gram-freq` birthmark can be written and read back: a k-gram is a
/// list of operations and a JSON object's keys are strings, so the map cannot
/// be written as an object.
///
/// `op-2gram-freq` on this fixture rather than a larger k, because the
/// fixture's one function has four operations, so k >= 5 yields an empty map,
/// and an empty map has no key to write -- a test picking k = 5 would pass
/// whatever the map's form.
///
/// The score is checked against `run`, which computes the same analysis
/// without ever writing a birthmark. Equal scores say the file round trip is
/// faithful, not merely that it completed.
#[test]
fn test_a_kgram_frequency_birthmark_can_be_written_and_read_back() {
    let temp_dir = tempdir().unwrap();
    let birthmarks = temp_dir.path().join("birthmarks");
    let through_a_file = temp_dir.path().join("through-a-file");
    let in_memory = temp_dir.path().join("in-memory");
    let inputs = [
        "testdata/lifted/pcodes/hello_clang.json",
        "testdata/lifted/pcodes/hello_gcc.json",
    ];

    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["extract", "-b", "op-2gram-freq", "-d"])
        .arg(&birthmarks)
        .args(inputs)
        .assert()
        .success();
    let written: Vec<_> = fs::read_dir(&birthmarks)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();
    assert_eq!(written.len(), 2, "the birthmarks were not written");
    assert!(
        fs::read_to_string(&written[0])
            .unwrap()
            .contains("KgramFreq"),
        "the file does not hold what was asked for"
    );

    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["compare", "-a", "cosine", "-d"])
        .arg(&through_a_file)
        .args(&written)
        .assert()
        .success();

    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["run", "-a", "op-2gram-freq-cosine", "-d"])
        .arg(&in_memory)
        .args(inputs)
        .assert()
        .success();

    // Every row, sorted. The rows are written from a parallel iteration, so
    // which one lands first is not part of the output's meaning -- reading
    // only the first line made this test depend on a race, and it lost.
    //
    // Each row is `index, similarity, left, right, duration`; the duration is
    // wall clock and the only field that differs between two runs of the same
    // analysis, so it is dropped.
    let scores = |dir: &std::path::Path| {
        let csv = fs::read_to_string(dir.join("results.csv")).unwrap();
        let mut rows: Vec<String> = csv
            .lines()
            .filter(|l| !l.starts_with("total duration,"))
            .map(|l| l.rsplit_once(',').unwrap().0.to_string())
            .collect();
        rows.sort();
        assert!(!rows.is_empty(), "no scores in {}", dir.display());
        rows
    };
    assert_eq!(scores(&through_a_file), scores(&in_memory));
}

#[test]
fn test_compare_command() {
    let temp_dir = tempdir().unwrap();
    let birthmarks_dir = temp_dir.path().join("birthmarks");
    let similarities_dir = temp_dir.path().join("similarities");

    // First, extract
    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("extract")
        .arg("-d")
        .arg(&birthmarks_dir)
        .arg("-b")
        .arg("op-seq")
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .arg("testdata/lifted/pcodes/hello_gcc.json")
        .assert()
        .success();

    let entries: Vec<_> = fs::read_dir(&birthmarks_dir)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();

    // Now, compare
    let mut cmd = Command::cargo_bin("oinkie").unwrap();
    cmd.arg("compare")
        .arg("-d")
        .arg(&similarities_dir)
        .arg("-a")
        .arg("jaccard")
        .arg("-A")
        .arg("hungarian")
        .arg("-s")
        .arg("all")
        .args(&entries)
        .assert()
        .success();

    let sim_entries: Vec<_> = fs::read_dir(&similarities_dir)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();
    assert!(
        !sim_entries.is_empty(),
        "Expected similarity files to be generated"
    );
}

#[test]
fn test_run_command() {
    let temp_dir = tempdir().unwrap();
    let similarities_dir = temp_dir.path().join("similarities");

    let mut cmd = Command::cargo_bin("oinkie").unwrap();
    cmd.arg("run")
        .arg("-a")
        .arg("op-set-jaccard")
        .arg("-s")
        .arg("all")
        .arg("-d")
        .arg(&similarities_dir)
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .arg("testdata/lifted/pcodes/hello_gcc.json")
        .assert()
        .success();

    let sim_entries: Vec<_> = fs::read_dir(&similarities_dir)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();
    assert!(
        !sim_entries.is_empty(),
        "Expected similarity files to be generated"
    );
}

/// The first score in a summary CSV: `index,similarity,left,right,duration`.
fn first_score(summary: &std::path::Path) -> f64 {
    let content =
        fs::read_to_string(summary).unwrap_or_else(|e| panic!("{}: {e}", summary.display()));
    let first = content.lines().next().expect("an empty summary");
    first.split(',').nth(1).unwrap().parse().unwrap()
}

/// `run` is `extract` followed by `compare`, so the two give the same score --
/// for every birthmark family and shape, since a `run` that compared the
/// programs' operations whatever birthmark the analysis named would agree on
/// `op-*` alone.
#[test]
fn test_run_scores_what_extract_and_compare_score() {
    let inputs = [
        "testdata/lifted/pcodes/hello_clang.json",
        "testdata/lifted/pcodes/udl.json",
    ];
    for (birthmark_type, algorithm) in [
        ("op-seq", "levenshtein"),
        ("fc-seq", "levenshtein"),
        ("op-3gram-seq", "levenshtein"),
        ("fc-set", "jaccard"),
        ("op-2gram-set", "jaccard"),
        ("fc-freq", "cosine"),
        ("op-2gram-freq", "weighted-jaccard"),
        ("op-freq", "jensen-shannon"),
        ("fc-freq", "tanimoto"),
    ] {
        let analysis = format!("{birthmark_type}-{algorithm}");
        let dir = tempdir().unwrap();

        Command::cargo_bin("oinkie")
            .unwrap()
            .args(["run", "-a", &analysis, "-s", "all", "-d"])
            .arg(dir.path().join("run"))
            .args(inputs)
            .assert()
            .success();

        let birthmarks = dir.path().join("birthmarks");
        Command::cargo_bin("oinkie")
            .unwrap()
            .args(["extract", "-b", birthmark_type, "-d"])
            .arg(&birthmarks)
            .args(inputs)
            .assert()
            .success();
        let mut extracted = fs::read_dir(&birthmarks)
            .unwrap()
            .map(|e| e.unwrap().path())
            .collect::<Vec<_>>();
        // `compare` pairs its arguments in order; give them in the order `run` had
        extracted.sort_by_key(|p| {
            !p.file_name()
                .unwrap()
                .to_string_lossy()
                .starts_with("hello_clang")
        });
        Command::cargo_bin("oinkie")
            .unwrap()
            .args(["compare", "-a", algorithm, "-s", "all", "-d"])
            .arg(dir.path().join("compare"))
            .args(&extracted)
            .assert()
            .success();

        let run = first_score(&dir.path().join("run").join("results.csv"));
        let compare = first_score(&dir.path().join("compare").join("results.csv"));
        assert_eq!(
            run, compare,
            "{analysis}: run and extract + compare disagree"
        );
    }
}

/// A k-gram of size zero is a usage error, refused before it reaches
/// extraction, not a panic there.
#[test]
fn test_a_zero_gram_analysis_is_refused_not_a_panic() {
    let dir = tempdir().unwrap();
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["run", "-a", "op-0gram-set-jaccard", "-s", "all", "-d"])
        .arg(dir.path())
        .args([
            "testdata/lifted/pcodes/hello_clang.json",
            "testdata/lifted/pcodes/udl.json",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicates::str::contains("op-0gram-set"))
        .stderr(predicates::str::contains("panicked").not());
}

/// The birthmark named on a side of a pair's CSV: the last field of its
/// `left` or `right` line.
fn side_birthmark(pair_csv: &std::path::Path, side: &str) -> std::path::PathBuf {
    let content = fs::read_to_string(pair_csv).unwrap();
    let line = content
        .lines()
        .find(|l| l.starts_with(&format!("{side},birthmark,")))
        .unwrap_or_else(|| panic!("no {side} birthmark in {}", pair_csv.display()));
    std::path::PathBuf::from(line.rsplit(',').next().unwrap())
}

/// `run` writes the birthmarks it compares into the score directory, one per
/// input, and each pair's CSV names the two it used -- so the directory holds
/// everything `review` needs to re-read the comparison, as `compare`'s does.
#[test]
fn test_run_writes_the_birthmarks_it_compares() {
    let dir = tempdir().unwrap();
    let dest = dir.path().join("out");
    let inputs = [
        "testdata/lifted/pcodes/hello_clang.json",
        "testdata/lifted/pcodes/hello_gcc.json",
        "testdata/lifted/pcodes/udl.json",
    ];
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["run", "-a", "fc-set-jaccard", "-s", "all", "-d"])
        .arg(&dest)
        .args(inputs)
        .assert()
        .success();

    let written = fs::read_dir(dest.join("birthmarks"))
        .expect("no birthmarks directory")
        .map(|e| e.unwrap().path())
        .collect::<Vec<_>>();
    assert_eq!(
        written.len(),
        inputs.len(),
        "one birthmark per input: {written:?}"
    );

    for pair in ["00000.csv", "00001.csv", "00002.csv"] {
        for side in ["left", "right"] {
            let named = side_birthmark(&dest.join(pair), side);
            assert!(
                written.contains(&named),
                "{pair} {side}: {} was not written",
                named.display()
            );
            let b: serde_json::Value =
                serde_json::from_str(&fs::read_to_string(&named).unwrap()).unwrap();
            assert_eq!(
                b["metadata"]["birthmark_type"],
                "FcSet",
                "{}",
                named.display()
            );
        }
    }
}

/// `--skip` reuses a birthmark already written -- but only one of the type the
/// analysis asks for. The file name does not say which type a birthmark is, so
/// a directory run before with another analysis would otherwise hand the old
/// birthmarks to the new comparison.
#[test]
fn test_run_skip_does_not_reuse_a_birthmark_of_another_type() {
    let dir = tempdir().unwrap();
    let dest = dir.path().join("out");
    let inputs = [
        "testdata/lifted/pcodes/hello_clang.json",
        "testdata/lifted/pcodes/udl.json",
    ];
    let run = |analysis: &str, scores: &str| {
        Command::cargo_bin("oinkie")
            .unwrap()
            .args(["run", "-S", "-a", analysis, "-s", "all", "-d"])
            .arg(dest.join(scores))
            .args(inputs)
            .assert()
            .success();
    };
    run("fc-set-jaccard", "");
    run("op-set-jaccard", "");
    let named = side_birthmark(&dest.join("00000.csv"), "left");
    let b: serde_json::Value = serde_json::from_str(&fs::read_to_string(&named).unwrap()).unwrap();
    assert_eq!(
        b["metadata"]["birthmark_type"], "OpSet",
        "the fc-set birthmark was reused"
    );
    // and the score was recomputed with it: one kept from the fc-set run
    // would name the op-set birthmark that replaced the one it compared
    let fresh = dir.path().join("fresh");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["run", "-a", "op-set-jaccard", "-s", "all", "-d"])
        .arg(&fresh)
        .args(inputs)
        .assert()
        .success();
    let similarity = |pair: &std::path::Path| -> String {
        let content = fs::read_to_string(pair).unwrap();
        let line = content.lines().find(|l| l.starts_with("result,")).unwrap();
        line.split(',').nth(2).unwrap().to_string()
    };
    assert_eq!(
        similarity(&dest.join("00000.csv")),
        similarity(&fresh.join("00000.csv")),
        "the fc-set score was kept"
    );
}

/// The same input twice is extracted once and written once, rather than by
/// two workers into one file at the same time.
#[test]
fn test_run_given_an_input_twice_writes_its_birthmark_once() {
    let dir = tempdir().unwrap();
    let dest = dir.path().join("out");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["run", "-s", "all", "-d"])
        .arg(&dest)
        .args([
            "testdata/lifted/pcodes/hello_clang.json",
            "testdata/lifted/pcodes/hello_clang.json",
            "testdata/lifted/pcodes/udl.json",
        ])
        .assert()
        .success();
    let written = fs::read_dir(dest.join("birthmarks"))
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect::<Vec<_>>();
    assert_eq!(written.len(), 2, "{written:?}");
    for w in written {
        serde_json::from_str::<serde_json::Value>(&fs::read_to_string(&w).unwrap())
            .unwrap_or_else(|e| panic!("{}: {e}", w.display()));
    }
}

/// A score directory from `run` over two programs whose functions hold
/// different numbers of elements under `fc-set`: udl's hold 0, 0 and 3, and
/// hello_clang's one holds 1, so the mean over all four is 1.
fn fc_set_scores(dir: &std::path::Path) -> std::path::PathBuf {
    let dest = dir.join("scores");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["run", "-a", "fc-set-jaccard", "-s", "all", "-d"])
        .arg(&dest)
        .args([
            "testdata/lifted/pcodes/udl.json",
            "testdata/lifted/pcodes/hello_clang.json",
        ])
        .assert()
        .success();
    dest
}

/// `review --min-elements`, and what it leaves in the summary.
fn review(scores: &std::path::Path, min: Option<&str>) -> (f64, Option<String>) {
    let out = scores.parent().unwrap().join("review.csv");
    let mut cmd = Command::cargo_bin("oinkie").unwrap();
    cmd.arg("review").arg("-d").arg(&out).arg(scores);
    if let Some(m) = min {
        cmd.args(["--min-elements", m]);
    }
    cmd.assert().success();
    let content = fs::read_to_string(&out).unwrap();
    let last = content.lines().last().unwrap();
    let recorded = last.starts_with("min elements,").then(|| last.to_string());
    (first_score(&out), recorded)
}

/// Functions with fewer elements than the threshold are dropped before the
/// pair is aggregated, and the summary says which threshold it was.
#[test]
fn test_review_drops_the_functions_with_too_few_elements() {
    let dir = tempdir().unwrap();
    let scores = fc_set_scores(dir.path());
    let (plain, recorded) = review(&scores, None);
    assert_eq!(recorded, None, "no threshold, no line");
    // udl's two empty functions take part: 1/3, over its three functions
    assert!((plain - 1.0 / 9.0).abs() < 1e-9, "{plain}");

    // half the mean: udl's empty functions go, leaving entry against entry
    let (half, recorded) = review(&scores, Some("0.5x"));
    assert!((half - 1.0 / 3.0).abs() < 1e-9, "{half}");
    assert_eq!(recorded.as_deref(), Some("min elements,0.5x,0.5"));

    // a count that only udl's entry reaches: hello_clang has nothing left,
    // and one side with nothing scores 0.0
    let (two, recorded) = review(&scores, Some("2"));
    assert_eq!(two, 0.0);
    assert_eq!(recorded.as_deref(), Some("min elements,2,2"));

    // one neither side reaches: both are empty, which scores 1.0
    let (four, _) = review(&scores, Some("4"));
    assert_eq!(four, 1.0);

    // a threshold that drops nothing changes nothing but the record
    let (zero, recorded) = review(&scores, Some("0"));
    assert_eq!(zero, plain);
    assert_eq!(recorded.as_deref(), Some("min elements,0,0"));
}

/// `review -A` with the aggregators that read the same matching as
/// `hungarian` differently. hello_clang's one function best matches one of
/// udl's three at 1/3: `hungarian` averages that over udl's three functions,
/// `containment` over hello_clang's one, and `matched` counts it if it is
/// close enough.
#[test]
fn test_review_scores_under_containment_and_matched() {
    let dir = tempdir().unwrap();
    let scores = fc_set_scores(dir.path());
    let score = |aggregator: &str| {
        let out = dir
            .path()
            .join(format!("{}.csv", aggregator.replace(':', "_")));
        Command::cargo_bin("oinkie")
            .unwrap()
            .args(["review", "-A", aggregator, "-d"])
            .arg(&out)
            .arg(&scores)
            .assert()
            .success();
        first_score(&out)
    };
    assert!((score("hungarian") - 1.0 / 9.0).abs() < 1e-9);
    assert!((score("containment") - 1.0 / 3.0).abs() < 1e-9);
    assert!((score("matched:0.3") - 1.0 / 3.0).abs() < 1e-9);
    assert_eq!(score("matched:0.5"), 0.0);
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["review", "-A", "matched:2", "-d"])
        .arg(dir.path().join("refused.csv"))
        .arg(&scores)
        .assert()
        .failure();
}

/// `weighted` needs each function's size, which `run` has in hand and
/// `review` reads from the birthmarks the pair CSVs name: the two give the
/// same score, the sides' sizes each following the matrix's orientation.
/// op-seq on udl and hello_gcc, so that the sizes differ between functions
/// and between the two sides.
#[test]
fn test_review_weighted_scores_what_run_weighted_scores() {
    let dir = tempdir().unwrap();
    let scores = dir.path().join("scores");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args([
            "run",
            "-a",
            "op-seq-lcs",
            "-A",
            "weighted",
            "-s",
            "all",
            "-d",
        ])
        .arg(&scores)
        .args([
            "testdata/lifted/pcodes/udl.json",
            "testdata/lifted/pcodes/hello_gcc.json",
        ])
        .assert()
        .success();
    let run = first_score(&scores.join("results.csv"));
    let review = |aggregator: &str| {
        let out = dir.path().join(format!("{aggregator}.csv"));
        Command::cargo_bin("oinkie")
            .unwrap()
            .args(["review", "-A", aggregator, "-d"])
            .arg(&out)
            .arg(&scores)
            .assert()
            .success();
        first_score(&out)
    };
    assert_eq!(review("weighted"), run);
    assert_ne!(
        review("weighted"),
        review("hungarian"),
        "the sizes made no difference"
    );
}

/// A ratio is of the mean over every function of every distinct birthmark
/// in the directory: here op-seq, under which the functions are of different
/// lengths, with udl in both pairs and counted once.
#[test]
fn test_review_min_elements_ratio_is_of_the_mean_over_the_directory() {
    let dir = tempdir().unwrap();
    let scores = dir.path().join("scores");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args([
            "run",
            "-a",
            "op-seq-levenshtein",
            "-s",
            "first-vs-others",
            "-d",
        ])
        .arg(&scores)
        .args([
            "testdata/lifted/pcodes/udl.json",
            "testdata/lifted/pcodes/hello_clang.json",
            "testdata/lifted/pcodes/hello_gcc.json",
        ])
        .assert()
        .success();
    let lengths = fs::read_dir(scores.join("birthmarks"))
        .unwrap()
        .flat_map(|e| {
            let b: serde_json::Value =
                serde_json::from_str(&fs::read_to_string(e.unwrap().path()).unwrap()).unwrap();
            b["elements"]
                .as_array()
                .unwrap()
                .iter()
                .map(|f| f["data"]["Seq"].as_array().unwrap().len())
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();
    let mean = lengths.iter().sum::<usize>() as f64 / lengths.len() as f64;
    assert_ne!(
        mean, 1.0,
        "the fixture no longer tells a ratio from a count"
    );

    let (_, recorded) = review(&scores, Some("1x"));
    assert_eq!(recorded, Some(format!("min elements,1x,{mean}")));
}

#[test]
fn test_review_refuses_a_bare_fraction_for_min_elements() {
    let dir = tempdir().unwrap();
    let scores = fc_set_scores(dir.path());
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["review", "--min-elements", "0.3"])
        .arg(&scores)
        .assert()
        .failure()
        .stderr(predicates::str::contains("write 0.3x"));
}

/// Without the birthmarks there are no counts, and a directory that does not
/// name them is refused rather than reviewed as if nothing were short.
#[test]
fn test_review_min_elements_needs_the_birthmarks_named() {
    let dir = tempdir().unwrap();
    let scores = fc_set_scores(dir.path());
    let pair = scores.join("00000.csv");
    let content = fs::read_to_string(&pair).unwrap();
    // as written before the birthmark file was recorded: the field empty
    let without = content
        .lines()
        .map(|l| {
            if l.starts_with("left,") {
                format!("{},", &l[..l.rfind(',').unwrap()])
            } else {
                l.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("\n");
    fs::write(&pair, without).unwrap();
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["review", "-d"])
        .arg(dir.path().join("r.csv"))
        .args(["--min-elements", "2"])
        .arg(&scores)
        .assert()
        .failure()
        .stderr(predicates::str::contains("does not name the birthmarks"));
    // and without the option the directory still reviews
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["review", "-d"])
        .arg(dir.path().join("r.csv"))
        .arg(&scores)
        .assert()
        .success();
}

/// A birthmark replaced since the comparison would lend its counts to
/// another's functions.
#[test]
fn test_review_min_elements_refuses_a_birthmark_that_has_changed() {
    let dir = tempdir().unwrap();
    let scores = fc_set_scores(dir.path());
    let pair = scores.join("00000.csv");
    let (left, right) = (
        side_birthmark(&pair, "left"),
        side_birthmark(&pair, "right"),
    );
    fs::copy(&right, &left).unwrap();
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["review", "-d"])
        .arg(dir.path().join("r.csv"))
        .args(["--min-elements", "2"])
        .arg(&scores)
        .assert()
        .failure()
        .stderr(predicates::str::contains("has changed"));
}

/// A comparison with an empty birthmark on one side, or both, is written
/// with a matrix that names no functions for that side, and `review` failed
/// to read one back -- the very pairs `--min-elements` is about.
#[test]
fn test_review_reads_back_a_comparison_with_an_empty_birthmark() {
    let dir = tempdir().unwrap();
    let birthmarks = dir.path().join("birthmarks");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["extract", "-b", "fc-set", "-d"])
        .arg(&birthmarks)
        .args([
            "testdata/lifted/pcodes/udl.json",
            "testdata/lifted/pcodes/hello_clang.json",
        ])
        .assert()
        .success();
    let some = fs::read_dir(&birthmarks)
        .unwrap()
        .next()
        .unwrap()
        .unwrap()
        .path();
    let mut json: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&some).unwrap()).unwrap();
    json["elements"] = serde_json::json!([]);
    fs::write(birthmarks.join("empty.json"), json.to_string()).unwrap();
    let mut inputs = fs::read_dir(&birthmarks)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect::<Vec<_>>();
    inputs.sort();

    let scores = dir.path().join("scores");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["compare", "-s", "all-and-self", "-d"])
        .arg(&scores)
        .args(&inputs)
        .assert()
        .success();
    let out = dir.path().join("review.csv");
    Command::cargo_bin("oinkie")
        .unwrap()
        .args(["review", "-d"])
        .arg(&out)
        .arg(&scores)
        .assert()
        .success();
    let score_column = |p: &std::path::Path| {
        fs::read_to_string(p)
            .unwrap()
            .lines()
            .take_while(|l| !l.starts_with("total duration,"))
            .map(|l| l.split(',').nth(1).unwrap().to_string())
            .collect::<Vec<_>>()
    };
    let compared = score_column(&scores.join("results.csv"));
    assert!(
        compared.contains(&"0".to_string()) && compared.contains(&"1".to_string()),
        "the fixture no longer has an empty side and two empty sides: {compared:?}"
    );
    assert_eq!(score_column(&out), compared);
}

/// Help and the version go to a pipe as text: no colour codes, which a
/// terminal would turn into colour and anything else keeps as `^[[1m`.
/// The test's captured stdout is such a pipe. And they still succeed.
#[test]
fn test_help_written_to_a_pipe_has_no_colour_codes() {
    for args in [
        vec!["-h"],
        vec!["--help"],
        vec!["review", "-h"],
        vec!["compare", "--help"],
        vec!["--version"],
    ] {
        let out = Command::cargo_bin("oinkie")
            .unwrap()
            .args(&args)
            .output()
            .unwrap();
        assert!(out.status.success(), "{args:?}");
        assert!(!out.stdout.is_empty(), "{args:?}: nothing printed");
        assert!(
            !out.stdout.contains(&0x1b),
            "{args:?}: an escape code in {:?}",
            String::from_utf8_lossy(&out.stdout)
        );
    }
}

/// The old name is refused, not aliased, and the refusal names the new one --
/// including when it is handed the arguments the old command took.
#[test]
fn test_the_old_name_reaggregate_is_refused_naming_review() {
    for args in [
        vec!["reaggregate"],
        vec!["reaggregate", "-A", "topn:3", "-d", "x.csv", "out/"],
    ] {
        Command::cargo_bin("oinkie")
            .unwrap()
            .args(&args)
            .assert()
            .failure()
            .stderr(predicates::str::contains("use review"));
    }
}

#[test]
fn test_review_command() {
    let temp_dir = tempdir().unwrap();
    let birthmarks_dir = temp_dir.path().join("birthmarks");
    let similarities_dir = temp_dir.path().join("similarities");

    // First, extract
    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("extract")
        .arg("-d")
        .arg(&birthmarks_dir)
        .arg("-b")
        .arg("op-seq")
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .arg("testdata/lifted/pcodes/hello_gcc.json")
        .assert()
        .success();

    let entries: Vec<_> = fs::read_dir(&birthmarks_dir)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();

    // Compare
    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("compare")
        .arg("-d")
        .arg(&similarities_dir)
        .arg("-a")
        .arg("levenshtein")
        .arg("-s")
        .arg("all")
        .args(&entries)
        .assert()
        .success();

    // Review
    let dest_file = temp_dir.path().join("review.csv");
    let mut cmd = Command::cargo_bin("oinkie").unwrap();
    cmd.arg("review")
        .arg("-A")
        .arg("hungarian")
        .arg("-d")
        .arg(&dest_file)
        .arg(&similarities_dir)
        .assert()
        .success();

    assert!(dest_file.exists());
}

/// The path given to `-i` is handed to Ghidra as its project location and is
/// also used as the working directory of the Ghidra process. A relative path
/// must therefore be resolved before the process starts, or Ghidra resolves it
/// a second time against itself and looks for `irs/irs`.
/// Both `-i` regressions in one run, because each run is a whole decompiler.
///
/// A path given to `-i` is created rather than required to exist, as every
/// other destination directory in the CLI is and as the temporary directory
/// used without `-i` is by construction. And it is resolved once, by oinkie,
/// not again by Ghidra against its own working directory.
///
/// A relative path that does not exist yet covers both at once, and being
/// nested covers creating intermediate levels rather than just the last.
///
/// Getting either wrong makes the run itself fail here -- Ghidra complaining
/// that `irs/irs` does not exist. The explicit assertions below still earn
/// their place: they name which of the two broke, and they catch a variant
/// that doubles the path without failing outright.
#[test]
#[serial(ghidra)]
fn test_lift_command_intermediate_dir_is_created_and_resolved_once() {
    // Ghidra rejects any path element starting with '.', and tempdir() names
    // its directories ".tmpXXXX", so the project location needs a plain prefix.
    let temp_dir = tempfile::Builder::new()
        .prefix("oinkie_test")
        .tempdir()
        .unwrap();
    let input = fs::canonicalize("testdata/bin/hello_clang").unwrap();
    let dest = temp_dir.path().join("lifted");

    Command::cargo_bin("oinkie")
        .unwrap()
        .current_dir(temp_dir.path())
        .arg("lift")
        .arg("-i")
        .arg("irs/nested")
        .arg("-d")
        .arg(&dest)
        .arg(&input)
        .assert()
        .success();

    let intermediate = temp_dir.path().join("irs/nested");
    assert!(intermediate.is_dir(), "the -i directory was not created");
    assert!(
        !intermediate.join("irs/nested").exists(),
        "the -i path was resolved twice"
    );
    assert!(dest.join("hello_clang.json").exists());
}

/// A function name can hold a double quote. A C++ user-defined literal
/// operator is the everyday way to get one: Ghidra demangles `operator""_km`
/// as `operator""__km`, and a name pasted into the JSON unescaped makes a file
/// that cannot be read back -- while `lift` still reports success, since
/// analyzeHeadless exits 0 regardless.
///
/// Both halves are asserted. That the output parses is the escaping; that the
/// name survives rules out "strip the quote", which would parse and would then
/// compare a name the program does not have.
#[test]
#[serial(ghidra)]
fn test_lift_escapes_a_quote_in_a_function_name() {
    let temp_dir = tempdir().unwrap();
    let dest = temp_dir.path().join("lifted");

    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("lift")
        .arg("-d")
        .arg(&dest)
        .arg("testdata/bin/udl")
        .assert()
        .success();

    let out_file = dest.join("udl.json");
    // through oinkie's own reader rather than a parser of the test's
    // choosing: this is the operation an unescaped name breaks
    oinkie::Program::load(&out_file).expect("oinkie cannot read the file it just wrote");

    let body = fs::read_to_string(&out_file).unwrap();
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    let names = json["functions"]
        .as_array()
        .expect("no functions array")
        .iter()
        .map(|f| f["name"].as_str().expect("a function with no name"))
        .collect::<Vec<_>>();
    assert!(
        names.iter().any(|n| n.contains('"')),
        "the quoted name did not survive escaping: {names:?}"
    );
}

/// A lifting script can write bytes, return normally, and leave behind a file
/// nothing can read. `analyzeHeadless` exits 0 either way, so the lift is
/// checked by reading its output, or the failure would surface at `extract`
/// as a parse error in a file the reader had never seen.
///
/// Driven through `--script`, because a replacement is arbitrary Java that
/// oinkie never inspects: the check has to be on the output.
#[test]
#[serial(ghidra)]
fn test_a_lift_whose_output_cannot_be_read_is_not_a_successful_lift() {
    let temp_dir = tempdir().unwrap();
    let dest = temp_dir.path().join("lifted");

    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("lift")
        .arg("--script")
        .arg("testdata/scripts/BrokenLifter.java")
        .arg("-d")
        .arg(&dest)
        .arg("testdata/bin/hello_clang")
        .assert()
        .failure()
        // The binary the user asked about, matched as the whole path and with
        // the colon that follows it. Matching "hello_clang" alone proved
        // nothing: the output is named hello_clang.json, so the assertion
        // passed on a message that did not mention the binary at all.
        .stderr(predicate::str::contains("testdata/bin/hello_clang:"))
        // the file that is wrong, which the cause names
        .stderr(predicate::str::contains("hello_clang.json"))
        // and that the lifter claimed success, which is what points at the script
        .stderr(predicate::str::contains("reported success"));
}

/// Birthmarks for the `stats` tests below, extracted rather than committed:
/// `testdata/` holds lifted programs and no birthmark, and the extraction is
/// a second of work that keeps the fixtures one thing rather than two that
/// can disagree.
///
/// The names carry a content hash -- `hello_clang_48fa2ffd841490f0.json` --
/// so the assertions below use the `file_name` column, which is the stem.
fn birthmarks_in(dir: &std::path::Path) {
    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("extract")
        .arg("-d")
        .arg(dir)
        .arg("-b")
        .arg("op-seq")
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .arg("testdata/lifted/pcodes/hello_gcc.json")
        .assert()
        .success();
}

/// `--per-file` with `-f csv` is a whole output function of its own, and only
/// starting the command runs the formatters and the driver that picks between
/// them: `cli/stats.rs`'s unit tests cover the arithmetic. A renamed column
/// or a row built in the wrong order would otherwise ship.
///
/// The header is asserted in full rather than by one column, because what
/// breaks silently here is a swap: every name still present, in the wrong
/// place, over data that still parses as CSV.
#[test]
fn test_stats_writes_a_row_per_file_as_csv() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    birthmarks_in(&dir);

    let out = Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-f")
        .arg("csv")
        .arg("--per-file")
        .arg(&dir)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    let lines: Vec<&str> = text.lines().collect();

    assert_eq!(
        lines[0],
        "path,file_name,ir,birthmark_type,functions,empty,\
elements_min,elements_q1,elements_median,elements_q3,elements_max,\
elements_mean,elements_stddev"
    );
    assert_eq!(lines.len(), 3, "expected a header and two rows: {text}");
    for name in ["hello_clang", "hello_gcc"] {
        assert!(
            lines[1..].iter().any(|l| l.contains(&format!(",{name},"))),
            "no row for {name}: {text}"
        );
    }
}

/// The same for Markdown, which reaches a different function: the per-file
/// section is built where the summary tables are, and only when `--per-file`
/// is given, so the two formats share no code on this path.
#[test]
fn test_stats_writes_a_per_file_section_as_markdown() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    birthmarks_in(&dir);

    let out = Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-f")
        .arg("markdown")
        .arg("--per-file")
        .arg(&dir)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();

    let per_file = text
        .split_once("## Per file")
        .unwrap_or_else(|| panic!("no per-file section: {text}"))
        .1;
    for name in ["hello_clang", "hello_gcc"] {
        assert!(
            per_file.contains(name),
            "{name} is not in the section: {text}"
        );
    }
}

/// `--top` is the third table, and the one whose rows have an order that
/// means something: rank 1 is the most frequent element, so a sort that went
/// the other way would still produce a well-formed table.
#[test]
fn test_stats_ranks_the_most_frequent_elements_as_csv() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    birthmarks_in(&dir);

    let out = Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-f")
        .arg("csv")
        .arg("--top")
        .arg("3")
        .arg(&dir)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    let lines: Vec<&str> = text.lines().collect();

    assert_eq!(lines[0], "ir,birthmark_type,rank,element,count");
    assert_eq!(lines.len(), 4, "expected a header and three ranks: {text}");

    let counts: Vec<u64> = lines[1..]
        .iter()
        .map(|l| l.rsplit(',').next().unwrap().parse().unwrap())
        .collect();
    assert!(
        counts.windows(2).all(|w| w[0] >= w[1]),
        "the ranks are not in descending order of count: {counts:?}"
    );
}

/// One CSV file holds one table, so the two options that each replace the
/// summary cannot both be given. The refusal names the formats that do take
/// both, rather than only saying no.
#[test]
fn test_stats_refuses_two_csv_tables_and_says_where_to_put_them() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    birthmarks_in(&dir);

    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-f")
        .arg("csv")
        .arg("--per-file")
        .arg("--top")
        .arg("3")
        .arg(&dir)
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("--per-file")
                .and(predicate::str::contains("-f json"))
                .and(predicate::str::contains("-f markdown")),
        );
}

/// `-o` is the other half of the driver: with it the report goes to the file
/// and stdout stays empty, which is what lets `stats` be piped into something
/// else without the report arriving twice.
#[test]
fn test_stats_writes_to_the_named_file_and_not_to_stdout() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    birthmarks_in(&dir);
    let dest = temp_dir.path().join("stats.md");

    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-o")
        .arg(&dest)
        .arg(&dir)
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    let written = fs::read_to_string(&dest).expect("the report was not written");
    assert!(
        written.contains("# Birthmark statistics"),
        "the file does not hold the report: {written}"
    );
}

/// JSON is the third format, and the one an agent or a script reads, so its
/// shape is a promise rather than a rendering.
///
/// `occurrences` is asserted null here and counted in the test below, because
/// that field is the one thing in the report that depends on the birthmark's
/// shape rather than on its size: a sequence has no counts to total.
#[test]
fn test_stats_reports_the_groups_as_json() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    birthmarks_in(&dir);

    let out = Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-f")
        .arg("json")
        .arg(&dir)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).expect("the report is not JSON");

    let groups = json["groups"].as_array().expect("no groups array");
    assert_eq!(
        groups.len(),
        1,
        "two files of one type are one group: {json}"
    );
    assert_eq!(groups[0]["ir"], "ghidra-pcode");
    assert_eq!(groups[0]["birthmark_type"], "op-seq");
    assert_eq!(groups[0]["files"], 2);
    assert_eq!(groups[0]["elements"]["min"], 4);
    assert!(
        groups[0]["occurrences"].is_null(),
        "a sequence has no occurrence total: {json}"
    );
    assert!(json["skipped"].as_array().unwrap().is_empty());
}

/// A `freq` birthmark counts its elements, so the report has a total of those
/// counts where a sequence has none. That branch is chosen by the birthmark's
/// shape, and every test above uses `op-seq`, so nothing reached it.
#[test]
fn test_stats_totals_the_counts_of_a_freq_birthmark() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("extract")
        .arg("-d")
        .arg(&dir)
        .arg("-b")
        .arg("op-freq")
        .arg("testdata/lifted/pcodes/hello_clang.json")
        .assert()
        .success();

    let out = Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-f")
        .arg("json")
        .arg(&dir)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let group = &json["groups"][0];

    assert_eq!(group["birthmark_type"], "op-freq");
    let vocabulary = group["vocabulary"].as_u64().expect("no vocabulary");
    let occurrences = group["occurrences"]
        .as_u64()
        .unwrap_or_else(|| panic!("a freq birthmark has an occurrence total: {json}"));
    assert!(
        occurrences >= vocabulary,
        "fewer occurrences than distinct elements: {occurrences} < {vocabulary}"
    );
}

/// A directory contributes the files directly inside it, and `-r` the ones
/// below as well. Asserted as the difference between the two runs over one
/// tree, because either alone would pass on a scan that ignored the flag.
#[test]
fn test_stats_descends_only_when_asked() {
    let temp_dir = tempdir().unwrap();
    let flat = temp_dir.path().join("birthmarks");
    birthmarks_in(&flat);

    let nested = temp_dir.path().join("nested");
    let deeper = nested.join("deeper");
    fs::create_dir_all(&deeper).unwrap();
    for entry in fs::read_dir(&flat).unwrap() {
        let path = entry.unwrap().path();
        let name = path.file_name().unwrap();
        let to = if name.to_string_lossy().starts_with("hello_gcc") {
            deeper.join(name)
        } else {
            nested.join(name)
        };
        fs::copy(&path, &to).unwrap();
    }

    let files_seen = |recursive: bool| {
        let mut cmd = Command::cargo_bin("oinkie").unwrap();
        cmd.arg("stats").arg("-f").arg("json");
        if recursive {
            cmd.arg("-r");
        }
        let out = cmd
            .arg(&nested)
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let json: serde_json::Value = serde_json::from_slice(&out).unwrap();
        json["groups"][0]["files"].as_u64().unwrap()
    };

    assert_eq!(files_seen(false), 1, "the subdirectory was read without -r");
    assert_eq!(files_seen(true), 2, "-r did not reach the subdirectory");
}

/// A file that does not read as a birthmark is skipped rather than fatal, and
/// counted rather than silent -- so a summary never covers fewer files than it
/// was given without saying so. The reason names the file, which is what makes
/// the report actionable instead of merely honest.
#[test]
fn test_stats_counts_what_it_could_not_read() {
    let temp_dir = tempdir().unwrap();
    let dir = temp_dir.path().join("birthmarks");
    birthmarks_in(&dir);
    fs::write(dir.join("junk.json"), r#"{"not":"a birthmark"}"#).unwrap();

    let out = Command::cargo_bin("oinkie")
        .unwrap()
        .arg("stats")
        .arg("-f")
        .arg("json")
        .arg(&dir)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).unwrap();

    let skipped = json["skipped"].as_array().expect("no skipped array");
    assert_eq!(
        skipped.len(),
        1,
        "the unreadable file was not counted: {json}"
    );
    assert!(
        skipped[0]["path"].as_str().unwrap().ends_with("junk.json"),
        "the skip does not name the file: {json}"
    );
    assert_eq!(
        json["groups"][0]["files"], 2,
        "the readable files were affected: {json}"
    );
}

/// A lift that came back with no functions succeeds, and warns.
///
/// The quieter counterpart of the test above. `EmptyLifter` writes a file
/// oinkie reads without complaint and that holds nothing, which is what a
/// Ghidra missing its decompiler native binary produces -- and also
/// what a binary with genuinely no functions would produce. oinkie cannot tell
/// the two apart, so it says what it sees and goes on.
///
/// End to end because the warning is the whole deliverable: it has to reach a
/// person's terminal, which no unit test of the message can show.
#[test]
#[serial(ghidra)]
fn test_a_lift_that_found_no_functions_warns_and_succeeds() {
    let temp_dir = tempdir().unwrap();
    let dest = temp_dir.path().join("lifted");

    Command::cargo_bin("oinkie")
        .unwrap()
        .arg("lift")
        .arg("--script")
        .arg("testdata/scripts/EmptyLifter.java")
        .arg("-d")
        .arg(&dest)
        .arg("testdata/bin/hello_clang")
        .assert()
        .success()
        // the binary the person asked about, with the colon that follows it
        .stderr(predicate::str::contains("testdata/bin/hello_clang:"))
        .stderr(predicate::str::contains("no functions"))
        // both readings, because oinkie cannot choose between them
        .stderr(predicate::str::contains("really has no functions"))
        .stderr(predicate::str::contains("the tool found none"));

    // and the file is there to be used, which is what "succeeds" has to mean
    assert!(
        dest.join("hello_clang.json").exists(),
        "the lift warned and then kept nothing"
    );
}