4use std::iter::Iterator;
9 // Read the user's command line arguments (if any)
11 // 0 arguments = get a single random line
12 // 1 argument k = get that number of lines
13 // >1 arguments = error
15 let args: Vec<_> = std::env::args().collect();
17 let k = match args.len() {
19 2 => match args[1].parse::<usize>() {
20 Ok(parsed_k) if parsed_k > 0 => parsed_k,
22 eprintln!("Usage: randline [k]");
27 eprintln!("Usage: randline [k]");
32 let lines = std::io::stdin().lock().lines().map(|line| match line {
35 eprintln!("Unable to read from stdin: {:?}", e);
40 let sample = sampling::reservoir_sample(lines, k);
49 use assert_cmd::Command;
51 // Note: for the purposes of the CLI tests, I trust that the reservoir
52 // sampling code works correctly -- that's tested separately. I'm just
53 // checking the CLI parses the options correctly, so all the input lines
54 // are the same for easy assertions.
56 // If you call `randline` without any arguments, it picks a single line.
58 fn it_selects_a_single_line_if_no_arg() {
59 Command::cargo_bin("randline")
61 .write_stdin("a\na\na\na\na\na\n")
68 // If you pass an argument `k` and there are more lines than `k`,
69 // it selects a subset of them.
71 fn it_selects_k_lines_if_more_lines_than_k() {
72 Command::cargo_bin("randline")
75 .write_stdin("a\na\na\na\na\na\n")
82 // If you pass an argument `k` and there are that number of lines,
83 // it selects all of them.
85 fn it_selects_k_lines_if_equal_lines_to_k() {
86 Command::cargo_bin("randline")
89 .write_stdin("a\na\n")
96 // If you pass an argument `k` and there are less lines than `k`,
97 // it selects all of them.
99 fn it_selects_k_lines_if_less_lines_than_k() {
100 Command::cargo_bin("randline")
103 .write_stdin("a\na\n")
110 // Passing a non-integer argument is an error.
112 fn it_fails_if_non_integer_argument() {
113 Command::cargo_bin("randline")
120 .stderr("Usage: randline [k]\n");
123 // Passing k=0 is an error.
125 fn it_fails_if_k_equals_zero() {
126 Command::cargo_bin("randline")
133 .stderr("Usage: randline [k]\n");
136 // Passing k<0 is an error.
138 fn it_fails_if_k_negative() {
139 Command::cargo_bin("randline")
146 .stderr("Usage: randline [k]\n");
149 // Passing more than one argument is an error.
151 fn it_fails_if_too_many_args() {
152 Command::cargo_bin("randline")
154 .args(&["1", "2", "3"])
159 .stderr("Usage: randline [k]\n");