grrs_cli_book_demo_deploy_test/
lib.rs

1use anyhow::{Error, Result};
2
3pub const PREFIX: &str = "found - ";
4
5// business logic of the cli
6pub fn find_matches(
7    content: &str,
8    pattern: &str,
9    mut writer: impl std::io::Write,
10) -> Result<(), Error> {
11    for line in content.lines() {
12        if line.contains(pattern) {
13            // println! works the same as writeln! but always uses standard output
14            // correct err handling:
15            // with PREFIX
16            writeln!(writer, "{}{}", PREFIX, line)?;
17            // without:
18            // writeln!(writer, "{}", line)?;
19            // bad:
20            // just notify: error in write op without returning Result
21            // let res = writeln!(writer, "found - {}", line);
22            // match res {
23            //     Ok(_) => {
24            //         println!("wrote to `writer` succefully")
25            //     }
26            //     Err(_) => {
27            //         println!("failed to write to `writer` succefully")
28            //     }
29            // }
30        }
31    }
32    Ok(())
33}
34
35#[cfg(test)]
36mod tests {
37    // you have to import everything in this module
38    use super::*;
39
40    #[test]
41    fn find_match() {
42        let mut res = Vec::new();
43        let ret = find_matches("hi\nlol and ok\nlulz", "lol", &mut res);
44        // The b prefix makes this a byte string literal
45        // so its type is going to be &[u8] instead of &str
46        // certainly need to handle this instead of unwrapping
47
48        // write prefix
49        // writeln!(res, "{}", PREFIX);
50        let mut to_be_compared: String = String::new();
51
52        let shoud_find_string = "lol and ok\n";
53        to_be_compared.push_str(PREFIX);
54        to_be_compared.push_str(&shoud_find_string);
55        println!("to be comp: {}", to_be_compared);
56        assert_eq!(ret.unwrap(), ());
57        // first iteration without prefix
58        // assert_eq!(res, b"lol and ok\n");
59        // without:
60        assert_eq!(res, to_be_compared.as_bytes());
61    }
62}