Integration testing

This commit is contained in:
mindfreq 2026-04-23 18:03:45 +02:00
parent d718d0c46e
commit 95eb8fcf0a
2 changed files with 44 additions and 8 deletions

View file

@ -69,4 +69,44 @@ pub fn search(config: Config, file_content: String) -> Result<Vec<String>, &'sta
Ok(str_result) Ok(str_result)
} }
#[cfg(test)]
mod tests {
use super::*;
fn run_search(args: Vec<String>) -> Vec<String> {
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<String> = 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<String> = 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()));
}
}
}

View file

@ -1,12 +1,11 @@
use colored::Colorize; use colored::Colorize;
use std::io::Read;
use std::process; use std::process;
use m_grep::{Config, search}; use m_grep::{Config, search};
fn main() { fn main() {
let args: Vec<String> = std::env::args().collect(); let args: Vec<String> = std::env::args().collect();
if let Err(err) = run(args) { if let Err(err) = run(args) {
eprintln!("{}: {}", "Error".red().bold(), err.to_string().red()); eprintln!("{}: {}", "Error".red().bold(), err.to_string().red());
process::exit(1); process::exit(1);
@ -16,16 +15,13 @@ fn main() {
fn run(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> { fn run(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
let config = Config::build(args)?; let config = Config::build(args)?;
let file_path = &config.file_path; let file_path = &config.file_path;
if !std::path::Path::new(&file_path).exists() { if !std::path::Path::new(&file_path).exists() {
return Err("File not exists!".into()); return Err("File not exists!".into());
} }
let mut file = std::fs::File::open(file_path).map_err(|_| "Failed to open file")?; let file_content = std::fs::read_to_string(file_path)
let mut file_content = String::new(); .expect("Failed to read file");
file.read_to_string(&mut file_content)
.map_err(|_| "Failed to read file")?;
let result = search(config, file_content)?; let result = search(config, file_content)?;