mockforge-cli 0.3.108

CLI interface for MockForge
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
//! Logs viewing CLI commands
//!
//! Provides command-line interface for viewing MockForge logs from Admin API or log files.

use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::io;
use std::path::PathBuf;
use std::time::Duration;
use tokio::fs::File;
use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader as TokioBufReader};
use tokio::time::sleep;

/// Log entry from Admin API
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
    pub timestamp: String,
    pub status: u16,
    pub method: String,
    pub url: String,
    pub response_time: Option<u64>,
    pub size: Option<u64>,
}

/// API response wrapper
#[derive(Debug, Deserialize)]
struct ApiResponse<T> {
    success: bool,
    data: Option<T>,
    error: Option<String>,
}

/// Execute logs command
#[allow(clippy::too_many_arguments)]
pub async fn execute_logs_command(
    admin_url: Option<String>,
    file: Option<PathBuf>,
    follow: bool,
    method: Option<String>,
    path: Option<String>,
    status: Option<u16>,
    limit: Option<usize>,
    json: bool,
    config: Option<PathBuf>,
) -> Result<()> {
    // If file is specified, read from file
    if let Some(file_path) = file {
        return read_logs_from_file(file_path, follow, json).await;
    }

    // Try to read from config file to get log file path
    if let Some(config_path) = config {
        if let Ok(log_file) = get_log_file_from_config(&config_path).await {
            if log_file.exists() {
                return read_logs_from_file(log_file, follow, json).await;
            }
        }
    }

    // Try Admin API first
    let admin_url = admin_url.unwrap_or_else(|| "http://localhost:9080".to_string());

    if follow {
        stream_logs_from_api(&admin_url, method, path, status, json).await
    } else {
        fetch_logs_from_api(&admin_url, method, path, status, limit, json).await
    }
}

/// Fetch logs from Admin API
async fn fetch_logs_from_api(
    admin_url: &str,
    method: Option<String>,
    path: Option<String>,
    status: Option<u16>,
    limit: Option<usize>,
    json: bool,
) -> Result<()> {
    let client = Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .context("Failed to create HTTP client")?;

    let mut url = format!("{}/__mockforge/logs", admin_url);
    let mut query_params = Vec::new();

    if let Some(m) = method {
        query_params.push(("method", m));
    }
    if let Some(p) = path {
        query_params.push(("path", p));
    }
    if let Some(s) = status {
        query_params.push(("status", s.to_string()));
    }
    if let Some(l) = limit {
        query_params.push(("limit", l.to_string()));
    }

    if !query_params.is_empty() {
        let query_string = query_params
            .iter()
            .map(|(k, v)| format!("{}={}", k, urlencoding::encode(v)))
            .collect::<Vec<_>>()
            .join("&");
        url = format!("{}?{}", url, query_string);
    }

    let response = client
        .get(&url)
        .send()
        .await
        .context("Failed to connect to Admin API. Is the server running with --admin flag?")?;

    if !response.status().is_success() {
        anyhow::bail!(
            "Admin API returned error: {} - {}. Make sure the server is running with --admin flag.",
            response.status(),
            response.text().await.unwrap_or_default()
        );
    }

    let api_response: ApiResponse<Vec<LogEntry>> =
        response.json().await.context("Failed to parse API response")?;

    if !api_response.success {
        anyhow::bail!(
            "API error: {}",
            api_response.error.unwrap_or_else(|| "Unknown error".to_string())
        );
    }

    let logs = api_response.data.unwrap_or_default();

    if json {
        println!("{}", serde_json::to_string_pretty(&logs)?);
    } else {
        print_logs_table(&logs);
    }

    Ok(())
}

/// Stream logs from Admin API using SSE
async fn stream_logs_from_api(
    admin_url: &str,
    method: Option<String>,
    path: Option<String>,
    status: Option<u16>,
    json: bool,
) -> Result<()> {
    let client = Client::builder()
        .timeout(Duration::from_secs(0)) // No timeout for streaming
        .build()
        .context("Failed to create HTTP client")?;

    // First, fetch recent logs
    let mut url = format!("{}/__mockforge/logs", admin_url);
    let mut query_params = Vec::new();

    if let Some(m) = method {
        query_params.push(("method", m));
    }
    if let Some(p) = path {
        query_params.push(("path", p));
    }
    if let Some(s) = status {
        query_params.push(("status", s.to_string()));
    }
    query_params.push(("limit", "50".to_string())); // Get recent logs

    if !query_params.is_empty() {
        let query_string = query_params
            .iter()
            .map(|(k, v)| format!("{}={}", k, urlencoding::encode(v)))
            .collect::<Vec<_>>()
            .join("&");
        url = format!("{}?{}", url, query_string);
    }

    // Fetch initial logs
    match client.get(&url).send().await {
        Ok(response) if response.status().is_success() => {
            if let Ok(api_response) = response.json::<ApiResponse<Vec<LogEntry>>>().await {
                if let Some(logs) = api_response.data {
                    if json {
                        println!("{}", serde_json::to_string_pretty(&logs)?);
                    } else {
                        print_logs_table(&logs);
                    }
                }
            }
        }
        _ => {
            eprintln!("⚠️  Could not fetch initial logs. Starting to follow...");
        }
    }

    // Now stream new logs using polling (SSE endpoint may not be available)
    eprintln!("📡 Following logs (press Ctrl+C to stop)...");
    let mut last_seen_timestamp = chrono::Utc::now().to_rfc3339();

    loop {
        sleep(Duration::from_millis(500)).await;

        match client.get(&url).send().await {
            Ok(response) if response.status().is_success() => {
                if let Ok(api_response) = response.json::<ApiResponse<Vec<LogEntry>>>().await {
                    if let Some(logs) = api_response.data {
                        // Filter to only show new logs
                        let new_logs: Vec<_> =
                            logs.iter().filter(|log| log.timestamp > last_seen_timestamp).collect();

                        if !new_logs.is_empty() {
                            if let Some(last_log) = new_logs.last() {
                                last_seen_timestamp = last_log.timestamp.clone();
                            }

                            if json {
                                for log in new_logs {
                                    println!("{}", serde_json::to_string(log)?);
                                }
                            } else {
                                for log in new_logs {
                                    print_log_entry(log);
                                }
                            }
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("⚠️  Error fetching logs: {}. Retrying...", e);
                sleep(Duration::from_secs(2)).await;
            }
            _ => {}
        }
    }
}

/// Read logs from file
async fn read_logs_from_file(file_path: PathBuf, follow: bool, json: bool) -> Result<()> {
    if !file_path.exists() {
        anyhow::bail!("Log file does not exist: {}", file_path.display());
    }

    if follow {
        follow_log_file(file_path, json).await
    } else {
        read_log_file_tail(file_path, json).await
    }
}

/// Read last N lines from log file
async fn read_log_file_tail(file_path: PathBuf, json: bool) -> Result<()> {
    let file = File::open(&file_path)
        .await
        .with_context(|| format!("Failed to open log file: {}", file_path.display()))?;

    let reader = TokioBufReader::new(file);
    let mut lines = reader.lines();

    // Read all lines into memory (for small files, this is fine)
    let mut all_lines = Vec::new();
    while let Some(line) = lines.next_line().await? {
        all_lines.push(line);
    }

    // Print last 100 lines
    let start = all_lines.len().saturating_sub(100);
    for line in &all_lines[start..] {
        if json {
            // Try to parse as JSON and pretty print
            if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(line) {
                println!("{}", serde_json::to_string_pretty(&json_value)?);
            } else {
                println!("{}", line);
            }
        } else {
            println!("{}", line);
        }
    }

    Ok(())
}

/// Follow log file (like tail -f)
async fn follow_log_file(file_path: PathBuf, json: bool) -> Result<()> {
    use tokio::fs::OpenOptions;

    eprintln!("📡 Following log file: {} (press Ctrl+C to stop)...", file_path.display());

    // Get initial file size
    let mut last_size = std::fs::metadata(&file_path)
        .with_context(|| format!("Failed to get file metadata: {}", file_path.display()))?
        .len();

    loop {
        // Check if file size changed
        let current_size = match std::fs::metadata(&file_path) {
            Ok(meta) => meta.len(),
            Err(_) => {
                sleep(Duration::from_millis(500)).await;
                continue;
            }
        };

        if current_size > last_size {
            // Read new content
            let file = OpenOptions::new()
                .read(true)
                .open(&file_path)
                .await
                .with_context(|| format!("Failed to open log file: {}", file_path.display()))?;

            let mut reader = TokioBufReader::new(file);
            reader.seek(io::SeekFrom::Start(last_size)).await?;

            let mut buffer = String::new();
            while reader.read_line(&mut buffer).await? > 0 {
                let line = buffer.trim_end();
                if !line.is_empty() {
                    if json {
                        // Try to parse as JSON and pretty print
                        if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(line) {
                            println!("{}", serde_json::to_string_pretty(&json_value)?);
                        } else {
                            println!("{}", line);
                        }
                    } else {
                        println!("{}", line);
                    }
                }
                buffer.clear();
            }

            last_size = current_size;
        } else {
            // No new data, wait a bit
            sleep(Duration::from_millis(100)).await;
        }
    }
}

/// Get log file path from config
async fn get_log_file_from_config(config_path: &PathBuf) -> Result<PathBuf> {
    use mockforge_core::config::load_config_auto;

    let config = load_config_auto(config_path).await?;

    if let Some(file_path) = config.logging.file_path {
        return Ok(PathBuf::from(file_path));
    }

    anyhow::bail!("No log file path configured")
}

/// Print logs in table format
fn print_logs_table(logs: &[LogEntry]) {
    if logs.is_empty() {
        println!("No logs found.");
        return;
    }

    // Print header
    println!(
        "{:<20} {:<8} {:<8} {:<50} {:<8} {:<10}",
        "Timestamp", "Status", "Method", "Path", "Time(ms)", "Size(bytes)"
    );
    println!("{}", "-".repeat(110));

    // Print logs
    for log in logs {
        print_log_entry(log);
    }
}

/// Print a single log entry
fn print_log_entry(log: &LogEntry) {
    let timestamp = if log.timestamp.len() > 19 {
        &log.timestamp[..19] // Truncate to YYYY-MM-DDTHH:MM:SS
    } else {
        &log.timestamp
    };

    let response_time = log.response_time.map(|t| t.to_string()).unwrap_or_else(|| "-".to_string());
    let size = log.size.map(|s| s.to_string()).unwrap_or_else(|| "-".to_string());

    // Color code status
    let status_str = if log.status >= 500 {
        format!("\x1b[31m{}\x1b[0m", log.status) // Red for 5xx
    } else if log.status >= 400 {
        format!("\x1b[33m{}\x1b[0m", log.status) // Yellow for 4xx
    } else {
        format!("\x1b[32m{}\x1b[0m", log.status) // Green for 2xx/3xx
    };

    let method_str = match log.method.as_str() {
        "GET" => format!("\x1b[34m{}\x1b[0m", log.method), // Blue
        "POST" => format!("\x1b[32m{}\x1b[0m", log.method), // Green
        "PUT" => format!("\x1b[33m{}\x1b[0m", log.method), // Yellow
        "DELETE" => format!("\x1b[31m{}\x1b[0m", log.method), // Red
        "PATCH" => format!("\x1b[35m{}\x1b[0m", log.method), // Magenta
        _ => log.method.clone(),
    };

    let path = if log.url.len() > 48 {
        format!("{}...", &log.url[..45])
    } else {
        log.url.clone()
    };

    println!(
        "{:<20} {:<8} {:<8} {:<50} {:<8} {:<10}",
        timestamp, status_str, method_str, path, response_time, size
    );
}

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

    fn create_test_log_entry() -> LogEntry {
        LogEntry {
            timestamp: "2025-01-15T10:30:45.123Z".to_string(),
            status: 200,
            method: "GET".to_string(),
            url: "/api/users".to_string(),
            response_time: Some(42),
            size: Some(1024),
        }
    }

    #[test]
    fn test_log_entry_serialization() {
        let log = create_test_log_entry();
        let json = serde_json::to_string(&log).unwrap();

        assert!(json.contains("\"timestamp\":\"2025-01-15T10:30:45.123Z\""));
        assert!(json.contains("\"status\":200"));
        assert!(json.contains("\"method\":\"GET\""));
        assert!(json.contains("\"url\":\"/api/users\""));
        assert!(json.contains("\"response_time\":42"));
        assert!(json.contains("\"size\":1024"));
    }

    #[test]
    fn test_log_entry_deserialization() {
        let json = r#"{
            "timestamp": "2025-01-15T10:30:45.123Z",
            "status": 201,
            "method": "POST",
            "url": "/api/items",
            "response_time": 100,
            "size": 2048
        }"#;

        let log: LogEntry = serde_json::from_str(json).unwrap();

        assert_eq!(log.timestamp, "2025-01-15T10:30:45.123Z");
        assert_eq!(log.status, 201);
        assert_eq!(log.method, "POST");
        assert_eq!(log.url, "/api/items");
        assert_eq!(log.response_time, Some(100));
        assert_eq!(log.size, Some(2048));
    }

    #[test]
    fn test_log_entry_deserialization_without_optional_fields() {
        let json = r#"{
            "timestamp": "2025-01-15T10:30:45Z",
            "status": 404,
            "method": "DELETE",
            "url": "/api/items/123",
            "response_time": null,
            "size": null
        }"#;

        let log: LogEntry = serde_json::from_str(json).unwrap();

        assert_eq!(log.status, 404);
        assert_eq!(log.method, "DELETE");
        assert!(log.response_time.is_none());
        assert!(log.size.is_none());
    }

    #[test]
    fn test_log_entry_clone() {
        let log = create_test_log_entry();
        let cloned = log.clone();

        assert_eq!(log.timestamp, cloned.timestamp);
        assert_eq!(log.status, cloned.status);
        assert_eq!(log.method, cloned.method);
        assert_eq!(log.url, cloned.url);
    }

    #[test]
    fn test_log_entry_debug() {
        let log = create_test_log_entry();
        let debug_str = format!("{:?}", log);

        assert!(debug_str.contains("LogEntry"));
        assert!(debug_str.contains("GET"));
        assert!(debug_str.contains("200"));
    }

    #[test]
    fn test_api_response_success() {
        let json = r#"{
            "success": true,
            "data": [{"timestamp": "2025-01-15T10:30:45Z", "status": 200, "method": "GET", "url": "/api/test", "response_time": 50, "size": 100}],
            "error": null
        }"#;

        let response: ApiResponse<Vec<LogEntry>> = serde_json::from_str(json).unwrap();

        assert!(response.success);
        assert!(response.data.is_some());
        assert!(response.error.is_none());
        assert_eq!(response.data.unwrap().len(), 1);
    }

    #[test]
    fn test_api_response_error() {
        let json = r#"{
            "success": false,
            "data": null,
            "error": "Server unavailable"
        }"#;

        let response: ApiResponse<Vec<LogEntry>> = serde_json::from_str(json).unwrap();

        assert!(!response.success);
        assert!(response.data.is_none());
        assert_eq!(response.error, Some("Server unavailable".to_string()));
    }

    #[test]
    fn test_log_entry_all_http_methods() {
        let methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"];

        for method in methods {
            let log = LogEntry {
                timestamp: "2025-01-15T10:30:45Z".to_string(),
                status: 200,
                method: method.to_string(),
                url: "/api/test".to_string(),
                response_time: None,
                size: None,
            };

            // Just verify it can be created and serialized
            let json = serde_json::to_string(&log).unwrap();
            assert!(json.contains(method));
        }
    }

    #[test]
    fn test_log_entry_various_status_codes() {
        let status_codes = [200, 201, 204, 301, 302, 400, 401, 403, 404, 500, 502, 503];

        for status in status_codes {
            let log = LogEntry {
                timestamp: "2025-01-15T10:30:45Z".to_string(),
                status,
                method: "GET".to_string(),
                url: "/api/test".to_string(),
                response_time: None,
                size: None,
            };

            let json = serde_json::to_string(&log).unwrap();
            assert!(json.contains(&format!("\"status\":{}", status)));
        }
    }

    #[test]
    fn test_log_entry_long_url_serialization() {
        let long_url =
            "/api/v1/organizations/12345/projects/67890/resources/abcdef/items/ghijkl/details"
                .to_string();
        let log = LogEntry {
            timestamp: "2025-01-15T10:30:45Z".to_string(),
            status: 200,
            method: "GET".to_string(),
            url: long_url.clone(),
            response_time: Some(150),
            size: Some(5000),
        };

        let json = serde_json::to_string(&log).unwrap();
        let parsed: LogEntry = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.url, long_url);
    }

    #[test]
    fn test_log_entry_special_characters_in_url() {
        let url = "/api/search?q=hello%20world&page=1".to_string();
        let log = LogEntry {
            timestamp: "2025-01-15T10:30:45Z".to_string(),
            status: 200,
            method: "GET".to_string(),
            url: url.clone(),
            response_time: None,
            size: None,
        };

        let json = serde_json::to_string(&log).unwrap();
        let parsed: LogEntry = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.url, url);
    }

    #[test]
    fn test_log_entry_zero_values() {
        let log = LogEntry {
            timestamp: "2025-01-15T10:30:45Z".to_string(),
            status: 200,
            method: "GET".to_string(),
            url: "/".to_string(),
            response_time: Some(0),
            size: Some(0),
        };

        assert_eq!(log.response_time, Some(0));
        assert_eq!(log.size, Some(0));

        let json = serde_json::to_string(&log).unwrap();
        assert!(json.contains("\"response_time\":0"));
        assert!(json.contains("\"size\":0"));
    }

    #[test]
    fn test_log_entry_large_values() {
        let log = LogEntry {
            timestamp: "2025-01-15T10:30:45Z".to_string(),
            status: 200,
            method: "GET".to_string(),
            url: "/api/large".to_string(),
            response_time: Some(u64::MAX),
            size: Some(u64::MAX),
        };

        let json = serde_json::to_string(&log).unwrap();
        let parsed: LogEntry = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.response_time, Some(u64::MAX));
        assert_eq!(parsed.size, Some(u64::MAX));
    }

    #[test]
    fn test_print_logs_table_empty() {
        // Test that empty logs don't cause panic
        let logs: Vec<LogEntry> = vec![];
        print_logs_table(&logs);
    }

    #[test]
    fn test_print_log_entry_does_not_panic() {
        // Test various edge cases for print_log_entry
        let test_cases = vec![
            // Short timestamp
            LogEntry {
                timestamp: "2025-01-15".to_string(),
                status: 200,
                method: "GET".to_string(),
                url: "/short".to_string(),
                response_time: None,
                size: None,
            },
            // Long timestamp
            LogEntry {
                timestamp: "2025-01-15T10:30:45.123456789Z".to_string(),
                status: 500,
                method: "POST".to_string(),
                url: "/error".to_string(),
                response_time: Some(1000),
                size: Some(100),
            },
            // Long URL that gets truncated
            LogEntry {
                timestamp: "2025-01-15T10:30:45Z".to_string(),
                status: 404,
                method: "DELETE".to_string(),
                url: "/api/v1/very/long/path/that/should/be/truncated/by/the/print/function"
                    .to_string(),
                response_time: None,
                size: None,
            },
            // 4xx status
            LogEntry {
                timestamp: "2025-01-15T10:30:45Z".to_string(),
                status: 403,
                method: "PUT".to_string(),
                url: "/forbidden".to_string(),
                response_time: Some(5),
                size: Some(0),
            },
            // PATCH method
            LogEntry {
                timestamp: "2025-01-15T10:30:45Z".to_string(),
                status: 200,
                method: "PATCH".to_string(),
                url: "/update".to_string(),
                response_time: Some(25),
                size: Some(512),
            },
            // Unknown method
            LogEntry {
                timestamp: "2025-01-15T10:30:45Z".to_string(),
                status: 200,
                method: "CUSTOM".to_string(),
                url: "/custom".to_string(),
                response_time: None,
                size: None,
            },
        ];

        for log in &test_cases {
            print_log_entry(log);
        }
    }

    #[test]
    fn test_print_logs_table_with_entries() {
        let logs = vec![
            create_test_log_entry(),
            LogEntry {
                timestamp: "2025-01-15T10:31:00Z".to_string(),
                status: 201,
                method: "POST".to_string(),
                url: "/api/items".to_string(),
                response_time: Some(100),
                size: Some(2048),
            },
        ];

        // Should not panic
        print_logs_table(&logs);
    }

    #[test]
    fn test_log_entry_round_trip() {
        let original = create_test_log_entry();
        let json = serde_json::to_string(&original).unwrap();
        let parsed: LogEntry = serde_json::from_str(&json).unwrap();

        assert_eq!(original.timestamp, parsed.timestamp);
        assert_eq!(original.status, parsed.status);
        assert_eq!(original.method, parsed.method);
        assert_eq!(original.url, parsed.url);
        assert_eq!(original.response_time, parsed.response_time);
        assert_eq!(original.size, parsed.size);
    }
}