1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//! Integration tests for struct serialization and deserialization.
use indoc::indoc;
use serde::{Deserialize, Serialize};
// Test macros
macro_rules! deser_ok {
($name:ident, $ty:ty, $input:expr, $expected:expr) => {
#[test]
fn $name() {
let val: $ty = serde_kdl2::from_str($input).unwrap();
assert_eq!(val, $expected);
}
};
}
macro_rules! roundtrip {
($name:ident, $ty:ty, $val:expr) => {
#[test]
fn $name() {
let val: $ty = $val;
let output = serde_kdl2::to_string(&val).unwrap();
let rt: $ty = serde_kdl2::from_str(&output).unwrap();
assert_eq!(val, rt);
}
};
}
// Shared types
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct SimpleConfig {
title: String,
count: i32,
enabled: bool,
ratio: f64,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Server {
host: String,
port: u16,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct AppConfig {
name: String,
server: Server,
}
// ════════════════════════════════════════════════════════════════════════
// Basic struct tests
// ════════════════════════════════════════════════════════════════════════
deser_ok!(
deserialize_simple_struct,
SimpleConfig,
indoc! {r#"
title "My App"
count 42
enabled #true
ratio 3.125
"#},
SimpleConfig {
title: "My App".into(),
count: 42,
enabled: true,
ratio: 3.125
}
);
roundtrip!(
serialize_simple_struct,
SimpleConfig,
SimpleConfig {
title: "My App".into(),
count: 42,
enabled: true,
ratio: 3.125,
}
);
deser_ok!(
deserialize_nested_struct,
AppConfig,
indoc! {r#"
name "webapp"
server {
host "localhost"
port 8080
}
"#},
AppConfig {
name: "webapp".into(),
server: Server {
host: "localhost".into(),
port: 8080,
},
}
);
roundtrip!(
serialize_nested_struct,
AppConfig,
AppConfig {
name: "webapp".into(),
server: Server {
host: "localhost".into(),
port: 8080,
},
}
);
// ── Deeply nested ──────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Level3 {
value: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Level2 {
inner: Level3,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Level1 {
middle: Level2,
}
#[test]
fn deeply_nested() {
let input = indoc! {r#"
middle {
inner {
value "deep"
}
}
"#};
let val: Level1 = serde_kdl2::from_str(input).unwrap();
assert_eq!(val.middle.inner.value, "deep");
let output = serde_kdl2::to_string(&val).unwrap();
let rt: Level1 = serde_kdl2::from_str(&output).unwrap();
assert_eq!(val, rt);
}