voirs-cli 0.1.0-beta.1

Command-line interface for VoiRS speech synthesis
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
//! API Testing Tools for VoiRS Server
//!
//! This module provides comprehensive API testing functionality for the VoiRS HTTP server.
//! It includes endpoint validation, performance measurements, authentication testing,
//! and detailed test reporting.
//!
//! # Features
//!
//! - **Endpoint Testing**: Test all server endpoints (health, voices, synthesize, stats)
//! - **Authentication**: Validate API key authentication mechanisms
//! - **Performance Metrics**: Measure response times, throughput, latency
//! - **Contract Validation**: Verify API responses match expected schemas
//! - **Test Reports**: Generate detailed JSON/Markdown test reports
//! - **Load Testing**: Basic concurrent request testing
//!
//! # Usage
//!
//! ```bash
//! # Test server at localhost:8080
//! voirs test-api localhost:8080
//!
//! # Test with API key authentication
//! voirs test-api localhost:8080 --api-key YOUR_KEY
//!
//! # Generate detailed report
//! voirs test-api localhost:8080 --report report.json
//!
//! # Run load test
//! voirs test-api localhost:8080 --load-test --concurrent 10
//! ```

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};

/// API test configuration
#[derive(Debug, Clone)]
pub struct ApiTestConfig {
    /// Server URL (e.g., "http://localhost:8080")
    pub server_url: String,
    /// Optional API key for authentication
    pub api_key: Option<String>,
    /// Timeout for requests in seconds
    pub timeout_secs: u64,
    /// Number of concurrent requests for load testing
    pub concurrent_requests: usize,
    /// Enable verbose output
    pub verbose: bool,
}

impl Default for ApiTestConfig {
    fn default() -> Self {
        Self {
            server_url: "http://localhost:8080".to_string(),
            api_key: None,
            timeout_secs: 30,
            concurrent_requests: 1,
            verbose: false,
        }
    }
}

/// Test result for a single endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EndpointTestResult {
    /// Endpoint path
    pub endpoint: String,
    /// HTTP method
    pub method: String,
    /// Success status
    pub success: bool,
    /// Response status code
    pub status_code: u16,
    /// Response time in milliseconds
    pub response_time_ms: u64,
    /// Response body size in bytes
    pub response_size_bytes: usize,
    /// Error message if failed
    pub error: Option<String>,
    /// Timestamp of the test
    pub timestamp: DateTime<Utc>,
}

impl EndpointTestResult {
    /// Create a successful test result
    fn success(
        endpoint: String,
        method: String,
        status_code: u16,
        response_time_ms: u64,
        response_size_bytes: usize,
    ) -> Self {
        Self {
            endpoint,
            method,
            success: true,
            status_code,
            response_time_ms,
            response_size_bytes,
            error: None,
            timestamp: Utc::now(),
        }
    }

    /// Create a failed test result
    fn failure(endpoint: String, method: String, error: String) -> Self {
        Self {
            endpoint,
            method,
            success: false,
            status_code: 0,
            response_time_ms: 0,
            response_size_bytes: 0,
            error: Some(error),
            timestamp: Utc::now(),
        }
    }
}

/// Complete API test report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiTestReport {
    /// Server URL tested
    pub server_url: String,
    /// Test start time
    pub start_time: DateTime<Utc>,
    /// Test end time
    pub end_time: DateTime<Utc>,
    /// Total duration in seconds
    pub duration_secs: f64,
    /// Individual endpoint results
    pub endpoint_results: Vec<EndpointTestResult>,
    /// Overall statistics
    pub statistics: TestStatistics,
    /// Load test results if applicable
    pub load_test: Option<LoadTestResults>,
}

impl ApiTestReport {
    /// Calculate success rate percentage
    pub fn success_rate(&self) -> f64 {
        if self.endpoint_results.is_empty() {
            return 0.0;
        }
        let successful = self.endpoint_results.iter().filter(|r| r.success).count();
        (successful as f64 / self.endpoint_results.len() as f64) * 100.0
    }

    /// Generate markdown report
    pub fn to_markdown(&self) -> String {
        let mut md = String::new();
        md.push_str("# VoiRS API Test Report\n\n");
        md.push_str(&format!("**Server**: {}\n", self.server_url));
        md.push_str(&format!(
            "**Date**: {}\n",
            self.start_time.format("%Y-%m-%d %H:%M:%S UTC")
        ));
        md.push_str(&format!("**Duration**: {:.2}s\n\n", self.duration_secs));

        md.push_str("## Summary\n\n");
        md.push_str(&format!(
            "- **Success Rate**: {:.1}%\n",
            self.success_rate()
        ));
        md.push_str(&format!(
            "- **Total Tests**: {}\n",
            self.endpoint_results.len()
        ));
        md.push_str(&format!(
            "- **Passed**: {}\n",
            self.endpoint_results.iter().filter(|r| r.success).count()
        ));
        md.push_str(&format!(
            "- **Failed**: {}\n",
            self.endpoint_results.iter().filter(|r| !r.success).count()
        ));
        md.push_str(&format!(
            "- **Avg Response Time**: {:.0}ms\n\n",
            self.statistics.avg_response_time_ms
        ));

        md.push_str("## Endpoint Results\n\n");
        md.push_str("| Endpoint | Method | Status | Response Time | Size | Result |\n");
        md.push_str("|----------|--------|--------|---------------|------|--------|\n");

        for result in &self.endpoint_results {
            let status_emoji = if result.success { "" } else { "" };
            md.push_str(&format!(
                "| {} | {} | {} | {}ms | {} bytes | {} |\n",
                result.endpoint,
                result.method,
                result.status_code,
                result.response_time_ms,
                result.response_size_bytes,
                status_emoji
            ));
        }

        if let Some(load_test) = &self.load_test {
            md.push_str("\n## Load Test Results\n\n");
            md.push_str(&format!(
                "- **Concurrent Requests**: {}\n",
                load_test.concurrent_requests
            ));
            md.push_str(&format!(
                "- **Total Requests**: {}\n",
                load_test.total_requests
            ));
            md.push_str(&format!(
                "- **Successful**: {}\n",
                load_test.successful_requests
            ));
            md.push_str(&format!("- **Failed**: {}\n", load_test.failed_requests));
            md.push_str(&format!(
                "- **Avg Latency**: {:.0}ms\n",
                load_test.avg_latency_ms
            ));
            md.push_str(&format!(
                "- **Min Latency**: {}ms\n",
                load_test.min_latency_ms
            ));
            md.push_str(&format!(
                "- **Max Latency**: {}ms\n",
                load_test.max_latency_ms
            ));
            md.push_str(&format!(
                "- **Throughput**: {:.2} req/s\n",
                load_test.requests_per_second
            ));
        }

        md
    }
}

/// Test statistics summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestStatistics {
    /// Total number of tests
    pub total_tests: usize,
    /// Number of successful tests
    pub successful_tests: usize,
    /// Number of failed tests
    pub failed_tests: usize,
    /// Average response time in milliseconds
    pub avg_response_time_ms: f64,
    /// Minimum response time in milliseconds
    pub min_response_time_ms: u64,
    /// Maximum response time in milliseconds
    pub max_response_time_ms: u64,
}

/// Load test results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoadTestResults {
    /// Number of concurrent requests
    pub concurrent_requests: usize,
    /// Total requests sent
    pub total_requests: usize,
    /// Successful requests
    pub successful_requests: usize,
    /// Failed requests
    pub failed_requests: usize,
    /// Average latency in milliseconds
    pub avg_latency_ms: f64,
    /// Minimum latency in milliseconds
    pub min_latency_ms: u64,
    /// Maximum latency in milliseconds
    pub max_latency_ms: u64,
    /// Requests per second
    pub requests_per_second: f64,
}

/// API tester
pub struct ApiTester {
    config: ApiTestConfig,
    client: Client,
}

impl ApiTester {
    /// Create a new API tester
    pub fn new(config: ApiTestConfig) -> Result<Self> {
        let client = Client::builder()
            .timeout(Duration::from_secs(config.timeout_secs))
            .build()
            .context("Failed to create HTTP client")?;

        Ok(Self { config, client })
    }

    /// Run all API tests
    pub async fn run_tests(&self) -> Result<ApiTestReport> {
        let start_time = Utc::now();
        let mut results = Vec::new();

        println!("🚀 Starting API tests for {}", self.config.server_url);
        println!();

        // Test health endpoint
        println!("Testing /api/v1/health...");
        results.push(self.test_health().await);

        // Test voices endpoint
        println!("Testing /api/v1/voices...");
        results.push(self.test_voices().await);

        // Test stats endpoint
        println!("Testing /api/v1/stats...");
        results.push(self.test_stats().await);

        // Test synthesize endpoint
        println!("Testing /api/v1/synthesize...");
        results.push(self.test_synthesize().await);

        // Test authentication if API key provided
        if self.config.api_key.is_some() {
            println!("Testing /api/v1/auth/info...");
            results.push(self.test_auth_info().await);
        }

        let end_time = Utc::now();
        let duration_secs = (end_time - start_time).num_milliseconds() as f64 / 1000.0;

        // Calculate statistics
        let statistics = self.calculate_statistics(&results);

        // Run load test if configured
        let load_test = if self.config.concurrent_requests > 1 {
            println!("\n🔥 Running load test...");
            Some(self.run_load_test().await?)
        } else {
            None
        };

        Ok(ApiTestReport {
            server_url: self.config.server_url.clone(),
            start_time,
            end_time,
            duration_secs,
            endpoint_results: results,
            statistics,
            load_test,
        })
    }

    /// Test health endpoint
    async fn test_health(&self) -> EndpointTestResult {
        let url = format!("{}/api/v1/health", self.config.server_url);
        let start = Instant::now();

        match self.client.get(&url).send().await {
            Ok(response) => {
                let elapsed = start.elapsed().as_millis() as u64;
                let status = response.status().as_u16();
                match response.bytes().await {
                    Ok(body) => EndpointTestResult::success(
                        "/api/v1/health".to_string(),
                        "GET".to_string(),
                        status,
                        elapsed,
                        body.len(),
                    ),
                    Err(e) => EndpointTestResult::failure(
                        "/api/v1/health".to_string(),
                        "GET".to_string(),
                        format!("Failed to read response body: {}", e),
                    ),
                }
            }
            Err(e) => EndpointTestResult::failure(
                "/api/v1/health".to_string(),
                "GET".to_string(),
                format!("Request failed: {}", e),
            ),
        }
    }

    /// Test voices endpoint
    async fn test_voices(&self) -> EndpointTestResult {
        let url = format!("{}/api/v1/voices", self.config.server_url);
        let start = Instant::now();

        let mut request = self.client.get(&url);
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        match request.send().await {
            Ok(response) => {
                let elapsed = start.elapsed().as_millis() as u64;
                let status = response.status().as_u16();
                match response.bytes().await {
                    Ok(body) => EndpointTestResult::success(
                        "/api/v1/voices".to_string(),
                        "GET".to_string(),
                        status,
                        elapsed,
                        body.len(),
                    ),
                    Err(e) => EndpointTestResult::failure(
                        "/api/v1/voices".to_string(),
                        "GET".to_string(),
                        format!("Failed to read response body: {}", e),
                    ),
                }
            }
            Err(e) => EndpointTestResult::failure(
                "/api/v1/voices".to_string(),
                "GET".to_string(),
                format!("Request failed: {}", e),
            ),
        }
    }

    /// Test stats endpoint
    async fn test_stats(&self) -> EndpointTestResult {
        let url = format!("{}/api/v1/stats", self.config.server_url);
        let start = Instant::now();

        let mut request = self.client.get(&url);
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        match request.send().await {
            Ok(response) => {
                let elapsed = start.elapsed().as_millis() as u64;
                let status = response.status().as_u16();
                match response.bytes().await {
                    Ok(body) => EndpointTestResult::success(
                        "/api/v1/stats".to_string(),
                        "GET".to_string(),
                        status,
                        elapsed,
                        body.len(),
                    ),
                    Err(e) => EndpointTestResult::failure(
                        "/api/v1/stats".to_string(),
                        "GET".to_string(),
                        format!("Failed to read response body: {}", e),
                    ),
                }
            }
            Err(e) => EndpointTestResult::failure(
                "/api/v1/stats".to_string(),
                "GET".to_string(),
                format!("Request failed: {}", e),
            ),
        }
    }

    /// Test synthesize endpoint
    async fn test_synthesize(&self) -> EndpointTestResult {
        let url = format!("{}/api/v1/synthesize", self.config.server_url);
        let start = Instant::now();

        let body = serde_json::json!({
            "text": "Hello, this is a test.",
            "voice": "default",
        });

        let mut request = self.client.post(&url).json(&body);
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        match request.send().await {
            Ok(response) => {
                let elapsed = start.elapsed().as_millis() as u64;
                let status = response.status().as_u16();
                match response.bytes().await {
                    Ok(body_bytes) => EndpointTestResult::success(
                        "/api/v1/synthesize".to_string(),
                        "POST".to_string(),
                        status,
                        elapsed,
                        body_bytes.len(),
                    ),
                    Err(e) => EndpointTestResult::failure(
                        "/api/v1/synthesize".to_string(),
                        "POST".to_string(),
                        format!("Failed to read response body: {}", e),
                    ),
                }
            }
            Err(e) => EndpointTestResult::failure(
                "/api/v1/synthesize".to_string(),
                "POST".to_string(),
                format!("Request failed: {}", e),
            ),
        }
    }

    /// Test auth info endpoint
    async fn test_auth_info(&self) -> EndpointTestResult {
        let url = format!("{}/api/v1/auth/info", self.config.server_url);
        let start = Instant::now();

        let mut request = self.client.get(&url);
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        match request.send().await {
            Ok(response) => {
                let elapsed = start.elapsed().as_millis() as u64;
                let status = response.status().as_u16();
                match response.bytes().await {
                    Ok(body) => EndpointTestResult::success(
                        "/api/v1/auth/info".to_string(),
                        "GET".to_string(),
                        status,
                        elapsed,
                        body.len(),
                    ),
                    Err(e) => EndpointTestResult::failure(
                        "/api/v1/auth/info".to_string(),
                        "GET".to_string(),
                        format!("Failed to read response body: {}", e),
                    ),
                }
            }
            Err(e) => EndpointTestResult::failure(
                "/api/v1/auth/info".to_string(),
                "GET".to_string(),
                format!("Request failed: {}", e),
            ),
        }
    }

    /// Calculate test statistics
    fn calculate_statistics(&self, results: &[EndpointTestResult]) -> TestStatistics {
        let total_tests = results.len();
        let successful_tests = results.iter().filter(|r| r.success).count();
        let failed_tests = total_tests - successful_tests;

        let response_times: Vec<u64> = results
            .iter()
            .filter(|r| r.success)
            .map(|r| r.response_time_ms)
            .collect();

        let avg_response_time_ms = if response_times.is_empty() {
            0.0
        } else {
            response_times.iter().sum::<u64>() as f64 / response_times.len() as f64
        };

        let min_response_time_ms = response_times.iter().min().copied().unwrap_or(0);
        let max_response_time_ms = response_times.iter().max().copied().unwrap_or(0);

        TestStatistics {
            total_tests,
            successful_tests,
            failed_tests,
            avg_response_time_ms,
            min_response_time_ms,
            max_response_time_ms,
        }
    }

    /// Run load test
    async fn run_load_test(&self) -> Result<LoadTestResults> {
        let url = format!("{}/api/v1/health", self.config.server_url);
        let concurrent = self.config.concurrent_requests;
        let total_requests = concurrent * 10; // 10 rounds per worker

        let start = Instant::now();
        let mut handles = Vec::new();

        for _ in 0..concurrent {
            let client = self.client.clone();
            let url = url.clone();
            let handle = tokio::spawn(async move {
                let mut results = Vec::new();
                for _ in 0..10 {
                    let req_start = Instant::now();
                    let result = client.get(&url).send().await;
                    let elapsed = req_start.elapsed().as_millis() as u64;
                    results.push((result.is_ok(), elapsed));
                }
                results
            });
            handles.push(handle);
        }

        let mut all_results = Vec::new();
        for handle in handles {
            let results = handle.await?;
            all_results.extend(results);
        }

        let duration = start.elapsed();
        let successful = all_results.iter().filter(|(ok, _)| *ok).count();
        let failed = total_requests - successful;

        let latencies: Vec<u64> = all_results.iter().map(|(_, latency)| *latency).collect();
        let avg_latency_ms = latencies.iter().sum::<u64>() as f64 / latencies.len() as f64;
        let min_latency_ms = latencies.iter().min().copied().unwrap_or(0);
        let max_latency_ms = latencies.iter().max().copied().unwrap_or(0);
        let requests_per_second = total_requests as f64 / duration.as_secs_f64();

        Ok(LoadTestResults {
            concurrent_requests: concurrent,
            total_requests,
            successful_requests: successful,
            failed_requests: failed,
            avg_latency_ms,
            min_latency_ms,
            max_latency_ms,
            requests_per_second,
        })
    }
}

/// Print test report to console
pub fn print_report(report: &ApiTestReport) {
    println!("\n{}", "=".repeat(60));
    println!("  VoiRS API Test Report");
    println!("{}\n", "=".repeat(60));

    println!("Server: {}", report.server_url);
    println!("Duration: {:.2}s", report.duration_secs);
    println!();

    println!("Summary:");
    println!("  Success Rate: {:.1}%", report.success_rate());
    println!("  Total Tests: {}", report.endpoint_results.len());
    println!(
        "  Passed: {}",
        report.endpoint_results.iter().filter(|r| r.success).count()
    );
    println!(
        "  Failed: {}",
        report
            .endpoint_results
            .iter()
            .filter(|r| !r.success)
            .count()
    );
    println!(
        "  Avg Response Time: {:.0}ms",
        report.statistics.avg_response_time_ms
    );
    println!();

    println!("Endpoint Results:");
    for result in &report.endpoint_results {
        let status = if result.success {
            "✅ PASS"
        } else {
            "❌ FAIL"
        };
        println!(
            "  {} {} {} - {} - {}ms",
            status, result.method, result.endpoint, result.status_code, result.response_time_ms
        );
        if let Some(error) = &result.error {
            println!("    Error: {}", error);
        }
    }

    if let Some(load_test) = &report.load_test {
        println!();
        println!("Load Test Results:");
        println!("  Concurrent Requests: {}", load_test.concurrent_requests);
        println!("  Total Requests: {}", load_test.total_requests);
        println!("  Successful: {}", load_test.successful_requests);
        println!("  Failed: {}", load_test.failed_requests);
        println!("  Avg Latency: {:.0}ms", load_test.avg_latency_ms);
        println!("  Min Latency: {}ms", load_test.min_latency_ms);
        println!("  Max Latency: {}ms", load_test.max_latency_ms);
        println!("  Throughput: {:.2} req/s", load_test.requests_per_second);
    }

    println!("\n{}\n", "=".repeat(60));
}

/// Run API tests with the given configuration
pub async fn run_api_tests(
    server_url: String,
    api_key: Option<String>,
    concurrent: Option<usize>,
    report_path: Option<String>,
    verbose: bool,
) -> Result<()> {
    let config = ApiTestConfig {
        server_url,
        api_key,
        timeout_secs: 30,
        concurrent_requests: concurrent.unwrap_or(1),
        verbose,
    };

    let tester = ApiTester::new(config)?;
    let report = tester.run_tests().await?;

    // Print report to console
    print_report(&report);

    // Save report if path provided
    if let Some(path) = report_path {
        if path.ends_with(".json") {
            let json = serde_json::to_string_pretty(&report)
                .context("Failed to serialize report to JSON")?;
            std::fs::write(&path, json).context("Failed to write JSON report")?;
            println!("📄 JSON report saved to: {}", path);
        } else if path.ends_with(".md") {
            let markdown = report.to_markdown();
            std::fs::write(&path, markdown).context("Failed to write Markdown report")?;
            println!("📄 Markdown report saved to: {}", path);
        } else {
            anyhow::bail!("Report path must end with .json or .md");
        }
    }

    // Exit with error code if any tests failed
    if report.statistics.failed_tests > 0 {
        anyhow::bail!("{} test(s) failed", report.statistics.failed_tests);
    }

    Ok(())
}

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

    #[test]
    fn test_api_test_config_default() {
        let config = ApiTestConfig::default();
        assert_eq!(config.server_url, "http://localhost:8080");
        assert_eq!(config.timeout_secs, 30);
        assert_eq!(config.concurrent_requests, 1);
        assert!(!config.verbose);
    }

    #[test]
    fn test_endpoint_test_result_success() {
        let result = EndpointTestResult::success(
            "/api/v1/health".to_string(),
            "GET".to_string(),
            200,
            150,
            1024,
        );

        assert!(result.success);
        assert_eq!(result.endpoint, "/api/v1/health");
        assert_eq!(result.method, "GET");
        assert_eq!(result.status_code, 200);
        assert_eq!(result.response_time_ms, 150);
        assert_eq!(result.response_size_bytes, 1024);
        assert!(result.error.is_none());
    }

    #[test]
    fn test_endpoint_test_result_failure() {
        let result = EndpointTestResult::failure(
            "/api/v1/health".to_string(),
            "GET".to_string(),
            "Connection refused".to_string(),
        );

        assert!(!result.success);
        assert_eq!(result.endpoint, "/api/v1/health");
        assert_eq!(result.method, "GET");
        assert_eq!(result.error, Some("Connection refused".to_string()));
    }

    #[test]
    fn test_api_test_report_success_rate() {
        let results = vec![
            EndpointTestResult::success(
                "/api/v1/health".to_string(),
                "GET".to_string(),
                200,
                100,
                512,
            ),
            EndpointTestResult::success(
                "/api/v1/voices".to_string(),
                "GET".to_string(),
                200,
                150,
                1024,
            ),
            EndpointTestResult::failure(
                "/api/v1/synth".to_string(),
                "POST".to_string(),
                "Error".to_string(),
            ),
        ];

        let report = ApiTestReport {
            server_url: "http://localhost:8080".to_string(),
            start_time: Utc::now(),
            end_time: Utc::now(),
            duration_secs: 1.5,
            endpoint_results: results,
            statistics: TestStatistics {
                total_tests: 3,
                successful_tests: 2,
                failed_tests: 1,
                avg_response_time_ms: 125.0,
                min_response_time_ms: 100,
                max_response_time_ms: 150,
            },
            load_test: None,
        };

        assert!((report.success_rate() - 66.666).abs() < 0.01);
    }

    #[test]
    fn test_markdown_report_generation() {
        let results = vec![EndpointTestResult::success(
            "/api/v1/health".to_string(),
            "GET".to_string(),
            200,
            100,
            512,
        )];

        let report = ApiTestReport {
            server_url: "http://localhost:8080".to_string(),
            start_time: Utc::now(),
            end_time: Utc::now(),
            duration_secs: 0.5,
            endpoint_results: results,
            statistics: TestStatistics {
                total_tests: 1,
                successful_tests: 1,
                failed_tests: 0,
                avg_response_time_ms: 100.0,
                min_response_time_ms: 100,
                max_response_time_ms: 100,
            },
            load_test: None,
        };

        let markdown = report.to_markdown();
        assert!(markdown.contains("# VoiRS API Test Report"));
        assert!(markdown.contains("http://localhost:8080"));
        assert!(markdown.contains("/api/v1/health"));
    }
}