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
//! Comprehensive error handling tests for core functionality.
//!
//! These tests verify that MockForge handles errors gracefully without panicking,
//! providing proper error messages and recovery mechanisms.

use mockforge_core::conditions::{evaluate_condition, ConditionContext};
use mockforge_core::routing::{HttpMethod, Route, RouteRegistry};
use mockforge_core::templating::expand_str;
use mockforge_core::validation::validate_json_schema;
use serde_json::json;

#[cfg(test)]
mod malformed_input_tests {
    use super::*;

    #[test]
    fn condition_evaluation_with_malformed_jsonpath() {
        let context = ConditionContext::new();

        // Malformed JSONPath expressions should return errors, not panic
        let malformed_paths = vec![
            "$.",
            "$..",
            "$[",
            "$]",
            "$.field[",
            "$.field[]",
            "$[invalid]",
            "$.field..nested",
        ];

        for path in malformed_paths {
            let result = evaluate_condition(path, &context);
            // Should not panic on malformed paths — any Result variant is acceptable
            // but the real test is that we reach this line without a panic
            let _ = result;
        }
    }

    #[test]
    fn condition_evaluation_with_malformed_logical_operators() {
        let context = ConditionContext::new();

        // Malformed logical operators
        let malformed = vec![
            "AND(", "OR(", "NOT(", "AND())", "OR(,)", "AND(OR(", "NOT(NOT(",
        ];

        for condition in malformed {
            let result = evaluate_condition(condition, &context);
            // Should not panic on malformed conditions
            let _ = result;
        }
    }

    #[test]
    fn route_matching_with_malformed_paths() {
        let mut registry = RouteRegistry::new();
        let route = Route::new(HttpMethod::GET, "/api/users".to_string());
        registry.add_http_route(route).unwrap();

        // Malformed paths should not panic
        let malformed_paths = vec![
            "",
            "//",
            "/api//users",
            "/api/users/",
            "api/users",             // Missing leading slash
            "/api/users?query=test", // Query string in path
            "/api/users#fragment",   // Fragment in path
        ];

        for path in malformed_paths {
            let _ = registry.find_http_routes(&HttpMethod::GET, path);
        }
    }

    #[test]
    fn validation_with_malformed_schemas() {
        // Malformed JSON schemas should not panic
        let malformed_schemas = vec![
            json!({}), // Empty schema
            json!({"type": "invalid_type"}),
            json!({"type": "object", "properties": null}),
            json!({"type": "array", "items": null}),
            json!({"type": "string", "pattern": "[invalid regex"}),
            json!({"type": "number", "minimum": "not a number"}),
            json!({"allOf": null}),
            json!({"oneOf": []}),
            json!({"$ref": "#/definitions/nonexistent"}),
        ];

        let test_data = json!({"test": "value"});

        for schema in malformed_schemas {
            let result = validate_json_schema(&test_data, &schema);
            // Should handle gracefully, may return errors
            let _ = result;
        }
    }

    #[test]
    fn template_expansion_with_malformed_templates() {
        // Malformed templates should not panic
        let malformed = vec![
            "{{",
            "}}",
            "{{{",
            "}}}",
            "{{{{",
            "{{.}}",
            "{{..}}",
            "{{/etc/passwd}}",
            "{{../../etc/passwd}}",
            "{{field",
            "field}}",
        ];

        for template in malformed {
            let _ = expand_str(template);
        }
    }
}

#[cfg(test)]
mod large_payload_tests {
    use super::*;

    #[test]
    fn condition_evaluation_with_very_large_input() {
        let context = ConditionContext::new();

        // Very large condition string
        let large_condition = "a".repeat(1_000_000);
        let result = evaluate_condition(&large_condition, &context);
        // Should handle without stack overflow
        let _ = result;
    }

    #[test]
    fn route_matching_with_very_long_path() {
        let mut registry = RouteRegistry::new();
        let route = Route::new(HttpMethod::GET, "/api/users".to_string());
        registry.add_http_route(route).unwrap();

        // Very long path
        let long_path = "/".to_string() + &"a".repeat(100_000);
        let _ = registry.find_http_routes(&HttpMethod::GET, &long_path);
    }

    #[test]
    fn validation_with_very_large_schema() {
        // Create a very large schema with many fields
        let mut properties = serde_json::Map::new();
        for i in 0..10_000 {
            properties.insert(format!("field_{}", i), json!({"type": "string"}));
        }

        let large_schema = json!({
            "type": "object",
            "properties": properties
        });

        let test_data = json!({"field_0": "value"});
        let result = validate_json_schema(&test_data, &large_schema);
        // Should handle without memory issues
        let _ = result;
    }

    #[test]
    fn template_expansion_with_very_large_template() {
        // Very large template
        let large_template = "{{field}} ".repeat(100_000);
        let _ = expand_str(&large_template);
    }
}

#[cfg(test)]
mod invalid_utf8_tests {
    use super::*;

    #[test]
    fn condition_evaluation_handles_invalid_utf8_gracefully() {
        let context = ConditionContext::new();

        // Create invalid UTF-8 sequences
        let invalid_utf8 = vec![
            &[0xFF, 0xFE, 0xFD][..],
            &[0xC0, 0x80][..],       // Overlong encoding
            &[0xE0, 0x80, 0x80][..], // Overlong encoding
        ];

        for bytes in invalid_utf8 {
            // Try to convert to string (will fail, but should handle gracefully)
            if let Ok(condition_str) = std::str::from_utf8(bytes) {
                let _ = evaluate_condition(condition_str, &context);
            }
        }
    }

    #[test]
    fn validation_handles_invalid_utf8_in_strings() {
        // Test with strings that might have encoding issues
        // Note: serde_json handles UTF-8 validation, so we test valid but unusual UTF-8
        let schema = json!({
            "type": "object",
            "properties": {
                "field": {"type": "string"}
            }
        });

        // Valid but unusual UTF-8 sequences
        let test_cases = vec![
            json!({"field": "\u{0000}"}),  // Null byte
            json!({"field": "\u{FFFD}"}),  // Replacement character
            json!({"field": "\u{1F4A9}"}), // Emoji
        ];

        for test_data in test_cases {
            let _ = validate_json_schema(&test_data, &schema);
        }
    }
}

#[cfg(test)]
mod resource_exhaustion_tests {
    use super::*;

    #[test]
    fn condition_evaluation_with_deeply_nested_conditions() {
        let context = ConditionContext::new();

        // Create deeply nested logical operators
        let mut nested = "true".to_string();
        for _ in 0..100 {
            nested = format!("AND({})", nested);
        }

        let result = evaluate_condition(&nested, &context);
        // Should handle without stack overflow
        let _ = result;
    }

    #[test]
    fn route_registry_with_many_routes() {
        let mut registry = RouteRegistry::new();

        // Add many routes
        for i in 0..10_000 {
            let route = Route::new(HttpMethod::GET, format!("/api/route_{}", i));
            let _ = registry.add_http_route(route);
        }

        // Should still be able to find routes
        let matches = registry.find_http_routes(&HttpMethod::GET, "/api/route_0");
        assert!(!matches.is_empty());
    }

    #[test]
    fn validation_with_deeply_nested_schemas() {
        // Create deeply nested schema
        let mut nested = json!({"type": "string"});
        for _ in 0..100 {
            nested = json!({
                "type": "object",
                "properties": {
                    "nested": nested
                }
            });
        }

        let test_data = json!({"nested": "value"});
        let result = validate_json_schema(&test_data, &nested);
        // Should handle without stack overflow
        let _ = result;
    }
}

#[cfg(test)]
mod edge_case_tests {
    use super::*;

    #[test]
    fn condition_evaluation_with_empty_context() {
        let context = ConditionContext::new();

        // Various conditions with empty context
        let conditions = vec![
            "",
            "true",
            "false",
            "$.field",
            "headers.test == value",
            "query.param == value",
        ];

        for condition in conditions {
            let _ = evaluate_condition(condition, &context);
        }
    }

    #[test]
    fn route_matching_with_special_characters() {
        let mut registry = RouteRegistry::new();

        // Routes with special characters
        let special_routes = vec![
            "/api/test%20path",
            "/api/test+path",
            "/api/test@path",
            "/api/test#path",
            "/api/test$path",
        ];

        for route_path in special_routes {
            let route = Route::new(HttpMethod::GET, route_path.to_string());
            let _ = registry.add_http_route(route);
        }
    }

    #[test]
    fn validation_with_null_values() {
        let schema = json!({
            "type": "object",
            "properties": {
                "field": {"type": "string"}
            }
        });

        let test_cases = vec![
            json!({"field": null}),
            json!({"field": "value"}),
            json!({}), // Missing field
        ];

        for test_data in test_cases {
            let _ = validate_json_schema(&test_data, &schema);
        }
    }

    #[test]
    fn template_expansion_with_empty_context() {
        let templates = vec!["{{field}}", "{{nested.field}}", "{{array.0}}"];

        for template in templates {
            // Should handle missing context gracefully
            let _ = expand_str(template);
        }
    }
}

#[cfg(test)]
mod concurrent_access_tests {
    use super::*;
    use std::sync::Arc;
    use std::thread;

    #[test]
    fn route_registry_concurrent_access() {
        let registry = Arc::new(RouteRegistry::new());
        let mut handles = vec![];

        // Spawn multiple threads adding routes
        for i in 0..10 {
            let _registry_clone = Arc::clone(&registry);
            let handle = thread::spawn(move || {
                for j in 0..100 {
                    let mut reg = RouteRegistry::new();
                    let route = Route::new(HttpMethod::GET, format!("/api/route_{}_{}", i, j));
                    let _ = reg.add_http_route(route);
                }
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn condition_evaluation_concurrent_access() {
        let context = Arc::new(ConditionContext::new());
        let mut handles = vec![];

        // Spawn multiple threads evaluating conditions
        for _ in 0..10 {
            let context_clone = Arc::clone(&context);
            let handle = thread::spawn(move || {
                for _ in 0..100 {
                    let _ = evaluate_condition("true", &context_clone);
                }
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle.join().unwrap();
        }
    }
}