mockforge-sdk 0.3.115

Developer SDK for embedding MockForge in tests and applications
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! Mock server implementation
#![allow(clippy::missing_errors_doc, clippy::too_many_lines)]

use crate::builder::MockServerBuilder;
use crate::stub::ResponseStub;
use crate::{Error, Result};
use axum::Router;
use mockforge_core::config::{RouteConfig, RouteResponseConfig};
use mockforge_core::{Config, ServerConfig};
use serde_json::Value;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::RwLock;
use tokio::task::JoinHandle;

/// A stored stub configuration for runtime matching
#[derive(Debug, Clone)]
struct StoredStub {
    method: String,
    path: String,
    status: u16,
    headers: HashMap<String, String>,
    body: Value,
}

/// Shared stub store for runtime stub management
type StubStore = Arc<RwLock<Vec<StoredStub>>>;

/// A mock server that can be embedded in tests
///
/// The mock server supports dynamically adding stubs at runtime after the server
/// has started. Stubs added via `stub_response()` or `add_stub()` will be served
/// by a fallback handler that matches requests against the stub store.
pub struct MockServer {
    port: u16,
    address: SocketAddr,
    config: ServerConfig,
    server_handle: Option<JoinHandle<()>>,
    shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
    routes: Vec<RouteConfig>,
    /// Shared stub store for runtime updates
    stub_store: StubStore,
}

impl MockServer {
    /// Create a new mock server builder
    #[must_use]
    #[allow(clippy::new_ret_no_self)]
    pub const fn new() -> MockServerBuilder {
        MockServerBuilder::new()
    }

    /// Create a mock server from configuration
    pub(crate) fn from_config(server_config: ServerConfig, _core_config: Config) -> Result<Self> {
        let port = server_config.http.port;
        let host = server_config.http.host.clone();

        let address: SocketAddr = format!("{host}:{port}")
            .parse()
            .map_err(|e| Error::InvalidConfig(format!("Invalid address: {e}")))?;

        Ok(Self {
            port,
            address,
            config: server_config,
            server_handle: None,
            shutdown_tx: None,
            routes: Vec::new(),
            stub_store: Arc::new(RwLock::new(Vec::new())),
        })
    }

    /// Start the mock server
    ///
    /// # Panics
    ///
    /// Panics if the internal axum server task encounters an error.
    pub async fn start(&mut self) -> Result<()> {
        if self.server_handle.is_some() {
            return Err(Error::ServerAlreadyStarted(self.port));
        }

        // Build the router with the shared stub store
        let router = self.build_simple_router(self.stub_store.clone());

        // Create shutdown channel
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
        self.shutdown_tx = Some(shutdown_tx);

        // Bind the listener BEFORE spawning so we can get the actual address
        // This is important for port 0 (auto-assign) to work correctly
        let listener = tokio::net::TcpListener::bind(self.address)
            .await
            .map_err(|e| Error::General(format!("Failed to bind to {}: {e}", self.address)))?;

        // Get the actual bound address (important when using port 0)
        let actual_address = listener
            .local_addr()
            .map_err(|e| Error::General(format!("Failed to get local address: {e}")))?;

        // Update our address and port with the actual bound values
        self.address = actual_address;
        self.port = actual_address.port();

        tracing::info!("MockForge SDK server listening on {}", actual_address);

        // Spawn the server with the already-bound listener
        let server_handle = tokio::spawn(async move {
            axum::serve(listener, router)
                .with_graceful_shutdown(async move {
                    let _ = shutdown_rx.await;
                })
                .await
                .expect("Server error");
        });

        self.server_handle = Some(server_handle);

        // Wait for the server to be ready by polling health
        self.wait_for_ready().await?;

        Ok(())
    }

    /// Wait for the server to be ready
    async fn wait_for_ready(&self) -> Result<()> {
        let max_attempts = 50;
        let delay = tokio::time::Duration::from_millis(100);

        for attempt in 0..max_attempts {
            // Try to connect to the server
            let client = reqwest::Client::builder()
                .timeout(tokio::time::Duration::from_millis(100))
                .build()
                .map_err(|e| Error::General(format!("Failed to create HTTP client: {e}")))?;

            match client.get(format!("{}/health", self.url())).send().await {
                Ok(response) if response.status().is_success() => return Ok(()),
                _ => {
                    if attempt < max_attempts - 1 {
                        tokio::time::sleep(delay).await;
                    }
                }
            }
        }

        let timeout_ms = u32::try_from(delay.as_millis()).unwrap_or(u32::MAX);
        Err(Error::General(format!(
            "Server failed to become ready within {}ms",
            max_attempts * timeout_ms
        )))
    }

    /// Build a simple router from stored routes
    fn build_simple_router(&self, stub_store: StubStore) -> Router {
        use axum::extract::{Path, Request};
        use axum::http::StatusCode;
        use axum::routing::{delete, get, post, put};
        use axum::{response::IntoResponse, Json};

        // Shared state for admin API (separate from stub store)
        type MockStore = Arc<RwLock<HashMap<String, Value>>>;
        let mock_store: MockStore = Arc::new(RwLock::new(HashMap::new()));

        // Admin API handlers
        let store_for_list = mock_store.clone();
        let list_mocks = move || {
            let store = store_for_list.clone();
            async move {
                let items: Vec<Value> = store.read().await.values().cloned().collect();
                let total = items.len();
                Json(serde_json::json!({
                    "mocks": items,
                    "total": total,
                    "enabled": total  // All mocks are enabled by default
                }))
            }
        };

        let store_for_create = mock_store.clone();
        let create_mock = move |Json(mut mock): Json<Value>| {
            let store = store_for_create.clone();
            async move {
                let id = mock
                    .get("id")
                    .and_then(|v| v.as_str())
                    .filter(|s| !s.is_empty())
                    .map_or_else(|| uuid::Uuid::new_v4().to_string(), String::from);
                mock["id"] = serde_json::json!(id);
                store.write().await.insert(id, mock.clone());
                (StatusCode::CREATED, Json(mock))
            }
        };

        let store_for_get = mock_store.clone();
        let get_mock = move |Path(id): Path<String>| {
            let store = store_for_get.clone();
            async move {
                store.read().await.get(&id).map_or_else(
                    || StatusCode::NOT_FOUND.into_response(),
                    |mock| (StatusCode::OK, Json(mock.clone())).into_response(),
                )
            }
        };

        let store_for_update = mock_store.clone();
        let update_mock = move |Path(id): Path<String>, Json(mut mock): Json<Value>| {
            let store = store_for_update.clone();
            async move {
                mock["id"] = serde_json::json!(id.clone());
                store.write().await.insert(id, mock.clone());
                Json(mock)
            }
        };

        let store_for_delete = mock_store.clone();
        let delete_mock = move |Path(id): Path<String>| {
            let store = store_for_delete.clone();
            async move {
                store.write().await.remove(&id);
                StatusCode::NO_CONTENT
            }
        };

        let get_stats = move || {
            let store = mock_store.clone();
            async move {
                let count = store.read().await.len();
                Json(serde_json::json!({
                    "uptime_seconds": 1,  // Minimum uptime for tests
                    "total_requests": 0,
                    "active_mocks": count,
                    "enabled_mocks": count,
                    "registered_routes": count
                }))
            }
        };

        // Fallback handler that matches against dynamically added stubs
        let fallback_handler = move |request: Request| {
            let stub_store = stub_store.clone();
            async move {
                let method = request.method().to_string();
                let path = request.uri().path().to_string();

                // Search for a matching stub, cloning out before dropping the lock
                let matching_stub = stub_store
                    .read()
                    .await
                    .iter()
                    .find(|s| s.method.eq_ignore_ascii_case(&method) && s.path == path)
                    .cloned();

                if let Some(stub) = matching_stub {
                    let mut response = Json(stub.body).into_response();
                    *response.status_mut() =
                        StatusCode::from_u16(stub.status).unwrap_or(StatusCode::OK);

                    for (key, value) in &stub.headers {
                        if let Ok(header_name) = axum::http::HeaderName::from_bytes(key.as_bytes())
                        {
                            if let Ok(header_value) = axum::http::HeaderValue::from_str(value) {
                                response.headers_mut().insert(header_name, header_value);
                            }
                        }
                    }

                    return response;
                }

                // No matching stub found
                StatusCode::NOT_FOUND.into_response()
            }
        };

        // Start with health and admin API endpoints
        let mut router = Router::new()
            .route("/health", get(|| async { (StatusCode::OK, "OK") }))
            .route("/api/mocks", get(list_mocks).post(create_mock))
            .route("/api/mocks/{id}", get(get_mock).put(update_mock).delete(delete_mock))
            .route("/api/stats", get(get_stats));

        // Add pre-defined routes (added before server start)
        for route_config in &self.routes {
            let status = route_config.response.status;
            let body = route_config.response.body.clone();
            let headers = route_config.response.headers.clone();

            let handler = move || {
                let body = body.clone();
                let headers = headers.clone();
                async move {
                    let mut response = Json(body).into_response();
                    *response.status_mut() = StatusCode::from_u16(status).unwrap();

                    for (key, value) in headers {
                        if let Ok(header_name) = axum::http::HeaderName::from_bytes(key.as_bytes())
                        {
                            if let Ok(header_value) = axum::http::HeaderValue::from_str(&value) {
                                response.headers_mut().insert(header_name, header_value);
                            }
                        }
                    }

                    response
                }
            };

            let path = &route_config.path;

            router = match route_config.method.to_uppercase().as_str() {
                "GET" => router.route(path, get(handler)),
                "POST" => router.route(path, post(handler)),
                "PUT" => router.route(path, put(handler)),
                "DELETE" => router.route(path, delete(handler)),
                _ => router,
            };
        }

        // Add fallback for dynamically added stubs
        router.fallback(fallback_handler)
    }

    /// Stop the mock server
    pub async fn stop(mut self) -> Result<()> {
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }

        if let Some(handle) = self.server_handle.take() {
            let _ = handle.await;
        }

        Ok(())
    }

    /// Stub a response for a given method and path
    pub async fn stub_response(
        &mut self,
        method: impl Into<String>,
        path: impl Into<String>,
        body: Value,
    ) -> Result<()> {
        let stub = ResponseStub::new(method, path, body);
        self.add_stub(stub).await
    }

    /// Add a response stub
    ///
    /// Stubs can be added before or after the server starts.
    /// Stubs added after start are served via a fallback handler.
    pub async fn add_stub(&mut self, stub: ResponseStub) -> Result<()> {
        // Add to the shared stub store (works at runtime)
        let stored_stub = StoredStub {
            method: stub.method.clone(),
            path: stub.path.clone(),
            status: stub.status,
            headers: stub.headers.clone(),
            body: stub.body.clone(),
        };
        self.stub_store.write().await.push(stored_stub);

        // Also add to routes for pre-start configuration
        let route_config = RouteConfig {
            path: stub.path.clone(),
            method: stub.method,
            request: None,
            response: RouteResponseConfig {
                status: stub.status,
                headers: stub.headers,
                body: Some(stub.body),
            },
            fault_injection: None,
            latency: None,
        };

        self.routes.push(route_config);

        Ok(())
    }

    /// Remove all stubs
    pub async fn clear_stubs(&mut self) -> Result<()> {
        self.routes.clear();
        self.stub_store.write().await.clear();
        Ok(())
    }

    /// Get the server port
    #[must_use]
    pub const fn port(&self) -> u16 {
        self.port
    }

    /// Get the server base URL
    ///
    /// Note: If the server is bound to `0.0.0.0` (all interfaces),
    /// this returns `127.0.0.1` as the host for client connections.
    #[must_use]
    pub fn url(&self) -> String {
        // 0.0.0.0 means "bind to all interfaces" but isn't a valid connection target
        // Convert to localhost for client connections
        if self.address.ip().is_unspecified() {
            format!("http://127.0.0.1:{}", self.address.port())
        } else {
            format!("http://{}", self.address)
        }
    }

    /// Check if the server is running
    #[must_use]
    pub const fn is_running(&self) -> bool {
        self.server_handle.is_some()
    }
}

impl Default for MockServer {
    fn default() -> Self {
        Self {
            port: 0,
            address: "127.0.0.1:0".parse().unwrap(),
            config: ServerConfig::default(),
            server_handle: None,
            shutdown_tx: None,
            routes: Vec::new(),
            stub_store: Arc::new(RwLock::new(Vec::new())),
        }
    }
}

impl std::fmt::Debug for MockServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MockServer")
            .field("port", &self.port)
            .field("address", &self.address)
            .field("is_running", &self.server_handle.is_some())
            .field("routes_count", &self.routes.len())
            .finish_non_exhaustive()
    }
}

// Implement Drop to ensure server is stopped
impl Drop for MockServer {
    fn drop(&mut self) {
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::mem::{size_of, size_of_val};

    #[test]
    fn test_mock_server_new() {
        let builder = MockServer::new();
        // Should return a MockServerBuilder
        assert_eq!(size_of_val(&builder), size_of::<MockServerBuilder>());
    }

    #[test]
    fn test_mock_server_default() {
        let server = MockServer::default();
        assert_eq!(server.port, 0);
        assert!(!server.is_running());
        assert!(server.routes.is_empty());
    }

    #[test]
    fn test_mock_server_port() {
        let server = MockServer::default();
        assert_eq!(server.port(), 0);
    }

    #[test]
    fn test_mock_server_url() {
        let mut server = MockServer::default();
        server.port = 8080;
        server.address = "127.0.0.1:8080".parse().unwrap();
        assert_eq!(server.url(), "http://127.0.0.1:8080");
    }

    #[test]
    fn test_mock_server_is_running_false() {
        let server = MockServer::default();
        assert!(!server.is_running());
    }

    #[test]
    fn test_from_config_valid() {
        let server_config = ServerConfig::default();
        let core_config = Config::default();

        let result = MockServer::from_config(server_config, core_config);
        assert!(result.is_ok());

        let server = result.unwrap();
        assert!(!server.is_running());
        assert!(server.routes.is_empty());
    }

    #[test]
    fn test_from_config_invalid_address() {
        let mut server_config = ServerConfig::default();
        server_config.http.host = "invalid host with spaces".to_string();
        let core_config = Config::default();

        let result = MockServer::from_config(server_config, core_config);
        assert!(result.is_err());
        match result {
            Err(Error::InvalidConfig(msg)) => {
                assert!(msg.contains("Invalid address"));
            }
            _ => panic!("Expected InvalidConfig error"),
        }
    }

    #[tokio::test]
    async fn test_add_stub() {
        let mut server = MockServer::default();
        let stub = ResponseStub::new("GET", "/api/test", json!({"test": true}));

        let result = server.add_stub(stub.clone()).await;
        assert!(result.is_ok());
        assert_eq!(server.routes.len(), 1);

        let route = &server.routes[0];
        assert_eq!(route.path, "/api/test");
        assert_eq!(route.method, "GET");
        assert_eq!(route.response.status, 200);
    }

    #[tokio::test]
    async fn test_add_stub_with_custom_status() {
        let mut server = MockServer::default();
        let stub = ResponseStub::new("POST", "/api/create", json!({"created": true})).status(201);

        let result = server.add_stub(stub).await;
        assert!(result.is_ok());
        assert_eq!(server.routes.len(), 1);

        let route = &server.routes[0];
        assert_eq!(route.response.status, 201);
    }

    #[tokio::test]
    async fn test_add_stub_with_headers() {
        let mut server = MockServer::default();
        let stub = ResponseStub::new("GET", "/api/test", json!({}))
            .header("Content-Type", "application/json")
            .header("X-Custom", "value");

        let result = server.add_stub(stub).await;
        assert!(result.is_ok());

        let route = &server.routes[0];
        assert_eq!(
            route.response.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
        assert_eq!(route.response.headers.get("X-Custom"), Some(&"value".to_string()));
    }

    #[tokio::test]
    async fn test_stub_response() {
        let mut server = MockServer::default();

        let result = server.stub_response("GET", "/api/users", json!({"users": []})).await;
        assert!(result.is_ok());
        assert_eq!(server.routes.len(), 1);

        let route = &server.routes[0];
        assert_eq!(route.path, "/api/users");
        assert_eq!(route.method, "GET");
    }

    #[tokio::test]
    async fn test_clear_stubs() {
        let mut server = MockServer::default();

        server.stub_response("GET", "/api/test1", json!({})).await.unwrap();
        server.stub_response("POST", "/api/test2", json!({})).await.unwrap();
        assert_eq!(server.routes.len(), 2);

        let result = server.clear_stubs().await;
        assert!(result.is_ok());
        assert_eq!(server.routes.len(), 0);
    }

    #[tokio::test]
    async fn test_multiple_stubs() {
        let mut server = MockServer::default();

        server.stub_response("GET", "/api/users", json!({"users": []})).await.unwrap();
        server
            .stub_response("POST", "/api/users", json!({"created": true}))
            .await
            .unwrap();
        server
            .stub_response("DELETE", "/api/users/1", json!({"deleted": true}))
            .await
            .unwrap();

        assert_eq!(server.routes.len(), 3);

        assert_eq!(server.routes[0].method, "GET");
        assert_eq!(server.routes[1].method, "POST");
        assert_eq!(server.routes[2].method, "DELETE");
    }

    #[test]
    fn test_build_simple_router_empty() {
        let server = MockServer::default();
        let router = server.build_simple_router(server.stub_store.clone());
        // Router should be created without panicking
        assert_eq!(size_of_val(&router), size_of::<Router>());
    }

    #[tokio::test]
    async fn test_build_simple_router_with_routes() {
        let mut server = MockServer::default();
        server.stub_response("GET", "/test", json!({"test": true})).await.unwrap();
        server.stub_response("POST", "/create", json!({"created": true})).await.unwrap();

        let router = server.build_simple_router(server.stub_store.clone());
        // Router should be built with the routes
        assert_eq!(size_of_val(&router), size_of::<Router>());
    }

    #[tokio::test]
    async fn test_start_server_already_started() {
        // Use port 0 for OS assignment - the server now properly updates
        // self.address after binding
        let mut server = MockServer::default();
        server.port = 0;
        server.address = "127.0.0.1:0".parse().unwrap();

        // Start the server
        let result = server.start().await;
        assert!(result.is_ok(), "Failed to start server: {:?}", result.err());
        assert!(server.is_running());

        // Verify the port was updated from 0 to an actual port
        assert_ne!(server.port, 0, "Port should have been updated from 0");

        // Try to start again
        let result2 = server.start().await;
        assert!(result2.is_err());
        match result2 {
            Err(Error::ServerAlreadyStarted(_)) => (),
            _ => panic!("Expected ServerAlreadyStarted error"),
        }

        // Clean up
        let _ = Box::pin(server.stop()).await;
    }

    #[test]
    fn test_server_debug_format() {
        let server = MockServer::default();
        let debug_str = format!("{server:?}");
        assert!(debug_str.contains("MockServer"));
    }

    #[tokio::test]
    async fn test_route_config_conversion() {
        let mut server = MockServer::default();
        let stub = ResponseStub::new("PUT", "/api/update", json!({"updated": true}))
            .status(200)
            .header("X-Version", "1.0");

        server.add_stub(stub).await.unwrap();

        let route = &server.routes[0];
        assert_eq!(route.path, "/api/update");
        assert_eq!(route.method, "PUT");
        assert_eq!(route.response.status, 200);
        assert_eq!(route.response.headers.get("X-Version"), Some(&"1.0".to_string()));
        assert!(route.response.body.is_some());
        assert_eq!(route.response.body, Some(json!({"updated": true})));
    }

    #[tokio::test]
    async fn test_server_with_different_methods() {
        let mut server = MockServer::default();

        server.stub_response("GET", "/test", json!({})).await.unwrap();
        server.stub_response("POST", "/test", json!({})).await.unwrap();
        server.stub_response("PUT", "/test", json!({})).await.unwrap();
        server.stub_response("DELETE", "/test", json!({})).await.unwrap();
        server.stub_response("PATCH", "/test", json!({})).await.unwrap();

        assert_eq!(server.routes.len(), 5);

        // Verify all methods are different
        let methods: Vec<_> = server.routes.iter().map(|r| r.method.as_str()).collect();
        assert!(methods.contains(&"GET"));
        assert!(methods.contains(&"POST"));
        assert!(methods.contains(&"PUT"));
        assert!(methods.contains(&"DELETE"));
        assert!(methods.contains(&"PATCH"));
    }

    #[tokio::test]
    async fn test_server_url_format() {
        let mut server = MockServer::default();
        server.port = 3000;
        server.address = "127.0.0.1:3000".parse().unwrap();

        let url = server.url();
        assert_eq!(url, "http://127.0.0.1:3000");
        assert!(url.starts_with("http://"));
    }

    #[tokio::test]
    async fn test_server_with_ipv6_address() {
        let mut server = MockServer::default();
        server.port = 8080;
        server.address = "[::1]:8080".parse().unwrap();

        let url = server.url();
        assert_eq!(url, "http://[::1]:8080");
    }
}