Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/json testing #4

Merged
merged 2 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ fs-err = "2.9"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[dev-dependencies]
tempfile = "3.8"

# The profile that 'cargo dist' will build with
[profile.dist]
inherits = "release"
Expand Down
97 changes: 94 additions & 3 deletions src/format_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@ use anyhow::{Context, Result};
use fs_err as fs;
use serde_json::{Map, Value};

pub fn format_json_file(filename: &str, output_filename: Option<&str>) -> Result<()> {
pub fn format_json_file(filename: &str, output_filename: Option<&str>, sort: bool) -> Result<()> {
// Read the file
let data = fs::read_to_string(filename).context("Failed to read the file")?;

// Parse the JSON data
let mut json_value: Value = serde_json::from_str(&data).context("Failed to parse JSON")?;

// Sort keys if it's a map
if let Value::Object(map) = &mut json_value {
sort_map(map);
if sort {
if let Value::Object(map) = &mut json_value {
sort_map(map);
}
}

// Write the formatted JSON data back to the file
Expand Down Expand Up @@ -39,3 +41,92 @@ fn sort_map(map: &mut Map<String, Value>) {
map.insert(k, v);
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use tempfile::NamedTempFile;

fn setup_test_file(data: &str) -> NamedTempFile {
let mut file = NamedTempFile::new().expect("Failed to create test file");
file.write_all(data.as_bytes()).expect("Failed to write to test file");
file
}

fn read_file(path: &Path) -> std::io::Result<String> {
let mut file = File::open(path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}

#[test]
fn test_valid_json() {
let file = setup_test_file(r#"{"key": "value"}"#);
let result = format_json_file(file.path().to_str().unwrap(), None, false);
assert!(result.is_ok());
}

#[test]
fn test_invalid_json() {
let file = setup_test_file(r#"{"key": "value""#);
let result = format_json_file(file.path().to_str().unwrap(), None, false);
assert!(result.is_err());
}

#[test]
fn test_sort_json() {
let file = setup_test_file(r#"{"b": "2", "a": "1"}"#);
let _ = format_json_file(file.path().to_str().unwrap(), None, true).unwrap();

let sorted_data = read_file(file.path()).expect("Failed to read the file");
assert_eq!(
sorted_data,
r#"{
"a": "1",
"b": "2"
}"#
);
}

#[test]
fn test_nested_json() {
let file = setup_test_file(r#"{"a": {"c": "3", "b": "2"}}"#);
let _ = format_json_file(file.path().to_str().unwrap(), None, true).unwrap();

let sorted_data = read_file(file.path()).expect("Failed to read the file");
assert_eq!(
sorted_data,
r#"{
"a": {
"b": "2",
"c": "3"
}
}"#
);
}

#[test]
fn test_output_file() {
let input_file = setup_test_file(r#"{"key": "value"}"#);
let mut output_file = NamedTempFile::new().expect("Failed to create output test file");
let _ = format_json_file(
input_file.path().to_str().unwrap(),
Some(output_file.path().to_str().unwrap()),
false,
)
.unwrap();

let mut output_data = String::new();
output_file.read_to_string(&mut output_data).unwrap();
assert_eq!(
output_data,
r#"{
"key": "value"
}"#
);
}
}
7 changes: 5 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@

#[arg(short, long, help = "Optional output filename to write the formatted JSON.")]
output: Option<String>,

#[arg(short, long, help = "Sort the JSON keys.")]
sort: bool,
},
}

Expand All @@ -52,8 +55,8 @@
let text = if *caps { text.to_uppercase() } else { text.to_string() };
println!("{}", comment(&text, *min_length, *symbol, prefix.clone()))
},
Some(Commands::FormatJson { filename, output }) => {
format_json_file(filename, output.as_deref())?;
Some(Commands::FormatJson { filename, output, sort }) => {
format_json_file(filename, output.as_deref(), *sort)?;

Check warning on line 59 in src/main.rs

View check run for this annotation

Codecov / codecov/patch

src/main.rs#L58-L59

Added lines #L58 - L59 were not covered by tests
},
None => {
bail!("Unknown command")
Expand Down
Loading