forge-core 0.10.0

Core types and traits for the Forge framework
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! HTTP mocking utilities for testing.

#![allow(clippy::unwrap_used, clippy::indexing_slicing)]

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use serde::Serialize;

/// Mock HTTP client for testing.
///
/// Mocks are matched **first-registered-wins**: the first handler whose
/// pattern matches the request URL (or path) is used. Register specific
/// patterns before broad wildcards.
///
/// Patterns are matched against both the full URL and the path component,
/// so `"/health"` matches a request to `https://internal:8080/health`.
#[derive(Clone)]
pub struct MockHttp {
    mocks: Arc<RwLock<Vec<MockHandler>>>,
    requests: Arc<RwLock<Vec<RecordedRequest>>>,
}

pub type BoxedHandler = Box<dyn Fn(&MockRequest) -> MockResponse + Send + Sync>;

struct MockHandler {
    pattern: String,
    handler: Arc<dyn Fn(&MockRequest) -> MockResponse + Send + Sync>,
}

/// A recorded request for verification.
#[derive(Debug, Clone)]
pub struct RecordedRequest {
    pub method: String,
    pub url: String,
    pub headers: HashMap<String, String>,
    pub body: serde_json::Value,
}

/// Mock HTTP request.
#[derive(Debug, Clone)]
pub struct MockRequest {
    pub method: String,
    pub path: String,
    pub url: String,
    pub headers: HashMap<String, String>,
    pub body: serde_json::Value,
}

/// Mock HTTP response.
#[derive(Debug, Clone)]
pub struct MockResponse {
    pub status: u16,
    pub headers: HashMap<String, String>,
    pub body: serde_json::Value,
}

impl MockResponse {
    pub fn json<T: Serialize>(body: T) -> Self {
        Self {
            status: 200,
            headers: HashMap::from([("content-type".to_string(), "application/json".to_string())]),
            body: serde_json::to_value(body).unwrap_or(serde_json::Value::Null),
        }
    }

    pub fn error(status: u16, message: &str) -> Self {
        Self {
            status,
            headers: HashMap::from([("content-type".to_string(), "application/json".to_string())]),
            body: serde_json::json!({ "error": message }),
        }
    }

    pub fn internal_error(message: &str) -> Self {
        Self::error(500, message)
    }

    pub fn not_found(message: &str) -> Self {
        Self::error(404, message)
    }

    pub fn unauthorized(message: &str) -> Self {
        Self::error(401, message)
    }

    pub fn ok() -> Self {
        Self::json(serde_json::json!({}))
    }
}

impl MockHttp {
    pub fn new() -> Self {
        Self {
            mocks: Arc::new(RwLock::new(Vec::new())),
            requests: Arc::new(RwLock::new(Vec::new())),
        }
    }

    pub fn builder() -> MockHttpBuilder {
        MockHttpBuilder::new()
    }

    /// Add a mock handler (sync version for use in builders).
    ///
    /// The pattern supports `*` as a glob wildcard. Mocks are matched
    /// first-registered-wins against both the full URL and the path.
    pub fn add_mock_sync<F>(&self, pattern: &str, handler: F)
    where
        F: Fn(&MockRequest) -> MockResponse + Send + Sync + 'static,
    {
        let mut mocks = self.mocks.write().unwrap();
        mocks.push(MockHandler {
            pattern: pattern.to_string(),
            handler: Arc::new(handler),
        });
    }

    /// No wildcards; use `mock_glob` for patterns.
    pub fn mock_exact<F>(&self, url: &str, handler: F)
    where
        F: Fn(&MockRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.add_mock_sync(url, handler);
    }

    /// Add a mock handler with glob pattern (`*` matches any substring).
    ///
    /// Register specific patterns before broad ones — first match wins.
    pub fn mock_glob<F>(&self, pattern: &str, handler: F)
    where
        F: Fn(&MockRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.add_mock_sync(pattern, handler);
    }

    pub fn add_mock_boxed(&mut self, pattern: &str, handler: BoxedHandler) {
        let mut mocks = self.mocks.write().unwrap();
        mocks.push(MockHandler {
            pattern: pattern.to_string(),
            handler: Arc::from(handler),
        });
    }

    pub async fn execute(&self, request: MockRequest) -> MockResponse {
        {
            let mut requests = self.requests.write().unwrap();
            requests.push(RecordedRequest {
                method: request.method.clone(),
                url: request.url.clone(),
                headers: request.headers.clone(),
                body: request.body.clone(),
            });
        }

        let mocks = self.mocks.read().unwrap();
        for mock in mocks.iter() {
            if self.matches_pattern(&request.url, &mock.pattern)
                || self.matches_pattern(&request.path, &mock.pattern)
            {
                return (mock.handler)(&request);
            }
        }

        MockResponse::error(500, &format!("No mock found for {}", request.url))
    }

    fn matches_pattern(&self, url: &str, pattern: &str) -> bool {
        let pattern_parts: Vec<&str> = pattern.split('*').collect();
        if pattern_parts.len() == 1 {
            return url == pattern;
        }

        let mut remaining = url;
        for (i, part) in pattern_parts.iter().enumerate() {
            if part.is_empty() {
                continue;
            }

            if i == 0 {
                if !remaining.starts_with(part) {
                    return false;
                }
                remaining = &remaining[part.len()..];
            } else if i == pattern_parts.len() - 1 {
                if !remaining.ends_with(part) {
                    return false;
                }
            } else if let Some(pos) = remaining.find(part) {
                remaining = &remaining[pos + part.len()..];
            } else {
                return false;
            }
        }

        true
    }

    pub fn requests(&self) -> Vec<RecordedRequest> {
        self.requests.read().unwrap().clone()
    }

    pub fn requests_blocking(&self) -> Vec<RecordedRequest> {
        self.requests.read().unwrap().clone()
    }

    pub fn requests_to(&self, pattern: &str) -> Vec<RecordedRequest> {
        self.requests
            .read()
            .unwrap()
            .iter()
            .filter(|r| self.matches_pattern(&r.url, pattern))
            .cloned()
            .collect()
    }

    pub fn clear_requests(&self) {
        self.requests.write().unwrap().clear();
    }

    pub fn clear_mocks(&self) {
        self.mocks.write().unwrap().clear();
    }

    /// Assert that a URL pattern was called.
    pub fn assert_called(&self, pattern: &str) {
        let requests = self.requests_blocking();
        let matching = requests
            .iter()
            .filter(|r| self.matches_pattern(&r.url, pattern))
            .count();
        assert!(
            matching > 0,
            "Expected HTTP call matching '{}', but none found. Recorded requests: {:?}",
            pattern,
            requests.iter().map(|r| &r.url).collect::<Vec<_>>()
        );
    }

    /// Assert that a URL pattern was called a specific number of times.
    pub fn assert_called_times(&self, pattern: &str, expected: usize) {
        let requests = self.requests_blocking();
        let matching = requests
            .iter()
            .filter(|r| self.matches_pattern(&r.url, pattern))
            .count();
        assert_eq!(
            matching, expected,
            "Expected {} HTTP calls matching '{}', but found {}",
            expected, pattern, matching
        );
    }

    /// Assert that a URL pattern was not called.
    pub fn assert_not_called(&self, pattern: &str) {
        let requests = self.requests_blocking();
        let matching = requests
            .iter()
            .filter(|r| self.matches_pattern(&r.url, pattern))
            .count();
        assert_eq!(
            matching, 0,
            "Expected no HTTP calls matching '{}', but found {}",
            pattern, matching
        );
    }

    /// Assert that a request was made with specific body content.
    pub fn assert_called_with_body<F>(&self, pattern: &str, predicate: F)
    where
        F: Fn(&serde_json::Value) -> bool,
    {
        let requests = self.requests_blocking();
        let matching = requests
            .iter()
            .filter(|r| self.matches_pattern(&r.url, pattern) && predicate(&r.body));
        assert!(
            matching.count() > 0,
            "Expected HTTP call matching '{}' with matching body, but none found",
            pattern
        );
    }
}

impl Default for MockHttp {
    fn default() -> Self {
        Self::new()
    }
}

pub struct MockHttpBuilder {
    mocks: Vec<(String, BoxedHandler)>,
}

impl MockHttpBuilder {
    pub fn new() -> Self {
        Self { mocks: Vec::new() }
    }

    pub fn mock<F>(mut self, pattern: &str, handler: F) -> Self
    where
        F: Fn(&MockRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.mocks.push((pattern.to_string(), Box::new(handler)));
        self
    }

    pub fn mock_json<T: Serialize + Clone + Send + Sync + 'static>(
        self,
        pattern: &str,
        response: T,
    ) -> Self {
        self.mock(pattern, move |_| MockResponse::json(response.clone()))
    }

    pub fn build(self) -> MockHttp {
        let mut mock = MockHttp::new();
        for (pattern, handler) in self.mocks {
            mock.add_mock_boxed(&pattern, handler);
        }
        mock
    }
}

impl Default for MockHttpBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_mock_response_json() {
        let response = MockResponse::json(serde_json::json!({"id": 123}));
        assert_eq!(response.status, 200);
        assert_eq!(response.body["id"], 123);
    }

    #[test]
    fn test_mock_response_error() {
        let response = MockResponse::error(404, "Not found");
        assert_eq!(response.status, 404);
        assert_eq!(response.body["error"], "Not found");
    }

    #[test]
    fn test_pattern_matching() {
        let mock = MockHttp::new();

        assert!(mock.matches_pattern(
            "https://api.example.com/users",
            "https://api.example.com/users"
        ));

        assert!(mock.matches_pattern(
            "https://api.example.com/users/123",
            "https://api.example.com/*"
        ));

        assert!(mock.matches_pattern(
            "https://api.example.com/v2/users",
            "https://api.example.com/*/users"
        ));

        assert!(!mock.matches_pattern("https://other.com/users", "https://api.example.com/*"));
    }

    #[tokio::test]
    async fn test_mock_execution() {
        let mock = MockHttp::new();
        mock.add_mock_sync("https://api.example.com/*", |_| {
            MockResponse::json(serde_json::json!({"status": "ok"}))
        });

        let request = MockRequest {
            method: "GET".to_string(),
            path: "/users".to_string(),
            url: "https://api.example.com/users".to_string(),
            headers: HashMap::new(),
            body: serde_json::Value::Null,
        };

        let response = mock.execute(request).await;
        assert_eq!(response.status, 200);
        assert_eq!(response.body["status"], "ok");
    }

    #[tokio::test]
    async fn test_request_recording() {
        let mock = MockHttp::new();
        mock.add_mock_sync("*", |_| MockResponse::ok());

        let request = MockRequest {
            method: "POST".to_string(),
            path: "/api/users".to_string(),
            url: "https://api.example.com/users".to_string(),
            headers: HashMap::from([("authorization".to_string(), "Bearer token".to_string())]),
            body: serde_json::json!({"name": "Test"}),
        };

        let _ = mock.execute(request).await;

        let requests = mock.requests();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0].method, "POST");
        assert_eq!(requests[0].body["name"], "Test");
    }

    #[tokio::test]
    async fn test_assert_called() {
        let mock = MockHttp::new();
        mock.add_mock_sync("*", |_| MockResponse::ok());

        let request = MockRequest {
            method: "GET".to_string(),
            path: "/test".to_string(),
            url: "https://api.example.com/test".to_string(),
            headers: HashMap::new(),
            body: serde_json::Value::Null,
        };

        let _ = mock.execute(request).await;

        mock.assert_called("https://api.example.com/*");
        mock.assert_called_times("https://api.example.com/*", 1);
        mock.assert_not_called("https://other.com/*");
    }

    #[test]
    fn test_builder() {
        let mock = MockHttpBuilder::new()
            .mock("https://api.example.com/*", |_| MockResponse::ok())
            .mock_json("https://other.com/*", serde_json::json!({"id": 1}))
            .build();

        assert_eq!(mock.mocks.read().unwrap().len(), 2);
    }

    fn req(method: &str, url: &str, path: &str) -> MockRequest {
        MockRequest {
            method: method.to_string(),
            path: path.to_string(),
            url: url.to_string(),
            headers: HashMap::new(),
            body: serde_json::Value::Null,
        }
    }

    #[test]
    fn response_status_helpers_use_documented_codes() {
        assert_eq!(MockResponse::internal_error("boom").status, 500);
        assert_eq!(MockResponse::not_found("nope").status, 404);
        assert_eq!(MockResponse::unauthorized("nope").status, 401);
        assert_eq!(MockResponse::ok().status, 200);

        // ok() returns an empty JSON object — handlers that key off body shape
        // (e.g., serde to () or empty struct) rely on this.
        assert_eq!(MockResponse::ok().body, serde_json::json!({}));
    }

    #[test]
    fn response_json_sets_content_type_header() {
        let r = MockResponse::json(serde_json::json!({"ok": true}));
        assert_eq!(
            r.headers.get("content-type"),
            Some(&"application/json".to_string())
        );
    }

    #[test]
    fn pattern_matcher_handles_leading_and_double_wildcards() {
        let m = MockHttp::new();
        // Leading wildcard (pattern_parts[0] is empty).
        assert!(m.matches_pattern("https://api.example.com/v1/users", "*/users"));
        assert!(!m.matches_pattern("https://api.example.com/v1/posts", "*/users"));

        // Bare `*` matches anything (both pattern parts are empty strings).
        assert!(m.matches_pattern("anything", "*"));
        assert!(m.matches_pattern("", "*"));
    }

    #[test]
    fn pattern_matcher_rejects_exact_pattern_with_extra_suffix() {
        let m = MockHttp::new();
        assert!(!m.matches_pattern(
            "https://api.example.com/users/extra",
            "https://api.example.com/users"
        ));
    }

    #[tokio::test]
    async fn execute_falls_back_to_500_when_no_mock_matches() {
        let mock = MockHttp::new();
        let r = mock.execute(req("GET", "https://nowhere/", "/")).await;
        assert_eq!(r.status, 500);
        assert!(
            r.body["error"]
                .as_str()
                .unwrap_or_default()
                .contains("No mock found"),
            "fallback should explain the failure, got {:?}",
            r.body
        );
    }

    #[tokio::test]
    async fn execute_records_request_even_when_no_mock_matches() {
        // The recording happens before the lookup so failed-match calls still
        // show up in requests() — important for diagnosing "why didn't my mock fire".
        let mock = MockHttp::new();
        let _ = mock.execute(req("DELETE", "https://nowhere/x", "/x")).await;
        let recorded = mock.requests();
        assert_eq!(recorded.len(), 1);
        assert_eq!(recorded[0].method, "DELETE");
        assert_eq!(recorded[0].url, "https://nowhere/x");
    }

    #[tokio::test]
    async fn execute_matches_against_path_when_url_misses() {
        // Pattern only matches the path, not the full URL.
        let mock = MockHttp::new();
        mock.add_mock_sync("/health", |_| MockResponse::ok());
        let r = mock
            .execute(req("GET", "https://internal.svc:8080/health", "/health"))
            .await;
        assert_eq!(r.status, 200);
    }

    #[tokio::test]
    async fn execute_uses_first_registered_mock_on_overlapping_patterns() {
        let mock = MockHttp::new();
        mock.add_mock_sync("https://api.example.com/*", |_| {
            MockResponse::json(serde_json::json!({"hit": "first"}))
        });
        mock.add_mock_sync("https://api.example.com/users", |_| {
            MockResponse::json(serde_json::json!({"hit": "second"}))
        });

        let r = mock
            .execute(req("GET", "https://api.example.com/users", "/users"))
            .await;
        assert_eq!(r.body["hit"], "first");
    }

    #[tokio::test]
    async fn requests_to_filters_by_pattern() {
        let mock = MockHttp::new();
        mock.add_mock_sync("*", |_| MockResponse::ok());

        let _ = mock
            .execute(req("GET", "https://api.example.com/a", "/a"))
            .await;
        let _ = mock.execute(req("GET", "https://other.com/b", "/b")).await;
        let _ = mock
            .execute(req("GET", "https://api.example.com/c", "/c"))
            .await;

        let api_calls = mock.requests_to("https://api.example.com/*");
        assert_eq!(api_calls.len(), 2);
        assert!(api_calls.iter().all(|r| r.url.contains("api.example.com")));
    }

    #[tokio::test]
    async fn clear_requests_and_clear_mocks_independently_reset_state() {
        let mock = MockHttp::new();
        mock.add_mock_sync("*", |_| MockResponse::ok());
        let _ = mock.execute(req("GET", "https://x/", "/")).await;
        assert_eq!(mock.requests().len(), 1);

        mock.clear_requests();
        assert!(mock.requests().is_empty());
        // Mocks survive a requests-only clear; the next call should still match.
        let r = mock.execute(req("GET", "https://x/", "/")).await;
        assert_eq!(r.status, 200);

        mock.clear_mocks();
        let r = mock.execute(req("GET", "https://x/", "/")).await;
        assert_eq!(r.status, 500, "after clear_mocks, fallback should hit");
    }

    #[tokio::test]
    async fn assert_called_with_body_runs_predicate_against_recorded_body() {
        let mock = MockHttp::new();
        mock.add_mock_sync("*", |_| MockResponse::ok());

        let mut request = req("POST", "https://api/upload", "/upload");
        request.body = serde_json::json!({"size": 42});
        let _ = mock.execute(request).await;

        // Predicate matches — should not panic.
        mock.assert_called_with_body("https://api/*", |body| body["size"] == 42);
    }

    #[test]
    fn defaults_match_new() {
        // Default impls are wrappers around new(); just exercise them so the
        // Default path doesn't silently rot.
        let m1 = MockHttp::default();
        assert!(m1.requests().is_empty());
        let b1 = MockHttpBuilder::default();
        let m2 = b1.build();
        assert!(m2.requests().is_empty());
    }
}