focus/crates/focus-json/tests/writer_tests.rs

80 lines
2.3 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! writer 模块JSON 序列化)的集成测试。
//! Integration tests for the writer module (JSON serialization).
use focus_json::{parse, to_string, JsonValue};
fn roundtrip(input: &str) {
let parsed = parse(input).unwrap_or_else(|e| panic!("parse failed for {:?}: {}", input, e));
let serialized = to_string(&parsed);
let reparsed = parse(&serialized).expect("reparse failed");
assert_eq!(parsed, reparsed, "roundtrip mismatch for {:?}", input);
}
#[test]
fn serializes_primitives() {
assert_eq!(to_string(&JsonValue::Null), "null");
assert_eq!(to_string(&JsonValue::Bool(true)), "true");
assert_eq!(to_string(&JsonValue::Bool(false)), "false");
assert_eq!(to_string(&JsonValue::Str("hi".into())), r#""hi""#);
}
#[test]
fn serializes_integers_without_fraction() {
assert_eq!(to_string(&JsonValue::Num(3.0)), "3");
assert_eq!(to_string(&JsonValue::Num(-42.0)), "-42");
assert_eq!(to_string(&JsonValue::Num(0.0)), "0");
}
#[test]
fn serializes_fractional_numbers() {
assert_eq!(to_string(&JsonValue::Num(12.345)), "12.345");
}
#[test]
fn escapes_strings() {
let s = JsonValue::Str("a\"b\nc".into());
assert_eq!(to_string(&s), r#""a\"b\nc""#);
}
#[test]
fn escapes_control_chars_as_unicode() {
let s = JsonValue::Str("\u{0001}".into());
assert_eq!(to_string(&s), r#""\u0001""#);
}
#[test]
fn serializes_arrays_and_objects() {
let mut o = JsonValue::obj();
o.insert("a", JsonValue::Num(1.0)).unwrap();
o.insert(
"b",
JsonValue::Arr(vec![JsonValue::Bool(true), JsonValue::Null]),
)
.unwrap();
assert_eq!(to_string(&o), r#"{"a":1,"b":[true,null]}"#);
}
#[test]
fn roundtrips_various() {
roundtrip(r#"{"name":"focus","nums":[1,2,3],"nested":{"deep":true}}"#);
roundtrip(r#""escape: \\ \" \n \t""#);
roundtrip("12.345159");
roundtrip("-0");
roundtrip("[]");
roundtrip("{}");
}
#[test]
fn handles_unicode_in_strings() {
let s = JsonValue::Str("中文😀".into());
let serialized = to_string(&s);
assert_eq!(serialized, r#""中文😀""#);
assert_eq!(parse(&serialized).unwrap(), s);
}
#[test]
fn non_finite_becomes_null() {
assert_eq!(to_string(&JsonValue::Num(f64::NAN)), "null");
assert_eq!(to_string(&JsonValue::Num(f64::INFINITY)), "null");
}