whittle 1.0.0

Coordinate-consistent trimming of long-read uBAM and tagged FASTQ
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
//! CLI behavior over the compiled binary: argument validation, logging modes,
//! guardrail warnings, and the failure path.

use std::io::Read as _;
use std::path::Path;
use std::process::Stdio;

use assert_cmd::Command;
use predicates::prelude::*;

/// The binary with `WHITTLE_LOG` cleared, so the environment does not change
/// the log mode.
fn whittle() -> Command {
    let mut cmd = Command::cargo_bin("whittle").unwrap();
    cmd.env_remove("WHITTLE_LOG");
    cmd
}

/// One 20-bp Q40 read.
const READS: &str = "@r1\nACGTACGTACGTACGTACGT\n+\nIIIIIIIIIIIIIIIIIIII\n";

#[test]
fn version_is_long_only() {
    whittle()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));

    whittle()
        .arg("-V")
        .assert()
        .failure()
        .stderr(predicate::str::contains("unexpected argument '-V'"));
}

#[test]
fn verbosity_above_trace_is_rejected() {
    whittle()
        .args(["-vvv", "--input-format", "fastq"])
        .write_stdin("")
        .assert()
        .failure()
        .stderr(predicate::str::contains("accepts at most -vv"));
}

#[test]
fn head_tail_crop_over_stdin() {
    for (front, tail) in [
        ("--trim-front", "--trim-tail"),
        ("--head-crop", "--tail-crop"),
        ("--trim-front", "--tail-crop"),
        ("--head-crop", "--trim-tail"),
        ("-H", "-T"),
    ] {
        whittle()
            .args([front, "1", tail, "1", "--input-format", "fastq"])
            .write_stdin("@r1\nACGT\n+\nIIII\n")
            .assert()
            .success()
            .stdout("@r1\nCG\n+\nII\n");
    }
}

#[test]
fn quality_mode_filters_segments_without_changing_split_locations() {
    let input = "@r1\nACGTACGTACG\n+\nII#II##IIII\n";
    let split = "@r1_segment_1\nACGTA\n+\nII#II\n@r1_segment_2\nTACG\n+\nIIII\n";
    for mode in ["mean", "arithmetic", "median"] {
        whittle()
            .args([
                "--quality-trim",
                "runs",
                "--quality-cutoff",
                "9",
                "--min-low-quality-run",
                "2",
                "--quality-mode",
                mode,
                "--threads",
                "1",
                "--quiet",
            ])
            .write_stdin(input)
            .assert()
            .success()
            .stdout(split);

        let expected = if mode == "mean" {
            "@r1_segment_2\nTACG\n+\nIIII\n"
        } else {
            split
        };
        whittle()
            .args([
                "--quality-trim",
                "runs",
                "--quality-cutoff",
                "9",
                "--min-low-quality-run",
                "2",
                "--quality-mode",
                mode,
                "--min-quality",
                "12",
                "--threads",
                "1",
                "--quiet",
            ])
            .write_stdin(input)
            .assert()
            .success()
            .stdout(expected);
    }
}

/// `--quality-trim`, `--quality-cutoff` and `--min-low-quality-run` are
/// accepted only together as documented.
#[test]
fn quality_trim_flag_combinations_are_validated() {
    for (args, message) in [
        (
            &["--quality-trim", "ends"][..],
            "--quality-trim requires --quality-cutoff",
        ),
        (
            &["--quality-cutoff", "10"],
            "--quality-cutoff requires --quality-trim",
        ),
        (
            &[
                "--quality-trim",
                "best",
                "--quality-cutoff",
                "10",
                "--min-low-quality-run",
                "5",
            ],
            "--min-low-quality-run requires --quality-trim runs",
        ),
        (
            &[
                "--quality-trim",
                "runs",
                "--quality-cutoff",
                "10",
                "--min-low-quality-run",
                "0",
            ],
            "--min-low-quality-run must be at least 1",
        ),
        (
            &["--quality-trim", "middle", "--quality-cutoff", "10"],
            "invalid value",
        ),
        (
            &[
                "--quality-trim",
                "ends",
                "--quality-cutoff",
                "10",
                "--quality-end-cutoff",
                "20",
            ],
            "--quality-end-cutoff requires --quality-trim segments or runs",
        ),
        (
            &[
                "--quality-trim",
                "best",
                "--quality-cutoff",
                "10",
                "--quality-end-cutoff",
                "20",
            ],
            "--quality-end-cutoff requires --quality-trim segments or runs",
        ),
        (
            &["--quality-end-cutoff", "20"],
            "--quality-end-cutoff requires --quality-trim segments or runs",
        ),
    ] {
        whittle()
            .args(args)
            .args(["--input-format", "fastq"])
            .write_stdin("@r1\nACGT\n+\nIIII\n")
            .assert()
            .failure()
            .stderr(predicate::str::contains(message));
    }
}

#[test]
fn min_length_filters() {
    whittle()
        .args(["--min-length", "10", "--input-format", "fastq"])
        .write_stdin("@short\nACGT\n+\nIIII\n")
        .assert()
        .success()
        .stdout(""); // filtered out
}

/// Streaming the input while `File::create` truncates it destroys the data. The
/// run fails up front with one `Failed after` line and leaves the input
/// untouched.
#[test]
fn same_input_output_file_is_rejected_and_preserves_input() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("reads.fastq");
    std::fs::write(&path, "@r1\nACGT\n+\nIIII\n@r2\nTTTT\n+\nIIII\n").unwrap();
    let before = std::fs::read(&path).unwrap();

    let assert = whittle()
        .arg("-i")
        .arg(&path)
        .arg("-o")
        .arg(&path)
        .assert()
        .failure()
        .stderr(predicate::str::contains("same file"));
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr);
    assert_eq!(
        stderr.matches("Failed after").count(),
        1,
        "Exactly one failure line is printed: {stderr}"
    );

    assert_eq!(
        std::fs::read(&path).unwrap(),
        before,
        "Input must not be modified"
    );
}

#[test]
fn contradictory_length_bounds_error() {
    whittle()
        .args(["-l", "10", "-L", "5", "--input-format", "fastq"])
        .write_stdin("@r1\nACGTACGTAC\n+\nIIIIIIIIII\n")
        .assert()
        .failure()
        .stderr(predicate::str::contains("min-length"));
}

#[test]
fn contradictory_qual_bounds_error() {
    whittle()
        .args(["-q", "30", "-Q", "20", "--input-format", "fastq"])
        .write_stdin("@r1\nACGT\n+\nIIII\n")
        .assert()
        .failure()
        .stderr(predicate::str::contains("min-qual"));
}

#[test]
fn out_of_range_gc_bound_errors() {
    whittle()
        .args(["--min-gc", "2", "--input-format", "fastq"])
        .write_stdin("@r1\nACGT\n+\nIIII\n")
        .assert()
        .failure()
        .stderr(predicate::str::contains("min-gc"));
}

/// NaN slips past `min > max` (every NaN comparison is false) and would disable
/// quality filtering, so it is rejected explicitly.
#[test]
fn nan_quality_bound_errors() {
    whittle()
        .args(["--min-quality", "nan", "--input-format", "fastq"])
        .write_stdin("@r1\nACGT\n+\nIIII\n")
        .assert()
        .failure()
        .stderr(predicate::str::contains("NaN"));
}

/// How a run ends for one argument set.
enum Expect {
    /// Exit non-zero with the substring on stderr.
    Fails,
    /// Exit zero with the substring on stderr.
    Warns,
}

/// Every validation and advisory names the flag it concerns, so the offending
/// argument is identifiable from the message alone.
#[test]
fn every_validation_names_its_flag() {
    use std::io::Write as _;

    let dir = tempfile::tempdir().unwrap();
    let fastq = dir.path().join("reads.fastq");
    std::fs::write(&fastq, READS).unwrap();
    // gzip bytes behind a plain `.fastq` name, so `--input-format fastq-gz` is right
    // and the extension is the one that looks wrong.
    let misnamed_gz = dir.path().join("misnamed.fastq");
    let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
    enc.write_all(READS.as_bytes()).unwrap();
    std::fs::write(&misnamed_gz, enc.finish().unwrap()).unwrap();
    let folder = dir.path().join("folder");
    std::fs::create_dir(&folder).unwrap();
    std::fs::write(folder.join("a.fastq"), READS).unwrap();
    let missing = dir.path().join("no-such-adapters.fasta");
    let p = |path: &Path| path.to_str().unwrap().to_string();

    let cases: Vec<(Vec<String>, Expect, &str)> = vec![
        (
            vec!["--compression-level".into(), "10".into()],
            Expect::Fails,
            "--compression-level",
        ),
        (
            vec!["--max-gc".into(), "1.5".into()],
            Expect::Fails,
            "--max-gc (1.5) must be a fraction",
        ),
        (
            vec![
                "--min-gc".into(),
                "0.8".into(),
                "--max-gc".into(),
                "0.2".into(),
            ],
            Expect::Fails,
            "--min-gc (0.8) must not exceed --max-gc",
        ),
        (
            vec!["--max-quality".into(), "nan".into()],
            Expect::Fails,
            "NaN",
        ),
        (
            vec!["--min-quality=-5".into()],
            Expect::Fails,
            "--min-quality (-5) must be a finite quality",
        ),
        (
            vec!["--max-expected-errors=-0.5".into()],
            Expect::Fails,
            "--max-expected-errors (-0.5) must be a finite number of at least 0",
        ),
        (
            vec!["--max-expected-errors".into(), "nan".into()],
            Expect::Fails,
            "--max-expected-errors (NaN) must be a finite number",
        ),
        (
            vec!["--max-quality".into(), "inf".into()],
            Expect::Fails,
            "--max-quality (inf) must be a finite quality",
        ),
        (vec!["-t".into(), "0".into()], Expect::Fails, "--threads"),
        (
            vec!["--fastq-tags".into(), "MM,ABC".into()],
            Expect::Fails,
            "--fastq-tags: invalid tag",
        ),
        (
            vec!["--min-low-quality-run".into(), "5".into()],
            Expect::Fails,
            "--min-low-quality-run requires --quality-trim runs",
        ),
        (
            vec!["--progress".into(), "bar".into(), "--quiet".into()],
            Expect::Fails,
            "cannot be used with",
        ),
        (
            vec!["--adapter-fasta".into(), p(&missing)],
            Expect::Fails,
            "--adapter-fasta",
        ),
        (
            vec![
                "--adapter-preset".into(),
                "ont".into(),
                "--adapter-end-search".into(),
                "0".into(),
            ],
            Expect::Fails,
            "--adapter-end-search must be >= 1",
        ),
        (
            vec![
                "--adapter-discover".into(),
                "--adapter-sample-reads".into(),
                "0".into(),
            ],
            Expect::Fails,
            "--adapter-sample-reads 0 disables sampling",
        ),
        (
            vec!["--adapter-error-rate".into(), "0.5".into()],
            Expect::Fails,
            "--adapter-error-rate requires an adapter source",
        ),
        (
            vec!["--adapter-end-search".into(), "50".into()],
            Expect::Fails,
            "--adapter-end-search requires an adapter source",
        ),
        (
            vec!["--adapter-sample-reads".into(), "50".into()],
            Expect::Fails,
            "--adapter-sample-reads requires an adapter source",
        ),
        (
            vec![
                "-i".into(),
                p(&misnamed_gz),
                "--input-format".into(),
                "fastq-gz".into(),
                "-o".into(),
                p(&dir.path().join("out_in_mismatch.fastq")),
            ],
            Expect::Warns,
            "--input-format",
        ),
        (
            vec![
                "-i".into(),
                p(&fastq),
                "-o".into(),
                p(&dir.path().join("out_out_mismatch.fastq.gz")),
                "--output-format".into(),
                "fastq".into(),
            ],
            Expect::Warns,
            "--output-format",
        ),
        (
            vec![
                "-i".into(),
                p(&folder),
                "--input-format".into(),
                "fastq".into(),
                "-o".into(),
                p(&dir.path().join("out_folder.fastq")),
            ],
            Expect::Warns,
            "--input-format is ignored for a directory input",
        ),
        (
            vec![
                "-i".into(),
                p(&fastq),
                "-o".into(),
                p(&dir.path().join("out_noop.fastq")),
            ],
            Expect::Warns,
            "No trimming or filtering options set",
        ),
        (
            vec![
                "-i".into(),
                p(&fastq),
                "-o".into(),
                p(&dir.path().join("out.bam")),
            ],
            Expect::Fails,
            "FASTQ-to-BAM conversion is not supported",
        ),
        (
            vec![
                "-i".into(),
                p(&fastq),
                "-o".into(),
                p(&dir.path().join("out_sum.fastq")),
                "--summary-json".into(),
                p(dir.path()),
            ],
            Expect::Fails,
            "--summary-json",
        ),
    ];

    for (args, expect, needle) in cases {
        let mut cmd = whittle();
        cmd.args(&args);
        if !args.iter().any(|a| a == "-i") {
            cmd.args(["--input-format", "fastq"]).write_stdin(READS);
        }
        let output = cmd.output().unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr);
        match expect {
            Expect::Fails => assert!(
                !output.status.success(),
                "Case {args:?} must fail: {stderr}"
            ),
            Expect::Warns => assert!(
                output.status.success(),
                "Case {args:?} must succeed: {stderr}"
            ),
        }
        assert!(
            stderr.contains(needle),
            "Case {args:?}: stderr lacks {needle:?}: {stderr}"
        );
    }
}

/// A missing input names its path, so a command line with several paths on it
/// says which one is wrong.
#[test]
fn missing_input_error_names_the_path() {
    let dir = tempfile::tempdir().unwrap();
    let missing = dir.path().join("nonexistent.fastq");
    whittle()
        .arg("-i")
        .arg(&missing)
        .args(["-o", dir.path().join("out.fastq").to_str().unwrap()])
        .assert()
        .failure()
        .stderr(predicate::str::contains("opening input"))
        .stderr(predicate::str::contains("nonexistent.fastq"));
}

/// An unparseable `WHITTLE_LOG` does not disable logging: the level falls back
/// to the default, the failure line still prints, and the rejected directive is
/// named.
#[test]
fn invalid_whittle_log_falls_back_and_still_reports_the_failure() {
    let dir = tempfile::tempdir().unwrap();
    let missing = dir.path().join("nonexistent.fastq");
    whittle()
        .env("WHITTLE_LOG", "garbage=nope=1")
        .arg("-i")
        .arg(&missing)
        .args(["-o", dir.path().join("out.fastq").to_str().unwrap()])
        .assert()
        .failure()
        .stderr(predicate::str::contains("Failed after"))
        .stderr(predicate::str::contains("WHITTLE_LOG"))
        .stderr(predicate::str::contains("garbage=nope=1"));
}

/// `-` is the pipeline spelling of stdin and stdout; no file named `-` appears.
#[test]
fn dash_means_stdin_and_stdout() {
    let dir = tempfile::tempdir().unwrap();
    whittle()
        .current_dir(dir.path())
        .args(["-i", "-", "-o", "-", "--input-format", "fastq", "-l", "5"])
        .write_stdin(READS)
        .assert()
        .success()
        .stdout(READS)
        .stderr(predicate::str::contains("Input: <stdin>"))
        .stderr(predicate::str::contains("Output: <stdout>"));
    assert!(
        !dir.path().join("-").exists(),
        "No file named - may be created"
    );
}

/// A downstream reader that stops early (`whittle ... | head`) is not a failure
/// of this run: the process exits 0 without a `Failed after` line.
#[test]
fn downstream_closing_the_pipe_exits_quietly() {
    let dir = tempfile::tempdir().unwrap();
    let input = dir.path().join("reads.fastq");
    // Well past the pipe buffer, so writes are still in flight when the reader
    // goes away.
    std::fs::write(&input, READS.repeat(40_000)).unwrap();

    for threads in [&["-t", "1"][..], &[][..]] {
        let mut child = std::process::Command::new(assert_cmd::cargo::cargo_bin("whittle"))
            .env_remove("WHITTLE_LOG")
            .args(["-i", input.to_str().unwrap()])
            .args(threads)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        let mut stdout = child.stdout.take().unwrap();
        let mut head = [0u8; 100];
        stdout.read_exact(&mut head).unwrap();
        drop(stdout);

        let output = child.wait_with_output().unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            output.status.success(),
            "A closed pipe exits 0 ({threads:?}): {stderr}"
        );
        assert!(
            !stderr.contains("Failed after"),
            "A closed pipe is not reported as a failure ({threads:?}): {stderr}"
        );
    }
}

/// Two hard links to one inode canonicalize to distinct paths, so only the inode
/// and device check catches this; otherwise `File::create` truncates the input.
#[test]
#[cfg(unix)]
fn hard_linked_input_output_is_rejected_and_preserves_input() {
    let dir = tempfile::tempdir().unwrap();
    let input = dir.path().join("in.fastq");
    let output = dir.path().join("out.fastq");
    std::fs::write(&input, "@r1\nACGT\n+\nIIII\n@r2\nTTTT\n+\nIIII\n").unwrap();
    std::fs::hard_link(&input, &output).unwrap();
    let before = std::fs::read(&input).unwrap();

    whittle()
        .arg("-i")
        .arg(&input)
        .arg("-o")
        .arg(&output)
        .assert()
        .failure()
        .stderr(predicate::str::contains("same file"));

    assert_eq!(
        std::fs::read(&input).unwrap(),
        before,
        "Hard-linked input must be preserved"
    );
}

/// A default run prints the `Summary:` line to stderr; `--quiet` drops it and
/// keeps the reads on stdout.
#[test]
fn quiet_suppresses_summary_but_keeps_stdout() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .arg("--quiet")
        .write_stdin(input)
        .assert()
        .success()
        .stdout(predicate::str::contains("@r1"))
        .stderr(predicate::str::contains("Summary:").not());
}

#[test]
fn default_run_prints_summary_to_stderr() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle().write_stdin(input).assert().success().stderr(
        predicate::str::contains("Summary:")
            .and(predicate::str::contains("input reads"))
            .and(predicate::str::contains("output reads")),
    );
}

#[test]
fn over_spec_threads_warns() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .args(["-t", "100000"])
        .write_stdin(input)
        .assert()
        .success()
        .stderr(predicate::str::contains("exceeds").and(predicate::str::contains("using")));
}

#[test]
fn verbose_shows_phase_timing() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .arg("-v")
        .write_stdin(input)
        .assert()
        .success()
        .stderr(predicate::str::contains("Processing started")); // the phase timing line appears at DEBUG
}

#[test]
fn default_hides_debug() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .write_stdin(input)
        .assert()
        .success()
        .stderr(predicate::str::contains("Processing started").not());
}

/// `--quiet` wins even when `WHITTLE_LOG` asks for verbose output.
#[test]
fn quiet_beats_whittle_log() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .env("WHITTLE_LOG", "debug")
        .arg("--quiet")
        .write_stdin(input)
        .assert()
        .success()
        .stdout(predicate::str::contains("@r1"))
        .stderr(predicate::str::contains("Summary:").not());
}

/// Without `--quiet`, `WHITTLE_LOG` raises the level above the CLI default.
#[test]
fn whittle_log_overrides_verbosity_when_not_quiet() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .env("WHITTLE_LOG", "debug")
        .write_stdin(input)
        .assert()
        .success()
        .stderr(predicate::str::contains("Processing started"));
}

/// assert_cmd captures stderr to a pipe (non-TTY), so the run is in line mode
/// regardless of verbosity. The full startup banner and the `Completed` closer
/// appear in order.
#[test]
fn line_mode_banner_and_closer_appear_in_order() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle().write_stdin(input).assert().success().stderr(
        predicate::str::contains("whittle ")
            .and(predicate::str::contains("Command:"))
            .and(predicate::str::contains("Trimming"))
            .and(predicate::str::contains("Input: <stdin>"))
            .and(predicate::str::contains("Output: <stdout>"))
            .and(predicate::str::contains("Threads:"))
            .and(predicate::str::contains("Filters:"))
            .and(predicate::str::contains("Summary:"))
            .and(predicate::str::contains("Completed in")),
    );
}

/// The version and command lines precede the resolved configuration and the
/// diagnostics.
#[test]
fn banner_version_and_command_come_first_in_line_mode() {
    let input = "@r1\nACGT\n+\nIIII\n";
    let assert = whittle().write_stdin(input).assert().success();
    let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
    let version_pos = stderr.find("whittle ").expect("Version line present");
    let command_pos = stderr.find("Command:").expect("Command line present");
    let operation_pos = stderr.find("Trimming").expect("Operation line present");
    assert!(
        version_pos < command_pos && command_pos < operation_pos,
        "Expected version, then Command:, then the operation line, in order: {stderr:?}"
    );
}

/// Captured stderr is non-interactive and contains no ANSI escapes.
#[test]
fn non_tty_stderr_has_no_ansi_escapes() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .write_stdin(input)
        .assert()
        .success()
        .stderr(predicate::str::contains("\u{1b}").not());
}

/// Every read fails an unreachable min-qual bound: nothing survives, and the run
/// succeeds. The all-dropped guardrail WARN fires so the run is distinguishable
/// from a clean empty-output run.
#[test]
fn all_dropped_run_warns() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .args(["-q", "50", "--input-format", "fastq"])
        .write_stdin(input)
        .assert()
        .success()
        .stderr(
            predicate::str::contains("No reads survived")
                .and(predicate::str::contains("every input read was dropped")),
        );
}

/// Zero input reads is not an error, and the empty-input guardrail WARN still
/// fires.
#[test]
fn empty_bgzf_stream_is_empty_input() {
    let eof_block: &[u8] = &[
        0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43, 0x02,
        0x00, 0x1b, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    ];
    whittle()
        .write_stdin(eof_block)
        .assert()
        .success()
        .stderr(predicate::str::contains("Input contained no reads"));
}

#[test]
fn empty_input_warns() {
    whittle()
        .args(["--input-format", "fastq"])
        .write_stdin("")
        .assert()
        .success()
        .stderr(predicate::str::contains("Input contained no reads"));
}

#[test]
fn sequential_threads_label_for_dash_t_1() {
    let input = "@r1\nACGT\n+\nIIII\n";
    whittle()
        .args(["-t", "1"])
        .write_stdin(input)
        .assert()
        .success()
        .stderr(predicate::str::contains("Threads: 1 (sequential)"));
}

#[test]
fn bam_to_fastq_conversion_phrasing() {
    use noodles_bam as bam;
    use noodles_sam::alignment::RecordBuf;
    use noodles_sam::alignment::io::Write as _;
    use noodles_sam::alignment::record::Flags;
    use noodles_sam::{self as sam};

    let dir = tempfile::tempdir().unwrap();
    let inp = dir.path().join("in.bam");
    let out = dir.path().join("o.fastq");

    // A minimal one-read uBAM built in the tempdir keeps the test hermetic.
    let header = sam::Header::default();
    let mut w = bam::io::Writer::new(std::fs::File::create(&inp).unwrap());
    w.write_header(&header).unwrap();
    let mut rec = RecordBuf::default();
    *rec.flags_mut() = Flags::UNMAPPED;
    *rec.name_mut() = Some(b"r1".into());
    *rec.sequence_mut() = b"ACGTACGTAC".to_vec().into();
    *rec.quality_scores_mut() = vec![40; 10].into();
    w.write_alignment_record(&header, &rec).unwrap();
    w.try_finish().unwrap();

    whittle()
        .arg("-i")
        .arg(&inp)
        .arg("-o")
        .arg(&out)
        .assert()
        .success()
        .stderr(predicate::str::contains("Converting BAM to FASTQ"));
}

#[test]
fn gz_output_roundtrips() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.fastq.gz");
    whittle()
        .args(["--input-format", "fastq", "-o"])
        .arg(&out)
        .write_stdin("@r1\nACGT\n+\nIIII\n")
        .assert()
        .success();
    let mut gz = flate2::read::MultiGzDecoder::new(std::fs::File::open(&out).unwrap());
    let mut s = String::new();
    gz.read_to_string(&mut s).unwrap();
    assert_eq!(s, "@r1\nACGT\n+\nIIII\n");
}

#[test]
fn forced_in_format_is_checked_against_the_stream() {
    let dir = tempfile::tempdir().unwrap();
    let input = dir.path().join("reads.fastq");
    std::fs::write(&input, READS).unwrap();
    for (forced, detected) in [
        ("fastq-bgz", "FASTQ"),
        ("bam", "FASTQ"),
        ("fastq-gz", "FASTQ"),
    ] {
        whittle()
            .args([
                "-i",
                input.to_str().unwrap(),
                "--input-format",
                forced,
                "--quiet",
            ])
            .assert()
            .failure()
            .stderr(predicates::str::contains(format!(
                "but the input is {detected}"
            )))
            .stderr(predicates::str::contains("pass --input-format fastq"));
    }
    // A matching forced format and an empty input both run.
    whittle()
        .args([
            "-i",
            input.to_str().unwrap(),
            "--input-format",
            "fastq",
            "--quiet",
        ])
        .assert()
        .success()
        .stdout(READS);
    let empty = dir.path().join("empty.fastq");
    std::fs::write(&empty, "").unwrap();
    whittle()
        .args([
            "-i",
            empty.to_str().unwrap(),
            "--input-format",
            "fastq",
            "--quiet",
        ])
        .assert()
        .success()
        .stdout("");
}

#[test]
fn unknown_output_extension_is_reported() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.fasta");
    whittle()
        .args([
            "-o",
            out.to_str().unwrap(),
            "--input-format",
            "fastq",
            "-l",
            "5",
        ])
        .write_stdin(READS)
        .assert()
        .success()
        .stderr(predicates::str::contains(
            "extension .fasta names no supported format; writing FASTQ",
        ));
    assert_eq!(std::fs::read_to_string(&out).unwrap(), READS);
}

#[test]
fn fastq_to_bam_is_rejected_before_the_run() {
    whittle()
        .args(["-i", "reads.fastq", "-o", "out.bam"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicates::str::contains(
            "FASTQ-to-BAM conversion is not supported",
        ))
        .stderr(predicates::str::contains("Input:").not());
}

#[test]
fn piped_fastq_to_bam_is_rejected_before_the_run() {
    whittle()
        .args(["-o", "out.bam"])
        .write_stdin("@r1\nACGTACGTAC\n+\nIIIIIIIIII\n")
        .assert()
        .failure()
        .stderr(predicates::str::contains(
            "FASTQ-to-BAM conversion is not supported (a FASTQ read carries no header",
        ))
        .stderr(predicates::str::contains("Input:").not());
}

#[test]
fn update_moves_requires_bam_input() {
    whittle()
        .args(["-i", "reads.fastq", "--update-moves"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicates::str::contains(
            "--update-moves rewrites the ONT signal tags of BAM records and requires BAM input",
        ));
}

#[test]
fn zero_threads_names_the_floor() {
    whittle()
        .args(["-t", "0", "--input-format", "fastq"])
        .write_stdin(READS)
        .assert()
        .failure()
        .stderr(predicates::str::contains("must be at least 1"))
        .stderr(predicates::str::contains("18446744073709551615").not());
}

/// The paraseq parser writes what the seq_io parser writes over reads long
/// enough that a record set holds only a few of them.
#[cfg(feature = "paraseq")]
#[test]
fn paraseq_parser_matches_seq_io_on_long_reads() {
    let mut fastq = String::new();
    for i in 0..40usize {
        let seq: String = (0..200_000)
            .map(|j| ['A', 'C', 'G', 'T'][(i * 7 + j * j) % 4])
            .collect();
        fastq.push_str(&format!("@long{i}\n{seq}\n+\n{}\n", "I".repeat(seq.len())));
    }
    let run = |parser: &str| {
        whittle()
            .env("WHITTLE_FASTQ_PARSER", parser)
            .args(["-t", "4", "--preserve-order", "--quiet", "-H", "5"])
            .args(["--input-format", "fastq"])
            .write_stdin(fastq.clone())
            .assert()
            .success()
            .get_output()
            .stdout
            .clone()
    };
    let paraseq = run("paraseq");
    assert_eq!(paraseq.iter().filter(|&&b| b == b'@').count(), 40);
    assert!(paraseq == run("seq_io"), "The parsers disagree");
}