From 95eb8fcf0a1b6059ea2620122338d857fd1e2c02 Mon Sep 17 00:00:00 2001 From: mindfreq <144544047+mindfreq@users.noreply.github.com> Date: Thu, 23 Apr 2026 18:03:45 +0200 Subject: [PATCH] Integration testing --- src/lib.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/main.rs | 12 ++++-------- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0a21adc..57dda36 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,4 +69,44 @@ pub fn search(config: Config, file_content: String) -> Result, &'sta Ok(str_result) } +#[cfg(test)] +mod tests { + use super::*; + + fn run_search(args: Vec) -> Vec { + let config = Config::build(args).unwrap(); + + let file_content = std::fs::read_to_string(&config.file_path) + .expect("Failed to read file"); + + let result = search(config, file_content).unwrap(); + assert!(!result.is_empty(), "Expected matches but found none!"); + result + } + + #[test] + fn test_search() { + let args: Vec = vec!["target/debug/m-grep", "Who", "poem.txt"] + .iter().map(|&x| x.into()).collect(); + + let result = run_search(args); + + for line in result { + println!("{line}"); + assert_eq!(line, format!("I'm nobody! {} are you?", "Who".green())); + } + } + + #[test] + fn test_search_ignorecase() { + let args: Vec = vec!["target/debug/m-grep", "who", "poem.txt", "-i"] + .iter().map(|&x| x.into()).collect(); + + let result = run_search(args); + + for line in result { + assert_eq!(line, format!("I'm nobody! {} are you?", "Who".green())); + } + } +} diff --git a/src/main.rs b/src/main.rs index 3ce3528..b4a66b1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,11 @@ use colored::Colorize; -use std::io::Read; use std::process; use m_grep::{Config, search}; fn main() { let args: Vec = std::env::args().collect(); - + if let Err(err) = run(args) { eprintln!("{}: {}", "Error".red().bold(), err.to_string().red()); process::exit(1); @@ -16,16 +15,13 @@ fn main() { fn run(args: Vec) -> Result<(), Box> { let config = Config::build(args)?; let file_path = &config.file_path; - + if !std::path::Path::new(&file_path).exists() { return Err("File not exists!".into()); } - let mut file = std::fs::File::open(file_path).map_err(|_| "Failed to open file")?; - let mut file_content = String::new(); - - file.read_to_string(&mut file_content) - .map_err(|_| "Failed to read file")?; + let file_content = std::fs::read_to_string(file_path) + .expect("Failed to read file"); let result = search(config, file_content)?;