mockforge-test 0.3.117

Test utilities for MockForge - easy integration with Playwright and Vitest
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
//! MockForge server management for tests

use crate::config::{ServerConfig, ServerConfigBuilder};
use crate::error::Result;
use crate::health::{HealthCheck, HealthStatus};
use crate::process::{find_available_port, ManagedProcess};
use crate::scenario::ScenarioManager;
use parking_lot::Mutex;
use serde_json::Value;
use std::path::Path;
use std::sync::Arc;
use tracing::{debug, error, info};

/// A managed MockForge server instance for testing
pub struct MockForgeServer {
    process: Arc<Mutex<ManagedProcess>>,
    health: HealthCheck,
    scenario: ScenarioManager,
    http_port: u16,
    ws_port: Option<u16>,
    grpc_port: Option<u16>,
    admin_port: Option<u16>,
    metrics_port: Option<u16>,
}

impl MockForgeServer {
    /// Create a new builder for MockForgeServer
    pub fn builder() -> MockForgeServerBuilder {
        MockForgeServerBuilder::default()
    }

    /// Start a MockForge server with the given configuration
    pub async fn start(config: ServerConfig) -> Result<Self> {
        // Resolve any ports the caller asked us to auto-assign (port == 0).
        // Without this the SDK would forward `--<service>-port 0` to the CLI,
        // which leaves the SDK with no way to know the OS-assigned port — and
        // any test that hardcoded a port (e.g. 9080) would silently talk to a
        // *different* mockforge process if one happened to be running.
        let mut resolved_config = config.clone();
        if resolved_config.http_port == 0 {
            resolved_config.http_port = find_available_port(30000)?;
            info!("Auto-assigned HTTP port: {}", resolved_config.http_port);
        }
        if resolved_config.admin_port == Some(0) {
            let port = find_available_port(31000)?;
            resolved_config.admin_port = Some(port);
            info!("Auto-assigned admin port: {}", port);
        }
        if resolved_config.metrics_port == Some(0) {
            let port = find_available_port(32000)?;
            resolved_config.metrics_port = Some(port);
            info!("Auto-assigned metrics port: {}", port);
        }
        // The mockforge CLI always starts a WS server (default 3001) and gRPC
        // server (default 50051) even when not explicitly requested. When
        // multiple test instances spin up in parallel, all of them race for
        // those default ports — and lose. Auto-assign whenever the caller
        // didn't pin them, so each test gets its own private ports.
        if resolved_config.ws_port.is_none() || resolved_config.ws_port == Some(0) {
            let port = find_available_port(33000)?;
            resolved_config.ws_port = Some(port);
            info!("Auto-assigned WebSocket port: {}", port);
        }
        if resolved_config.grpc_port.is_none() || resolved_config.grpc_port == Some(0) {
            let port = find_available_port(34000)?;
            resolved_config.grpc_port = Some(port);
            info!("Auto-assigned gRPC port: {}", port);
        }

        // Spawn the process
        let process = ManagedProcess::spawn(&resolved_config)?;
        let http_port = process.http_port();

        info!("MockForge server started on port {}", http_port);

        // Create health check client
        let health = HealthCheck::new("localhost", http_port);

        // Wait for server to become healthy
        debug!("Waiting for server to become healthy...");
        health
            .wait_until_healthy(resolved_config.health_timeout, resolved_config.health_interval)
            .await?;

        info!("MockForge server is healthy and ready");

        // Create scenario manager
        let scenario = ScenarioManager::new("localhost", http_port);

        Ok(Self {
            process: Arc::new(Mutex::new(process)),
            health,
            scenario,
            http_port,
            ws_port: resolved_config.ws_port,
            grpc_port: resolved_config.grpc_port,
            admin_port: resolved_config.admin_port,
            metrics_port: resolved_config.metrics_port,
        })
    }

    /// Get the HTTP port the server is running on
    pub fn http_port(&self) -> u16 {
        self.http_port
    }

    /// Get the WebSocket port if configured
    pub fn ws_port(&self) -> Option<u16> {
        self.ws_port
    }

    /// Get the gRPC port if configured
    pub fn grpc_port(&self) -> Option<u16> {
        self.grpc_port
    }

    /// Get the admin UI port if admin was enabled.
    ///
    /// When the builder set `.admin_port(0)` this returns the
    /// auto-assigned port; when the builder set a specific port it
    /// returns that port; when the builder didn't enable admin at all
    /// it returns `None`.
    pub fn admin_port(&self) -> Option<u16> {
        self.admin_port
    }

    /// Get the metrics endpoint port if metrics was enabled.
    pub fn metrics_port(&self) -> Option<u16> {
        self.metrics_port
    }

    /// Get the base URL of the server
    pub fn base_url(&self) -> String {
        format!("http://localhost:{}", self.http_port)
    }

    /// Get the WebSocket URL if WebSocket is enabled
    pub fn ws_url(&self) -> Option<String> {
        self.ws_port.map(|port| format!("ws://localhost:{}/ws", port))
    }

    /// Get the process ID
    pub fn pid(&self) -> u32 {
        self.process.lock().pid()
    }

    /// Check if the server is still running
    pub fn is_running(&self) -> bool {
        self.process.lock().is_running()
    }

    /// Perform a health check
    pub async fn health_check(&self) -> Result<HealthStatus> {
        self.health.check().await
    }

    /// Check if the server is ready
    pub async fn is_ready(&self) -> bool {
        self.health.is_ready().await
    }

    /// Switch to a different scenario/workspace
    ///
    /// # Arguments
    ///
    /// * `scenario_name` - Name of the scenario to switch to
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use mockforge_test::MockForgeServer;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let server = MockForgeServer::builder().build().await?;
    /// server.scenario("user-auth-success").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn scenario(&self, scenario_name: &str) -> Result<()> {
        self.scenario.switch_scenario(scenario_name).await
    }

    /// Load a workspace configuration from a file
    pub async fn load_workspace<P: AsRef<Path>>(&self, workspace_file: P) -> Result<()> {
        self.scenario.load_workspace(workspace_file).await
    }

    /// Update mock configuration for a specific endpoint
    pub async fn update_mock(&self, endpoint: &str, config: Value) -> Result<()> {
        self.scenario.update_mock(endpoint, config).await
    }

    /// List available fixtures
    pub async fn list_fixtures(&self) -> Result<Vec<String>> {
        self.scenario.list_fixtures().await
    }

    /// Get server statistics
    pub async fn get_stats(&self) -> Result<Value> {
        self.scenario.get_stats().await
    }

    /// Reset all mocks to their initial state
    pub async fn reset(&self) -> Result<()> {
        self.scenario.reset().await
    }

    /// Stop the server
    pub fn stop(&self) -> Result<()> {
        info!("Stopping MockForge server (port: {})", self.http_port);
        self.process.lock().kill()
    }
}

impl Drop for MockForgeServer {
    fn drop(&mut self) {
        if let Err(e) = self.stop() {
            error!("Failed to stop MockForge server on drop: {}", e);
        }
    }
}

/// Builder for MockForgeServer
pub struct MockForgeServerBuilder {
    config_builder: ServerConfigBuilder,
}

impl Default for MockForgeServerBuilder {
    fn default() -> Self {
        Self {
            config_builder: ServerConfig::builder(),
        }
    }
}

impl MockForgeServerBuilder {
    /// Set HTTP port (0 for auto-assign)
    pub fn http_port(mut self, port: u16) -> Self {
        self.config_builder = self.config_builder.http_port(port);
        self
    }

    /// Set WebSocket port
    pub fn ws_port(mut self, port: u16) -> Self {
        self.config_builder = self.config_builder.ws_port(port);
        self
    }

    /// Set gRPC port
    pub fn grpc_port(mut self, port: u16) -> Self {
        self.config_builder = self.config_builder.grpc_port(port);
        self
    }

    /// Set admin UI port
    pub fn admin_port(mut self, port: u16) -> Self {
        self.config_builder = self.config_builder.admin_port(port);
        self
    }

    /// Set metrics port
    pub fn metrics_port(mut self, port: u16) -> Self {
        self.config_builder = self.config_builder.metrics_port(port);
        self
    }

    /// Set OpenAPI specification file
    pub fn spec_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.config_builder = self.config_builder.spec_file(path);
        self
    }

    /// Set workspace directory
    pub fn workspace_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.config_builder = self.config_builder.workspace_dir(path);
        self
    }

    /// Set profile name
    pub fn profile(mut self, profile: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.profile(profile);
        self
    }

    /// Enable admin UI
    pub fn enable_admin(mut self, enable: bool) -> Self {
        self.config_builder = self.config_builder.enable_admin(enable);
        self
    }

    /// Enable metrics endpoint
    pub fn enable_metrics(mut self, enable: bool) -> Self {
        self.config_builder = self.config_builder.enable_metrics(enable);
        self
    }

    /// Add extra CLI argument
    pub fn extra_arg(mut self, arg: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.extra_arg(arg);
        self
    }

    /// Set health check timeout
    pub fn health_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.config_builder = self.config_builder.health_timeout(timeout);
        self
    }

    /// Set working directory
    pub fn working_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.config_builder = self.config_builder.working_dir(path);
        self
    }

    /// Add environment variable
    pub fn env_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.env_var(key, value);
        self
    }

    /// Set path to mockforge binary
    pub fn binary_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.config_builder = self.config_builder.binary_path(path);
        self
    }

    /// Build and start the MockForge server
    pub async fn build(self) -> Result<MockForgeServer> {
        let config = self.config_builder.build();
        MockForgeServer::start(config).await
    }
}

// Helper function for use with test frameworks
/// Create a test server with default configuration
pub async fn with_mockforge<F, Fut>(test: F) -> Result<()>
where
    F: FnOnce(MockForgeServer) -> Fut,
    Fut: std::future::Future<Output = Result<()>>,
{
    let server = MockForgeServer::builder().build().await?;
    test(server).await
}

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

    #[test]
    fn test_builder_creation() {
        let builder = MockForgeServer::builder().http_port(3000).enable_admin(true).profile("test");
        // Verify builder captured the configuration
        drop(builder);
    }

    #[test]
    fn test_builder_default() {
        let _builder = MockForgeServerBuilder::default();
        // Default builder should be created
    }

    #[test]
    fn test_builder_http_port() {
        let builder = MockForgeServer::builder().http_port(8080);
        // Chain continues
        let _builder = builder.http_port(9090);
    }

    #[test]
    fn test_builder_ws_port() {
        let _builder = MockForgeServer::builder().ws_port(3001);
    }

    #[test]
    fn test_builder_grpc_port() {
        let _builder = MockForgeServer::builder().grpc_port(50051);
    }

    #[test]
    fn test_builder_admin_port() {
        let _builder = MockForgeServer::builder().admin_port(3002);
    }

    #[test]
    fn test_builder_metrics_port() {
        let _builder = MockForgeServer::builder().metrics_port(9090);
    }

    #[test]
    fn test_builder_spec_file() {
        let _builder = MockForgeServer::builder().spec_file("/path/to/spec.yaml");
    }

    #[test]
    fn test_builder_workspace_dir() {
        let _builder = MockForgeServer::builder().workspace_dir("/path/to/workspace");
    }

    #[test]
    fn test_builder_profile() {
        let _builder = MockForgeServer::builder().profile("production");
    }

    #[test]
    fn test_builder_enable_admin() {
        let _builder = MockForgeServer::builder().enable_admin(true);
        let _builder2 = MockForgeServer::builder().enable_admin(false);
    }

    #[test]
    fn test_builder_enable_metrics() {
        let _builder = MockForgeServer::builder().enable_metrics(true);
        let _builder2 = MockForgeServer::builder().enable_metrics(false);
    }

    #[test]
    fn test_builder_extra_arg() {
        let _builder = MockForgeServer::builder().extra_arg("--verbose");
    }

    #[test]
    fn test_builder_health_timeout() {
        let _builder = MockForgeServer::builder().health_timeout(Duration::from_secs(60));
    }

    #[test]
    fn test_builder_working_dir() {
        let _builder = MockForgeServer::builder().working_dir("/tmp/test");
    }

    #[test]
    fn test_builder_env_var() {
        let _builder = MockForgeServer::builder().env_var("RUST_LOG", "debug");
    }

    #[test]
    fn test_builder_binary_path() {
        let _builder = MockForgeServer::builder().binary_path("/usr/local/bin/mockforge");
    }

    #[test]
    fn test_builder_full_chain() {
        let _builder = MockForgeServer::builder()
            .http_port(3000)
            .ws_port(3001)
            .grpc_port(50051)
            .admin_port(3002)
            .metrics_port(9090)
            .spec_file("/spec.yaml")
            .workspace_dir("/workspace")
            .profile("test")
            .enable_admin(true)
            .enable_metrics(true)
            .extra_arg("--verbose")
            .health_timeout(Duration::from_secs(30))
            .working_dir("/working")
            .env_var("KEY", "VALUE")
            .binary_path("/bin/mockforge");

        // Full builder chain should compile
    }
}