rasusa 4.0.0

Randomly subsample reads or alignments
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
use crate::cli::{
    check_path_exists, parse_compression_format, parse_fraction, parse_level, CliError, Coverage,
    GenomeSize,
};
use crate::fastx::create_output_writer;
use crate::source::determine_record_source;
use crate::{Runner, SubSampler};
use anyhow::{Context, Result};
use clap::Parser;
use log::{debug, error, info, warn};
use niffler::compression;
use std::io::stdout;
use std::path::{Path, PathBuf};

#[derive(Debug, Parser)]
#[command(author, version, about)]
pub struct Reads {
    /// The FASTA/FASTQ or unaligned SAM/BAM/CRAM file(s) to subsample.
    ///
    /// For paired Illumina, the order matters. i.e., R1 then R2.
    /// Single-file paired-end is also supported for unaligned SAM/BAM/CRAM.
    #[arg(
    value_parser = check_path_exists,
    num_args = 1..=2,
    required = true,
    name = "FILE(S)"
    )]
    pub input: Vec<PathBuf>,

    /// Output filepath(s); stdout if not present.
    ///
    /// For paired Illumina pass this flag twice `-o o1.fq -o o2.fq`  
    ///
    /// NOTE: The order of the pairs is assumed to be the same as the input - e.g., R1 then R2.  
    ///
    /// This option is required for paired input.
    #[arg(short = 'o', long = "output", action = clap::ArgAction::Append)]
    pub output: Vec<PathBuf>,

    /// Genome size to calculate coverage with respect to. e.g., 4.3kb, 7Tb, 9000, 4.1MB
    ///
    /// Alternatively, a FASTA/Q index file can be provided and the genome size will be
    /// set to the sum of all reference sequences.
    ///
    /// If --bases is not provided, this option and --coverage are required
    #[clap(
    short,
    long,
    required_unless_present_any = &["bases", "num", "frac"],
    requires = "coverage",
    value_name = "size|faidx",
    conflicts_with_all = &["num", "frac"]
    )]
    pub genome_size: Option<GenomeSize>,

    /// The desired depth of coverage to subsample the reads to
    ///
    /// If --bases is not provided, this option and --genome-size are required
    #[clap(
    short,
    long,
    value_name = "FLOAT",
    required_unless_present_any = &["bases", "num", "frac"],
    requires = "genome_size",
    conflicts_with_all = &["num", "frac"]
    )]
    pub coverage: Option<Coverage>,

    /// Explicitly set the number of bases required e.g., 4.3kb, 7Tb, 9000, 4.1MB
    ///
    /// If this option is given, --coverage and --genome-size are ignored
    #[clap(short, long, value_name = "bases", conflicts_with_all = &["num", "frac"])]
    pub bases: Option<GenomeSize>,

    /// Subsample to a specific number of reads
    ///
    /// If paired-end reads are passed, this is the number of (matched) reads from EACH file.
    /// This option accepts the same format as genome size - e.g., 1k will take 1000 reads
    #[clap(short, long, value_name = "INT", conflicts_with = "frac")]
    pub num: Option<GenomeSize>,

    /// Subsample to a fraction of the reads - e.g., 0.5 samples half the reads
    ///
    /// Values >1 and <=100 will be automatically converted - e.g., 25 => 0.25
    #[clap(short, long, value_name = "FLOAT", value_parser = parse_fraction, conflicts_with = "num")]
    pub frac: Option<f32>,

    /// Exit with an error if the requested coverage/bases/reads is not possible
    #[clap(short = 'e', long)]
    pub strict: bool,

    /// Random seed to use.
    #[clap(short = 's', long = "seed", value_name = "INT")]
    pub seed: Option<u64>,

    /// Switch on verbosity.
    #[clap(short)]
    pub verbose: bool,

    /// u: uncompressed; b: Bzip2; g: Gzip; l: Lzma; x: Xz (Lzma); z: Zstd
    ///
    /// Rasusa will attempt to infer the output compression format automatically from the filename
    /// extension. This option is used to override that. If writing to stdout, the default is
    /// uncompressed. Note: this is only used for FASTA/FASTQ output.
    #[clap(short = 'Z', long = "compress-type", value_name = "u|b|g|l|x|z", value_parser = parse_compression_format)]
    pub compress_type: Option<niffler::compression::Format>,

    /// Explicitly set the output format.
    ///
    /// If not provided, Rasusa will attempt to infer the format from the filename extension.
    #[clap(short = 'O', long = "output-format", value_enum)]
    pub output_format: Option<crate::cli::OutputFormat>,

    /// Compression level to use if compressing output. Uses the default level for the format if
    /// not specified.
    #[clap(short = 'l', long, value_parser = parse_level, value_name = "1-21")]
    pub compress_level: Option<niffler::Level>,
}

impl Reads {
    /// Checks there is a valid and equal number of `--input` and `--output` arguments given.
    ///
    /// # Errors
    /// A [`CliError::BadInputOutputCombination`](#clierror) is returned for the following:
    /// - Either `--input` or `--output` are passed more than twice
    /// - An unequal number of `--input` and `--output` are passed. The only exception to
    ///   this is if one `--input` and zero `--output` are passed, in which case, the output
    ///   will be sent to STDOUT.
    pub fn validate_input_output_combination(&self) -> std::result::Result<(), CliError> {
        let out_len = self.output.len();
        let in_len = self.input.len();

        if in_len > 2 {
            let msg = String::from("Got more than 2 files for input.");
            return Err(CliError::BadInputOutputCombination(msg));
        }
        if out_len > 2 {
            let msg = String::from("Got more than 2 files for output.");
            return Err(CliError::BadInputOutputCombination(msg));
        }
        match in_len as isize - out_len as isize {
            diff if diff == 1 && in_len == 1 => Ok(()),
            diff if diff != 0 => Err(CliError::BadInputOutputCombination(format!(
                "Got {in_len} --input but {out_len} --output"
            ))),
            _ => Ok(()),
        }
    }
}

impl Runner for Reads {
    fn run(&mut self) -> Result<()> {
        self.validate_input_output_combination()?;
        let is_paired = self.input.len() == 2;
        if is_paired {
            info!("Two input files given. Assuming paired Illumina...")
        }

        let input_source = determine_record_source(&self.input[0]);
        let input_format = crate::alignment::infer_format_from_path(&self.input[0]);

        let check_conversion = |in_fmt: Option<noodles_util::alignment::io::Format>,
                                out_path: Option<&std::path::PathBuf>|
         -> Result<()> {
            if in_fmt.is_none() {
                let has_alignment_output = match &self.output_format {
                    Some(crate::cli::OutputFormat::Sam)
                    | Some(crate::cli::OutputFormat::Bam)
                    | Some(crate::cli::OutputFormat::Cram) => true,
                    _ => out_path
                        .map(|p| crate::alignment::infer_format_from_path(p).is_some())
                        .unwrap_or(false),
                };
                if has_alignment_output {
                    let out_fmt = match &self.output_format {
                        Some(crate::cli::OutputFormat::Sam) => {
                            noodles_util::alignment::io::Format::Sam
                        }
                        Some(crate::cli::OutputFormat::Bam) => {
                            noodles_util::alignment::io::Format::Bam
                        }
                        Some(crate::cli::OutputFormat::Cram) => {
                            noodles_util::alignment::io::Format::Cram
                        }
                        _ => crate::alignment::infer_format_from_path(out_path.unwrap()).unwrap(),
                    };
                    return Err(anyhow::anyhow!(
                        "Conversion from FASTA/FASTQ to {:?} is not supported. Please use FASTA/FASTQ output for FASTA/FASTQ input.",
                        out_fmt
                    ));
                }
            }
            Ok(())
        };

        check_conversion(input_format, self.output.first())?;
        if is_paired {
            let second_input_format = crate::alignment::infer_format_from_path(&self.input[1]);
            check_conversion(second_input_format, self.output.get(1))?;
        }

        let mut output_handle = match self.output.len() {
            0 => match self.compress_type {
                None => Box::new(stdout()) as Box<dyn std::io::Write>,
                Some(fmt) => {
                    let lvl = match fmt {
                        compression::Format::Gzip => compression::Level::Six,
                        compression::Format::Bzip => compression::Level::Nine,
                        compression::Format::Lzma => compression::Level::Six,
                        compression::Format::Zstd => compression::Level::Three,
                        _ => compression::Level::Zero,
                    };
                    niffler::basic::get_writer(Box::new(stdout()), fmt, lvl)?
                }
            },
            _ => create_output_writer(&self.output[0], self.compress_level, self.compress_type)
                .context("unable to create the first output file")?,
        };

        let target_total_bases: Option<u64> = match (self.genome_size, self.coverage, self.bases) {
            (_, _, Some(bases)) => Some(u64::from(bases)),
            (Some(gsize), Some(cov), _) => Some(gsize * cov),
            _ => None,
        };

        if let Some(bases) = target_total_bases {
            info!("Target number of bases to subsample to is: {bases}",);
        }

        info!("Gathering read lengths...");
        let mut read_lengths = input_source
            .read_lengths()
            .context("unable to gather read lengths for the first input file")?;

        if is_paired {
            let second_input_source = determine_record_source(&self.input[1]);
            let expected_num_reads = read_lengths.len();
            info!("Gathering read lengths for second input file...");
            let mate_lengths = second_input_source
                .read_lengths()
                .context("unable to gather read lengths for the second input file")?;

            if mate_lengths.len() != expected_num_reads {
                error!("First input has {} reads, but the second has {} reads. Paired Illumina files are assumed to have the same number of reads. The results of this subsample may not be as expected now.", expected_num_reads, read_lengths.len());
                std::process::exit(1);
            } else {
                info!(
                    "Both input files have the same number of reads ({}) 👍",
                    expected_num_reads
                );
            }
            // add the paired read lengths to the existing lengths
            for (i, len) in mate_lengths.iter().enumerate() {
                read_lengths[i] += len;
            }
        }
        info!("{} reads detected", read_lengths.len());

        // calculate the depth of coverage if using coverage-based subsampling
        if let Some(size) = self.genome_size {
            let number_of_bases: u64 = read_lengths.iter().map(|&x| x as u64).sum();
            let depth_of_covg = (number_of_bases as f64) / f64::from(size);
            info!("Input coverage is {:.2}x", depth_of_covg);

            if self.strict
                && target_total_bases.is_some()
                && Coverage(depth_of_covg as f32) < self.coverage.unwrap()
            {
                return Err(anyhow::anyhow!(
                    "Requested coverage ({:.2}x) is not possible as the actual coverage is {:.2}x",
                    self.coverage.unwrap().0,
                    depth_of_covg
                ));
            }
        }

        if let Some(req_bases) = self.bases {
            let total_bases: u64 = read_lengths.iter().map(|&x| x as u64).sum();
            let req_bases = u64::from(req_bases);
            if self.strict && req_bases > total_bases {
                return Err(anyhow::anyhow!(
                    "Requested number of bases ({}) is more than the input ({})",
                    req_bases,
                    total_bases
                ));
            }
        }

        let num_reads = match (self.num, self.frac) {
            (Some(n), None) => Some(u64::from(n)),
            (None, Some(f)) => {
                let n = ((f as f64) * (read_lengths.len() as f64)).round() as u64;
                if n == 0 {
                    if !self.strict {
                        warn!(
                            "Requested fraction of reads ({} * {}) was rounded to 0",
                            f,
                            read_lengths.len()
                        );
                    } else {
                        return Err(anyhow::anyhow!(
                            "Requested fraction of reads ({} * {}) was rounded to 0",
                            f,
                            read_lengths.len()
                        ));
                    }
                }
                Some(n)
            }
            _ => None,
        };

        if let Some(n) = num_reads {
            if self.strict && n as usize > read_lengths.len() {
                return Err(anyhow::anyhow!(
                    "Requested number of reads ({}) is more than the input ({})",
                    n,
                    read_lengths.len()
                ));
            }
            info!("Target number of reads to subsample to is: {}", n);
        }

        let subsampler = SubSampler {
            target_total_bases,
            seed: self.seed,
            num_reads,
        };

        let (reads_to_keep, nb_reads_to_keep) = subsampler.indices(&read_lengths);
        if is_paired {
            info!("Keeping {} reads from each input", nb_reads_to_keep);
        } else {
            info!("Keeping {} reads", nb_reads_to_keep);
        }
        debug!("Indices of reads being kept:\n{:?}", reads_to_keep);

        let output_format_1 = match &self.output_format {
            Some(crate::cli::OutputFormat::Sam) => Some(noodles_util::alignment::io::Format::Sam),
            Some(crate::cli::OutputFormat::Bam) => Some(noodles_util::alignment::io::Format::Bam),
            Some(crate::cli::OutputFormat::Cram) => Some(noodles_util::alignment::io::Format::Cram),
            Some(crate::cli::OutputFormat::Fasta) | Some(crate::cli::OutputFormat::Fastq) => None,
            None => {
                if self.output.is_empty() {
                    input_format
                } else {
                    crate::alignment::infer_format_from_path(&self.output[0])
                }
            }
        };

        let is_fasta_1 = match self.output_format {
            Some(crate::cli::OutputFormat::Fasta) => true,
            Some(crate::cli::OutputFormat::Fastq) => false,
            _ => {
                if self.output.is_empty() {
                    is_fasta_path(&self.input[0])
                } else {
                    is_fasta_path(&self.output[0])
                }
            }
        };

        let mut total_kept_bases = input_source.filter_reads_into(
            &reads_to_keep,
            nb_reads_to_keep,
            &mut output_handle,
            output_format_1,
            is_fasta_1,
        )? as u64;

        // repeat the same process for the second input (if illumina)
        if is_paired {
            let second_input_source = determine_record_source(&self.input[1]);
            let second_input_format = crate::alignment::infer_format_from_path(&self.input[1]);

            let mut second_output_handle =
                create_output_writer(&self.output[1], self.compress_level, self.compress_type)
                    .context("unable to create the second output file")?;

            let output_format_2 = match &self.output_format {
                Some(crate::cli::OutputFormat::Sam) => {
                    Some(noodles_util::alignment::io::Format::Sam)
                }
                Some(crate::cli::OutputFormat::Bam) => {
                    Some(noodles_util::alignment::io::Format::Bam)
                }
                Some(crate::cli::OutputFormat::Cram) => {
                    Some(noodles_util::alignment::io::Format::Cram)
                }
                Some(crate::cli::OutputFormat::Fasta) | Some(crate::cli::OutputFormat::Fastq) => {
                    None
                }
                None => {
                    if self.output.len() < 2 {
                        second_input_format
                    } else {
                        crate::alignment::infer_format_from_path(&self.output[1])
                    }
                }
            };

            let is_fasta_2 = match self.output_format {
                Some(crate::cli::OutputFormat::Fasta) => true,
                Some(crate::cli::OutputFormat::Fastq) => false,
                _ => {
                    if self.output.len() < 2 {
                        is_fasta_path(&self.input[1])
                    } else {
                        is_fasta_path(&self.output[1])
                    }
                }
            };

            total_kept_bases += second_input_source.filter_reads_into(
                &reads_to_keep,
                nb_reads_to_keep,
                &mut second_output_handle,
                output_format_2,
                is_fasta_2,
            )? as u64;
        }

        if let Some(gsize) = self.genome_size {
            let actual_covg = total_kept_bases / gsize;
            // safe to unwrap self.coverage as we have already ensured genome size and coverage co-occur
            if Coverage(actual_covg as f32) < self.coverage.unwrap() {
                warn!(
                "Requested coverage ({:.2}x) is not possible as the actual coverage is {:.2}x - \
                output will be the same as the input",
                self.coverage.unwrap().0,
                actual_covg
            );
            } else {
                info!("Actual coverage of kept reads is {:.2}x", actual_covg);
            }
        } else {
            info!("Kept {} bases", total_kept_bases);
        }

        info!("Done 🎉");
        Ok(())
    }
}

fn is_fasta_path(path: &Path) -> bool {
    let mut p = path.to_path_buf();
    if let Some(ext) = p.extension().map(|e| e.to_string_lossy().to_lowercase()) {
        if ["gz", "bz2", "xz", "zst", "bz"].contains(&ext.as_str()) {
            p = p.with_extension("");
        }
    }
    if let Some(ext) = p.extension().map(|e| e.to_string_lossy().to_lowercase()) {
        return ext == "fasta" || ext == "fa";
    }
    false
}

#[cfg(test)]
mod tests {
    use assert_cmd::Command;

    const SUB: &str = "reads";

    #[test]
    fn no_args_given_raises_error() {
        let passed_args = vec![SUB];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn no_input_file_given_raises_error() {
        let passed_args = vec![SUB, "-c", "30", "-g", "3mb"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn no_coverage_given_raises_error() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-g", "3mb"];
        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();

        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn invalid_coverage_given_raises_error() {
        let passed_args = vec![SUB, "in.fq", "-g", "3mb", "-c", "foo"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn no_genome_size_given_raises_error() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-c", "5"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn no_genome_size_but_bases_and_coverage() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-b", "5", "-c", "7"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn bases_and_coverage_and_genome_size_all_allowed() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-b", "5", "-c", "7", "-g", "5m"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn no_genome_size_or_coverage_given_but_bases_given() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-b", "5"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn no_genome_size_or_coverage_given_but_num_given() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-n", "5"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn no_genome_size_or_coverage_given_but_frac_given() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-f", "5"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn num_and_coverage_and_genome_size_not_allowed() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-n", "5", "-c", "7", "-g", "5m"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn frac_and_coverage_and_genome_size_not_allowed() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-f", "5", "-c", "7", "-g", "5m"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn frac_and_bases_not_allowed() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-f", "5", "-b", "7"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn frac_and_num_not_allowed() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-f", "5", "-n", "7"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn bases_and_num_not_allowed() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-b", "5", "-n", "7"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn invalid_genome_size_given_raises_error() {
        let passed_args = vec![SUB, "in.fq", "-c", "5", "-g", "8jb"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn faidx_given_as_genome_size() {
        let infile = "tests/cases/r1.fq.gz";
        let faidx = "tests/cases/h37rv.fa.fai";
        let passed_args = vec![SUB, infile, "-c", "5", "-g", faidx];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn invalid_seed_given_raises_error() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-c", "5", "-g", "8mb", "-s", "foo"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn all_valid_args_parsed_as_expected() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB,
            infile,
            "-c",
            "5",
            "-g",
            "8mb",
            "-s",
            "88",
            "-o",
            "/dev/null",
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn two_outputs_passed_with_one_option_flag() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB,
            infile,
            infile,
            "-c",
            "5",
            "-g",
            "8mb",
            "-s",
            "88",
            "-o",
            "/dev/null",
            "/dev/null",
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn three_inputs_raises_error() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB,
            infile,
            infile,
            infile,
            "-c",
            "5",
            "-g",
            "8mb",
            "-s",
            "88",
            "-o",
            "my/output/file.fq",
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn three_outputs_raises_error() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB,
            infile,
            infile,
            "-c",
            "5",
            "-g",
            "8mb",
            "-s",
            "88",
            "-o",
            "my/output/file.fq",
            "-o",
            "out.fq",
            "-o",
            "out.fq",
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn one_input_no_output_is_ok() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![SUB, infile, "-c", "5", "-g", "8mb", "-s", "88"];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn two_inputs_one_output_raises_error() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB, infile, infile, "-c", "5", "-g", "8mb", "-s", "88", "-o", "out.fq",
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn one_input_two_outputs_raises_error() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB, infile, "-c", "5", "-g", "8mb", "-s", "88", "-o", "out.fq", "-o", "out.fq",
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().failure();
    }

    #[test]
    fn two_input_two_outputs_is_ok() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB, infile, infile, "-c", "5", "-g", "8mb", "-s", "88", "-o", "out.fq", "-o", "out.fq",
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }

    #[test]
    fn two_input_two_outputs_is_ok_when_positional_args_at_end() {
        let infile = "tests/cases/r1.fq.gz";
        let passed_args = vec![
            SUB, "-c", "5", "-g", "8mb", "-s", "88", "-o", "out.fq", "-o", "out.fq", infile, infile,
        ];

        let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
        cmd.args(passed_args).assert().success();
    }
}