Skip to content

Commit

Permalink
test(libmake): ✅ add new tests for utility_macros.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienrousseau committed May 15, 2024
1 parent f3592c5 commit 169f728
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions tests/test_utility_macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#[cfg(test)]
mod tests {
use libmake::macro_get_field;
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::Write;
use tempfile::tempdir;
use serde_json::from_reader;

fn read_file<F, R>(file_path: &Path, f: F) -> Result<R, Box<dyn std::error::Error>>
where
F: FnOnce(File) -> Result<R, Box<dyn std::error::Error>>,
{
let file = File::open(file_path)?;
f(file)
}

macro_get_field!(get_field, from_reader);

#[test]
fn test_macro_get_field_success() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.json");

let json_data = r#"
{
"name": "Alice",
"age": 30
}
"#;

let mut file = File::create(&file_path).unwrap();
file.write_all(json_data.as_bytes()).unwrap();

let result = get_field(Some(file_path.to_str().unwrap()), "name");
assert_eq!(result.unwrap(), "Alice");

let result = get_field(Some(file_path.to_str().unwrap()), "age");
assert_eq!(result.unwrap(), "30");
}

#[test]
fn test_macro_get_field_field_not_found() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.json");

let json_data = r#"
{
"name": "Alice",
"age": 30
}
"#;

let mut file = File::create(&file_path).unwrap();
file.write_all(json_data.as_bytes()).unwrap();

let result = get_field(Some(file_path.to_str().unwrap()), "address");
assert!(result.is_err());
assert_eq!(result.unwrap_err().to_string(), "Field 'address' not found");
}

#[test]
fn test_macro_get_field_no_file_path() {
let result = get_field(None, "name");
assert!(result.is_ok());
assert_eq!(result.unwrap(), "");
}
}

0 comments on commit 169f728

Please sign in to comment.