jkconfig 0.2.3

A Ratatui-based TUI component library for JSON Schema configuration
Documentation
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use jkconfig::data::menu::MenuRoot;
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};

// Use Animal structures from other test file
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct Cat {
    pub a: usize,
    pub b: String,
    pub children: Option<CatChild>,
    pub child2: CatChild,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct CatChild {
    pub e: isize,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct Dog {
    pub c: Option<f32>,
    pub d: bool,
    pub l: Legs,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub enum Legs {
    Four,
    Two,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
/// 动物类型
/// Cat 或 Dog 的枚举
pub enum AnimalEnum {
    Cat(Cat),
    Dog(Dog),
    Rabbit,
    Duck { h: bool },
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
struct AnimalObject {
    animal: AnimalEnum,
}

#[test]
fn test_object() {
    let schema = schema_for!(AnimalObject);
    println!(
        "Generated JSON Schema: \n{}",
        serde_json::to_string_pretty(&schema).unwrap()
    );
    let menu = MenuRoot::try_from(schema.as_value()).unwrap();

    println!("Generated MenuRoot: \n{:#?}", menu);

    println!(
        "AnimalEnum element: \n{:#?}",
        menu.get_by_key("animal").unwrap()
    );
}

#[test]
fn test_value() {
    let schema = schema_for!(AnimalObject);

    let origin = AnimalObject {
        animal: AnimalEnum::Dog(Dog {
            c: Some(3.5),
            d: true,
            l: Legs::Four,
        }),
    };

    let value = schema.as_value();

    println!(
        "Generated JSON Schema Value: \n{}",
        serde_json::to_string_pretty(&value).unwrap()
    );

    let mut menu = MenuRoot::try_from(value).unwrap();

    let value = serde_json::to_value(&origin).unwrap();

    println!("Origin MenuRoot : \n{menu:#?}",);

    println!(
        "Json value to update: \n{}",
        serde_json::to_string_pretty(&value).unwrap()
    );

    menu.update_by_value(&value).unwrap();

    println!("Updated MenuRoot: \n{:#?}", menu);

    let actual_value = menu.as_json();

    println!(
        "Actual JSON value from MenuRoot: \n{}",
        serde_json::to_string_pretty(&actual_value).unwrap()
    );

    let actual: AnimalObject = serde_json::from_value(actual_value).unwrap();

    assert_eq!(origin.animal, actual.animal);
}

#[test]
fn test_value_enum() {
    let schema = schema_for!(AnimalObject);

    let origin = AnimalObject {
        animal: AnimalEnum::Rabbit,
    };

    let value = schema.as_value();

    println!(
        "Generated JSON Schema Value: \n{}",
        serde_json::to_string_pretty(&value).unwrap()
    );

    let mut menu = MenuRoot::try_from(value).unwrap();

    let value = serde_json::to_value(&origin).unwrap();

    println!("Origin MenuRoot : \n{menu:#?}",);

    println!(
        "Json value to update: \n{}",
        serde_json::to_string_pretty(&value).unwrap()
    );

    menu.update_by_value(&value).unwrap();

    println!("Updated MenuRoot: \n{:#?}", menu);

    let actual_value = menu.as_json();

    println!(
        "Actual JSON value from MenuRoot: \n{}",
        serde_json::to_string_pretty(&actual_value).unwrap()
    );

    let actual: AnimalObject = serde_json::from_value(actual_value).unwrap();

    assert_eq!(origin.animal, actual.animal);
}

#[test]
fn test_value_normal_case() {
    let schema = schema_for!(AnimalObject);
    let mut menu = MenuRoot::try_from(schema.as_value()).unwrap();

    // Test normal case with correct types
    let dog_value = serde_json::json!({
        "animal": {
            "Dog": {
                "c": 2.7,
                "d": false
            }
        }
    });

    let result = menu.update_by_value(&dog_value);
    assert!(
        result.is_ok(),
        "Normal case should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_value_type_mismatch() {
    let schema = schema_for!(AnimalObject);
    let mut menu = MenuRoot::try_from(schema.as_value()).unwrap();

    // Test type mismatch: boolean field receives string
    let bad_value = serde_json::json!({
        "animal": {
            "Dog": {
                "c": 2.7,
                "d": "this should be boolean"  // Type mismatch
            }
        }
    });

    let result = menu.update_by_value(&bad_value);
    assert!(result.is_err());
    println!("Type mismatch error: {:?}", result.err().unwrap());
}

#[test]
fn test_value_skip_unknown_fields() {
    let schema = schema_for!(AnimalObject);
    let mut menu = MenuRoot::try_from(schema.as_value()).unwrap();

    // Test with extra fields that don't exist in schema
    let value_with_extra = serde_json::json!({
        "animal": {
            "Dog": {
                "c": 1.5,
                "d": true,
                "unknown_field": "should be skipped",
                "another_unknown": 42
            }
        },
        "unknown_top_level": "should be skipped"
    });

    let result = menu.update_by_value(&value_with_extra);
    assert!(result.is_ok(), "Should skip unknown fields and succeed");
}

#[test]
fn test_value_empty_object() {
    let schema = schema_for!(AnimalObject);
    let mut menu = MenuRoot::try_from(schema.as_value()).unwrap();

    // Test with empty object (should skip since no matching fields)
    let empty_value = serde_json::json!({});

    let result = menu.update_by_value(&empty_value);
    // This might fail because animal is required, but let's see what happens
    println!("Empty object result: {:?}", result);
}

#[test]
fn test_value_cat_variant() {
    let schema = schema_for!(AnimalObject);
    let mut menu = MenuRoot::try_from(schema.as_value()).unwrap();

    // Test Cat variant
    let cat_value = serde_json::json!({
        "animal": {
            "Cat": {
                "a": 42,
                "b": "meow"
            }
        }
    });

    let result = menu.update_by_value(&cat_value);
    assert!(result.is_ok(), "Cat variant should succeed");
}

#[test]
fn test_value_integer_type_mismatch() {
    let schema = schema_for!(AnimalObject);
    let mut menu = MenuRoot::try_from(schema.as_value()).unwrap();

    // Test integer field receiving float
    let cat_value = serde_json::json!({
        "animal": {
            "Cat": {
                "a": 3.2,  // Should be integer, not float
                "b": "test"
            }
        }
    });

    let result = menu.update_by_value(&cat_value);
    assert!(result.is_err());
    println!("Integer type mismatch error: {:?}", result.err().unwrap());
}

/***
```json
Generated JSON Schema:
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "AnimalObject",
  "type": "object",
  "properties": {
    "animal": {
      "$ref": "#/$defs/AnimalEnum"
    }
  },
  "required": [
    "animal"
  ],
  "$defs": {
    "AnimalEnum": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "Cat": {
              "$ref": "#/$defs/Cat"
            }
          },
          "additionalProperties": false,
          "required": [
            "Cat"
          ]
        },
        {
          "type": "object",
          "properties": {
            "Dog": {
              "$ref": "#/$defs/Dog"
            }
          },
          "additionalProperties": false,
          "required": [
            "Dog"
          ]
        }
      ]
    },
    "Cat": {
      "type": "object",
      "properties": {
        "a": {
          "type": "integer",
          "format": "uint",
          "minimum": 0
        },
        "b": {
          "type": "string"
        }
      },
      "required": [
        "a",
        "b"
      ]
    },
    "Dog": {
      "type": "object",
      "properties": {
        "c": {
          "type": "number",
          "format": "float"
        },
        "d": {
          "type": "boolean"
        }
      },
      "required": [
        "c",
        "d"
      ]
    }
  }
}
```
***/

// 测试 MenuRoot::get_mut_by_key 方法的边界条件
#[cfg(test)]
mod menu_root_get_mut_by_key_tests {
    use super::*;

    /// 创建测试用的 MenuRoot 实例
    fn create_test_menu_root() -> MenuRoot {
        let schema = schema_for!(AnimalObject);
        MenuRoot::try_from(schema.as_value()).unwrap()
    }

    #[test]
    /// 测试有效路径(应返回Some的情况)
    fn test_get_mut_by_key_valid_paths() {
        let mut menu = create_test_menu_root();

        // 测试确认存在的有效路径
        let valid_paths = vec![("animal", "top-level field")];

        for (path, description) in valid_paths {
            let result = menu.get_mut_by_key(path);
            assert!(result.is_some(), "{} should return Some", description);
        }
    }

    #[test]
    /// 参数化测试:各种应返回None的边界条件
    fn test_get_mut_by_key_none_cases() {
        let mut menu = create_test_menu_root();

        let test_cases = vec![
            ("nonexistent.path", "nonexistent path"),
            (".animal", "path starting with dot"),
            ("animal.", "path ending with dot"),
            ("animal..Dog", "path with consecutive dots"),
            ("animal-Dog@c", "path with special characters"),
            ("animal.动物.c", "path with unicode characters"),
            ("...", "path with only dots"),
            ("animal..c", "path with empty field in middle"),
        ];

        for (input, description) in test_cases {
            let result = menu.get_mut_by_key(input);
            assert!(result.is_none(), "{} should return None", description);
        }
    }

    #[test]
    /// 测试深层嵌套路径
    fn test_get_mut_by_key_deep_nesting() {
        let mut menu = create_test_menu_root();

        // 测试可能存在的深层路径和不存在路径的边界情况
        let deep_path_cases = vec![
            ("animal.Cat.a", "Cat variant deep path"),
            ("animal.Dog.c", "Dog variant deep path"),
            ("animal.Duck.h", "Duck variant deep path"),
        ];

        let mut has_any_success = false;

        for (path, _description) in deep_path_cases {
            let result = menu.get_mut_by_key(path);
            if result.is_some() {
                has_any_success = true;
                break; // 如果找到有效路径,测试通过
            }
        }

        // 至少应该能够访问animal顶层路径
        let animal_result = menu.get_mut_by_key("animal");
        assert!(
            animal_result.is_some(),
            "Top-level 'animal' path should be accessible"
        );

        // 如果深层路径都不存在,这也是合理的行为(取决于OneOf的当前状态)
        if !has_any_success {
            println!(
                "Note: All deep paths returned None, which may be expected depending on OneOf state"
            );
        }
    }
}

#[test]
fn test_loglevel_schema() {
    #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
    pub enum LogLevel {
        Trace,
        Debug,
        Info,
        Warn,
        Error,
    }

    #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Default)]
    pub struct Cargo {
        pub log: Option<LogLevel>,
    }

    let schema = schemars::schema_for!(Cargo);
    println!(
        "Generated JSON Schema: \n{}",
        serde_json::to_string_pretty(&schema.as_value()).unwrap()
    );
    let menu = MenuRoot::try_from(schema.as_value()).unwrap();

    println!("Generated MenuRoot: \n{:#?}", menu);

    // Verify: log field should be Enum, not OneOf
    let log_item = menu.get_by_key("log").expect("log field should exist");
    match log_item {
        jkconfig::data::types::ElementType::Item(item) => {
            assert!(
                matches!(&item.item_type, jkconfig::data::item::ItemType::Enum(_)),
                "log should be Enum, got {:?}",
                item.item_type
            );
            if let jkconfig::data::item::ItemType::Enum(ei) = &item.item_type {
                assert_eq!(ei.variants.len(), 5, "should have 5 enum variants");
                assert_eq!(ei.variants[0], "Trace");
                assert_eq!(ei.variants[4], "Error");
            }
        }
        other => panic!("log should be Item(Enum), got {:?}", other),
    }
}