mockforge-core 0.3.114

Shared logic for MockForge - routing, validation, latency, proxy
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Property-based tests for core functionality.
//!
//! These tests use property-based testing to verify correctness of templating
//! and validation logic across a wide range of inputs.

use mockforge_core::templating::{expand_str, expand_tokens};
use mockforge_core::validation::validate_json_schema;
use proptest::prelude::*;
use serde_json::{json, Value};

/// Property test: Template expansion should never panic, regardless of input
#[cfg(test)]
mod template_expansion_tests {
    use super::*;

    proptest! {
        #[test]
        fn expand_str_never_panics(input in ".*") {
            // Should never panic, even with invalid or malformed input
            let _ = expand_str(&input);
        }

        #[test]
        fn expand_tokens_never_panics(
            value in prop::option::of(prop::num::i64::ANY),
            key in "[a-zA-Z_][a-zA-Z0-9_]*"
        ) {
            // Test with various JSON values
            let json_val = match value {
                Some(v) => json!(v),
                None => Value::Null,
            };

            let obj = json!({key: json_val});
            let _ = expand_tokens(&obj);
        }

        #[test]
        fn expand_tokens_with_nested_objects(
            key1 in "[a-zA-Z_][a-zA-Z0-9_]*",
            key2 in "[a-zA-Z_][a-zA-Z0-9_]*",
            val in prop::num::i64::ANY
        ) {
            let obj = json!({
                key1: {
                    key2: val
                }
            });
            let _ = expand_tokens(&obj);
        }
    }
}

/// Property test: JSON schema validation should never panic
#[cfg(test)]
mod validation_tests {
    use super::*;

    proptest! {
        #[test]
        fn validate_json_schema_never_panics(
            data_type in prop::sample::select(vec!["string", "number", "boolean", "null", "array", "object"]),
            prop_name in "[a-zA-Z_][a-zA-Z0-9_]*"
        ) {
            // Create a simple schema
            let schema = json!({
                "type": "object",
                "properties": {
                    prop_name.clone(): {
                        "type": data_type
                    }
                }
            });

            // Create data that might or might not match
            let data = json!({
                prop_name: "test"
            });

            // Should never panic, even if validation fails
            let _ = validate_json_schema(&data, &schema);
        }

        #[test]
        fn validate_arbitrary_json_values(
            key in "[a-zA-Z_][a-zA-Z0-9_]*",
            value in prop::num::i64::ANY
        ) {
            let schema = json!({
                "type": "object",
                "properties": {
                    key.clone(): {"type": "number"}
                }
            });

            let data = json!({key: value});

            // Validation might succeed or fail, but should never panic
            let result = validate_json_schema(&data, &schema);
            // Verify result is either valid or has errors
            assert!(result.valid || !result.errors.is_empty());
        }

        #[test]
        fn validate_with_complex_schemas(
            min_val in 0i64..100,
            max_val in 100i64..1000,
            test_val in 0i64..1000
        ) {
            let schema = json!({
                "type": "object",
                "properties": {
                    "value": {
                        "type": "number",
                        "minimum": min_val,
                        "maximum": max_val
                    }
                }
            });

            let data = json!({"value": test_val});
            let result = validate_json_schema(&data, &schema);

            // Verify the validation result is correct
            if test_val >= min_val && test_val <= max_val {
                // Might be valid
                assert!(result.valid || !result.errors.is_empty());
            }
            // Should never panic regardless
        }
    }
}

/// Property test: String template expansion properties
#[cfg(test)]
mod template_properties {
    use super::*;

    proptest! {
        #[test]
        fn expand_str_preserves_non_template_text(text in "[^{]+") {
            // Text without template markers should be preserved
            let result = expand_str(&text);
            assert_eq!(result, text);
        }

        #[test]
        fn expand_str_handles_escaped_braces(count in 0usize..10) {
            // Multiple braces in a row should be handled gracefully
            let input = "{".repeat(count);
            let _ = expand_str(&input);
        }

        #[test]
        fn expand_str_handles_unicode(text in "\\PC*") {
            // Should handle unicode characters without panicking
            let _ = expand_str(&text);
        }
    }
}

/// Property test: Edge cases and boundary conditions
#[cfg(test)]
mod edge_cases {
    use super::*;

    proptest! {
        #[test]
        fn handles_empty_strings(_count in 0usize..5) {
            let empty_str = "".to_string();
            let _ = expand_str(&empty_str);

            let empty_json = json!({});
            let _ = expand_tokens(&empty_json);
        }

        #[test]
        fn handles_very_long_strings(len in 0usize..10000) {
            let long_str = "a".repeat(len);
            let _ = expand_str(&long_str);
        }

        #[test]
        fn handles_deep_nesting(depth in 0usize..10) {
            let mut value = json!("leaf");
            for _ in 0..depth {
                value = json!({"nested": value});
            }
            let _ = expand_tokens(&value);
        }
    }
}

/// Property test: OpenAPI and JSON parsing robustness
#[cfg(test)]
mod parsing_robustness {
    use super::*;

    proptest! {
        #[test]
        fn json_parsing_handles_arbitrary_structure(
            key in "[a-zA-Z_][a-zA-Z0-9_]*",
            int_val in prop::num::i64::ANY,
            bool_val in any::<bool>(),
            str_val in ".*"
        ) {
            // Test parsing complex JSON structures
            let complex_json = json!({
                key.clone(): {
                    "integer": int_val,
                    "boolean": bool_val,
                    "string": str_val,
                    "array": [1, 2, 3],
                    "null": null
                }
            });

            // Should always serialize/deserialize successfully
            let serialized = serde_json::to_string(&complex_json);
            assert!(serialized.is_ok());

            if let Ok(json_str) = serialized {
                let deserialized = serde_json::from_str::<Value>(&json_str);
                assert!(deserialized.is_ok());
            }
        }

        #[test]
        fn schema_validation_with_arrays(
            min_items in 0usize..10,
            max_items in 10usize..20,
            array_len in 0usize..25
        ) {
            let schema = json!({
                "type": "array",
                "minItems": min_items,
                "maxItems": max_items,
                "items": {"type": "number"}
            });

            let data = json!((0..array_len).collect::<Vec<usize>>());
            let result = validate_json_schema(&data, &schema);

            // Validation should complete without panicking
            let expected_valid = array_len >= min_items && array_len <= max_items;
            if expected_valid {
                assert!(result.valid || !result.errors.is_empty());
            }
        }

        #[test]
        fn schema_validation_with_pattern(
            pattern in "[a-z]{3,10}",
            test_string in "\\PC*"
        ) {
            let schema = json!({
                "type": "string",
                "pattern": pattern
            });

            let data = json!(test_string);
            let _ = validate_json_schema(&data, &schema);
            // Should never panic regardless of pattern or string
        }

        #[test]
        fn template_expansion_with_special_chars(
            text in "[\\s\\S]{0,100}"
        ) {
            // Test with all sorts of special characters
            let template = format!("{{{{random.uuid}}}} {} {{{{faker.name}}}}", text);
            let result = expand_str(&template);
            // Should handle gracefully
            assert!(!result.is_empty() || template.is_empty());
        }
    }
}

/// Property test: Data type conversions and coercion
#[cfg(test)]
mod type_handling {
    use super::*;

    proptest! {
        #[test]
        fn handles_numeric_type_variations(
            int_val in prop::num::i64::ANY,
            float_val in prop::num::f64::ANY
        ) {
            // Schema expects number, should accept both int and float
            let schema = json!({
                "type": "object",
                "properties": {
                    "value": {"type": "number"}
                }
            });

            let int_data = json!({"value": int_val});
            let float_data = json!({"value": float_val});

            // Both should be processed without panicking
            let _ = validate_json_schema(&int_data, &schema);
            if float_val.is_finite() {
                let _ = validate_json_schema(&float_data, &schema);
            }
        }

        #[test]
        fn handles_string_representations(
            val in prop::num::i32::ANY
        ) {
            let schema = json!({
                "type": "object",
                "properties": {
                    "id": {"type": "string"}
                }
            });

            // Test with actual number vs string representation
            let as_number = json!({"id": val});
            let as_string = json!({"id": val.to_string()});

            let _result_num = validate_json_schema(&as_number, &schema);
            let result_str = validate_json_schema(&as_string, &schema);

            // String should be valid, number should not, but neither should panic
            assert!(!result_str.valid || result_str.errors.is_empty());
            // Number will likely be invalid, but shouldn't panic
        }

        #[test]
        fn handles_null_and_optional_fields(
            include_field in any::<bool>(),
            val in prop::option::of(prop::num::i64::ANY)
        ) {
            let schema = json!({
                "type": "object",
                "properties": {
                    "optional_field": {"type": ["number", "null"]}
                }
            });

            let data = if include_field {
                match val {
                    Some(v) => json!({"optional_field": v}),
                    None => json!({"optional_field": null})
                }
            } else {
                json!({})
            };

            let result = validate_json_schema(&data, &schema);
            // Should handle null and missing fields gracefully
            assert!(result.valid || !result.errors.is_empty());
        }
    }
}

/// Property test: Enhanced validation edge cases
#[cfg(test)]
mod enhanced_validation_tests {
    use super::*;

    proptest! {
        #[test]
        fn validate_with_required_fields(
            field_name in "[a-zA-Z_][a-zA-Z0-9_]*",
            include_field in any::<bool>(),
            field_value in prop::num::i64::ANY
        ) {
            let schema = json!({
                "type": "object",
                "required": [field_name.clone()],
                "properties": {
                    field_name.clone(): {"type": "number"}
                }
            });

            let data = if include_field {
                json!({field_name: field_value})
            } else {
                json!({})
            };

            let result = validate_json_schema(&data, &schema);
            // Should validate correctly based on required field presence
            if include_field {
                assert!(result.valid || !result.errors.is_empty());
            }
        }

        #[test]
        fn validate_with_enum_constraints(
            enum_values in prop::collection::vec(".*", 1..10),
            test_value in ".*"
        ) {
            let schema = json!({
                "type": "string",
                "enum": enum_values
            });

            let data = json!(test_value);
            let _ = validate_json_schema(&data, &schema);
        }

        #[test]
        fn validate_with_format_constraints(
            format_type in prop::sample::select(vec![
                "email", "uri", "date", "date-time", "uuid"
            ]),
            test_value in ".*"
        ) {
            let schema = json!({
                "type": "string",
                "format": format_type
            });

            let data = json!(test_value);
            let _ = validate_json_schema(&data, &schema);
        }

        #[test]
        fn validate_with_multiple_of_constraint(
            multiple_of in 1i64..100,
            test_value in 0i64..1000
        ) {
            let schema = json!({
                "type": "number",
                "multipleOf": multiple_of
            });

            let data = json!(test_value);
            let _ = validate_json_schema(&data, &schema);
        }

        #[test]
        fn validate_with_one_of_schemas(
            value in prop::num::i64::ANY
        ) {
            let schema = json!({
                "oneOf": [
                    {"type": "string"},
                    {"type": "number"}
                ]
            });

            let data = json!(value);
            let _ = validate_json_schema(&data, &schema);
        }

        #[test]
        fn validate_with_all_of_schemas(
            min_val in 0i64..50,
            max_val in 50i64..100,
            test_val in 0i64..100
        ) {
            let schema = json!({
                "allOf": [
                    {"type": "number"},
                    {"minimum": min_val},
                    {"maximum": max_val}
                ]
            });

            let data = json!(test_val);
            let _ = validate_json_schema(&data, &schema);
        }

        #[test]
        fn validate_with_any_of_schemas(
            test_value in prop::num::i64::ANY
        ) {
            let schema = json!({
                "anyOf": [
                    {"type": "string"},
                    {"type": "number"},
                    {"type": "boolean"}
                ]
            });

            let data = json!(test_value);
            let _ = validate_json_schema(&data, &schema);
        }
    }
}

/// Property test: Template expansion with malicious inputs
#[cfg(test)]
mod template_security_tests {
    use super::*;

    proptest! {
        #[test]
        fn expand_str_with_injection_attempts(
            malicious_input in prop::sample::select(vec![
                "{{{{{{",
                "}}}}}}",
                "{{.}}",
                "{{..}}",
                "{{/etc/passwd}}",
                "{{../../etc/passwd}}",
            ])
        ) {
            // Should handle malicious-looking template syntax without panicking
            let _ = expand_str(malicious_input);
        }

        #[test]
        fn expand_str_with_very_deep_nesting(
            depth in 0usize..100
        ) {
            let template = "{{".repeat(depth) + &"}}".repeat(depth);
            // Should handle deeply nested braces without stack overflow
            let _ = expand_str(&template);
        }

        #[test]
        fn expand_tokens_with_circular_references(
            key in "[a-zA-Z_][a-zA-Z0-9_]*"
        ) {
            // Create JSON that might cause issues
            let mut obj = serde_json::Map::new();
            obj.insert(key.clone(), json!({key: "circular"}));
            let json_obj = Value::Object(obj);

            // Should handle without infinite loops
            let _ = expand_tokens(&json_obj);
        }
    }
}