grpctestify 1.5.1

gRPC testing utility written in Rust
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
// GCTF document validator - validates parsed AST
// Checks for required sections, conflicts, and data integrity

use super::ast::*;
use anyhow::{Result, bail};
use serde::Serialize;

/// Validation error
#[derive(Debug, Clone, Serialize)]
pub struct ValidationError {
    pub message: String,
    pub line: Option<usize>,
    pub severity: ErrorSeverity,
}

/// Error severity
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ErrorSeverity {
    Error,
    Warning,
    Info,
}

/// Validate a parsed GCTF document (returns all errors/warnings without bailing)
pub fn validate_document_diagnostics(document: &GctfDocument) -> Vec<ValidationError> {
    let mut errors = Vec::new();

    // Check for required sections
    validate_required_sections(document, &mut errors);

    // Check for conflicts
    validate_conflicts(document, &mut errors);

    // Validate content
    validate_content(document, &mut errors);

    // Validate structure
    validate_structure(document, &mut errors);

    errors
}

/// Validate a parsed GCTF document (legacy wrapper that bails on error)
pub fn validate_document(document: &GctfDocument) -> Result<Vec<ValidationError>> {
    let errors = validate_document_diagnostics(document);
    let has_errors = errors.iter().any(|e| e.severity == ErrorSeverity::Error);

    if has_errors {
        let error_messages: Vec<String> = errors
            .iter()
            .filter(|e| e.severity == ErrorSeverity::Error)
            .map(|e| format!("Line {}: {}", e.line.unwrap_or(0), e.message))
            .collect();

        bail!("Validation failed:\n{}", error_messages.join("\n"));
    }

    Ok(errors)
}

/// Validate required sections
fn validate_required_sections(document: &GctfDocument, errors: &mut Vec<ValidationError>) {
    // ENDPOINT is required
    if document.get_endpoint().is_none() {
        errors.push(ValidationError {
            message: "ENDPOINT section is required".to_string(),
            line: None,
            severity: ErrorSeverity::Error,
        });
    }

    // ADDRESS or environment variable is required
    // The address might also be provided via CLI args or Config file, which the validator
    // doesn't have access to here. We should probably relax this check or make it a warning.
    // Ideally validation happens with full context, but for now let's check env var.
    // If neither section nor env var is present, we warn instead of error,
    // because it might be supplied at runtime.
    let env_addr = std::env::var(crate::config::ENV_GRPCTESTIFY_ADDRESS).ok();
    if document.get_address(env_addr.as_deref()).is_none() {
        // Downgrade to warning because address can come from CLI/Config
        errors.push(ValidationError {
            message: format!(
                "ADDRESS section missing (ensure {} is set or passed via --address)",
                crate::config::ENV_GRPCTESTIFY_ADDRESS
            ),
            line: None,
            severity: ErrorSeverity::Warning,
        });
    }

    // At least RESPONSE, ERROR or ASSERTS should be present for verification
    let has_response = document.first_section(SectionType::Response).is_some();
    let has_error = document.first_section(SectionType::Error).is_some();
    let has_asserts = document.first_section(SectionType::Asserts).is_some();

    if !has_response && !has_error && !has_asserts {
        errors.push(ValidationError {
            message: "At least one verification section (RESPONSE, ERROR, or ASSERTS) is required"
                .to_string(),
            line: None,
            severity: ErrorSeverity::Error,
        });
    }
}

/// Validate conflicts
fn validate_conflicts(document: &GctfDocument, errors: &mut Vec<ValidationError>) {
    // RESPONSE and ERROR cannot both be present
    if document.has_response_error_conflict() {
        errors.push(ValidationError {
            message: "Cannot have both RESPONSE and ERROR sections".to_string(),
            line: None,
            severity: ErrorSeverity::Error,
        });
    }
}

/// Validate content
fn validate_content(document: &GctfDocument, errors: &mut Vec<ValidationError>) {
    // Validate endpoint format
    if let Some(endpoint) = document.get_endpoint()
        && !endpoint.contains('/')
    {
        errors.push(ValidationError {
            message: format!(
                "Invalid endpoint format: {}. Expected format: package.Service/Method",
                endpoint
            ),
            line: document
                .first_section(SectionType::Endpoint)
                .map(|s| s.start_line),
            severity: ErrorSeverity::Error,
        });
    }

    // Validate address format
    if let Some(address) = document.get_address(None)
        && !address.contains(':')
    {
        errors.push(ValidationError {
            message: format!(
                "Invalid address format: {}. Expected format: host:port",
                address
            ),
            line: document
                .first_section(SectionType::Address)
                .map(|s| s.start_line),
            severity: ErrorSeverity::Error,
        });
    }

    // Validate JSON sections
    for section_type in [
        SectionType::Request,
        SectionType::Response,
        SectionType::Error,
    ] {
        for section in document.sections_by_type(section_type) {
            match &section.content {
                SectionContent::Json(json) => {
                    // Check if JSON is valid object or array
                    // For ERROR, we also allow strings
                    let is_valid = if section_type == SectionType::Error {
                        json.is_object() || json.is_array() || json.is_string()
                    } else {
                        json.is_object() || json.is_array()
                    };

                    if !is_valid {
                        errors.push(ValidationError {
                            message: format!(
                                "{:?} section must contain valid JSON object or array{}",
                                section_type,
                                if section_type == SectionType::Error {
                                    " or string"
                                } else {
                                    ""
                                }
                            ),
                            line: Some(section.start_line),
                            severity: ErrorSeverity::Error,
                        });
                    }

                    if section_type == SectionType::Error
                        && let Some(details) = json.get("details")
                    {
                        if !details.is_array() {
                            errors.push(ValidationError {
                                message: "ERROR section field 'details' must be an array"
                                    .to_string(),
                                line: Some(section.start_line),
                                severity: ErrorSeverity::Error,
                            });
                        } else if let Some(detail_items) = details.as_array() {
                            for detail in detail_items {
                                if !detail.is_object() {
                                    errors.push(ValidationError {
                                        message: "ERROR section 'details' items must be objects"
                                            .to_string(),
                                        line: Some(section.start_line),
                                        severity: ErrorSeverity::Error,
                                    });
                                    break;
                                }

                                if let Some(type_value) = detail.get("@type")
                                    && !type_value.is_string()
                                {
                                    errors.push(ValidationError {
                                        message:
                                            "ERROR.details item field '@type' must be a string"
                                                .to_string(),
                                        line: Some(section.start_line),
                                        severity: ErrorSeverity::Error,
                                    });
                                }
                            }
                        }
                    }
                }
                SectionContent::JsonLines(values) => {
                    if section_type != SectionType::Response {
                        errors.push(ValidationError {
                            message: format!(
                                "{:?} section does not support newline-delimited JSON messages",
                                section_type
                            ),
                            line: Some(section.start_line),
                            severity: ErrorSeverity::Error,
                        });
                    } else if values.is_empty() {
                        errors.push(ValidationError {
                            message: "RESPONSE section contains no JSON messages".to_string(),
                            line: Some(section.start_line),
                            severity: ErrorSeverity::Error,
                        });
                    }
                }
                _ => {}
            }
        }
    }

    // Validate key-value sections
    for section_type in [
        SectionType::RequestHeaders,
        SectionType::Tls,
        SectionType::Proto,
        SectionType::Options,
    ] {
        for section in document.sections_by_type(section_type) {
            if let SectionContent::KeyValues(kv) = &section.content {
                // Check for empty keys or values
                for key in kv.keys() {
                    if key.is_empty() {
                        errors.push(ValidationError {
                            message: format!("Empty key in {:?} section", section_type),
                            line: Some(section.start_line),
                            severity: ErrorSeverity::Error,
                        });
                    }
                }

                if section_type == SectionType::Options {
                    for (key, value) in kv {
                        match key.as_str() {
                            "timeout" => {
                                if value.trim().parse::<u64>().ok().is_none_or(|v| v == 0) {
                                    errors.push(ValidationError {
                                        message: format!(
                                            "OPTIONS.timeout must be a positive integer, got '{}'",
                                            value
                                        ),
                                        line: Some(section.start_line),
                                        severity: ErrorSeverity::Error,
                                    });
                                }
                            }
                            "no-retry" | "no_retry" => {
                                let normalized = value.trim().to_ascii_lowercase();
                                let is_bool = matches!(
                                    normalized.as_str(),
                                    "true" | "1" | "yes" | "on" | "false" | "0" | "no" | "off"
                                );
                                if !is_bool {
                                    errors.push(ValidationError {
                                        message: format!(
                                            "OPTIONS.{} must be a boolean, got '{}'",
                                            key, value
                                        ),
                                        line: Some(section.start_line),
                                        severity: ErrorSeverity::Error,
                                    });
                                }
                            }
                            "retry" => {
                                if value.trim().parse::<u32>().is_err() {
                                    errors.push(ValidationError {
                                        message: format!(
                                            "OPTIONS.retry must be a non-negative integer, got '{}'",
                                            value
                                        ),
                                        line: Some(section.start_line),
                                        severity: ErrorSeverity::Error,
                                    });
                                }
                            }
                            "retry-delay" | "retry_delay" => {
                                if value.trim().parse::<f64>().ok().is_none_or(|v| v < 0.0) {
                                    errors.push(ValidationError {
                                        message: format!(
                                            "OPTIONS.retry-delay must be a non-negative number, got '{}'",
                                            value
                                        ),
                                        line: Some(section.start_line),
                                        severity: ErrorSeverity::Error,
                                    });
                                }
                            }
                            "compression" => {
                                let normalized = value.trim().to_ascii_lowercase();
                                if !matches!(normalized.as_str(), "none" | "gzip") {
                                    errors.push(ValidationError {
                                        message: format!(
                                            "OPTIONS.compression must be one of: none, gzip (got '{}')",
                                            value
                                        ),
                                        line: Some(section.start_line),
                                        severity: ErrorSeverity::Error,
                                    });
                                }
                            }
                            _ => {
                                errors.push(ValidationError {
                                    message: format!(
                                        "Unknown OPTIONS key '{}'. Supported keys: timeout, retry, retry-delay, no-retry, compression",
                                        key
                                    ),
                                    line: Some(section.start_line),
                                    severity: ErrorSeverity::Warning,
                                });
                            }
                        }
                    }
                }
            }
        }
    }

    // Validate assertions
    for section in document.sections_by_type(SectionType::Asserts) {
        if let SectionContent::Assertions(assertions) = &section.content {
            for assertion in assertions {
                if assertion.is_empty() {
                    errors.push(ValidationError {
                        message: "Empty assertion found".to_string(),
                        line: Some(section.start_line),
                        severity: ErrorSeverity::Warning,
                    });
                }
            }
        }
    }
}

/// Validate structure
fn validate_structure(document: &GctfDocument, errors: &mut Vec<ValidationError>) {
    // Check for duplicate non-multiple sections
    let mut seen_sections = std::collections::HashSet::new();
    let mut meta_count = 0;
    let mut meta_first_line = None;

    for section in &document.sections {
        if section.section_type == SectionType::Meta {
            meta_count += 1;
            if meta_first_line.is_none() {
                meta_first_line = Some(section.start_line);
            }
        }

        if !section.section_type.is_multiple_allowed() {
            if seen_sections.contains(&section.section_type) {
                errors.push(ValidationError {
                    message: format!("Duplicate {:?} section found", section.section_type),
                    line: Some(section.start_line),
                    severity: ErrorSeverity::Error,
                });
            }
            seen_sections.insert(section.section_type);
        }
    }

    // Validate META section: only 0 or 1 per file, must be first if present
    if meta_count > 1 {
        errors.push(ValidationError {
            message: "Only one META section is allowed per file".to_string(),
            line: meta_first_line,
            severity: ErrorSeverity::Error,
        });
    }

    // Check META is first section (if present)
    if meta_count == 1
        && let Some(first_section) = document.sections.first()
        && first_section.section_type != SectionType::Meta
    {
        errors.push(ValidationError {
            message: "META section must be the first section in the file".to_string(),
            line: meta_first_line,
            severity: ErrorSeverity::Error,
        });
    }

    // Validate section order (optional, but good for readability)
    // Not enforcing strict order, just checking for obvious issues
    // TODO: Add optional strict ordering validation

    // Validate inline options are only on supported sections
    for section in &document.sections {
        let has_any_inline_options = section.inline_options.with_asserts
            || section.inline_options.partial
            || section.inline_options.tolerance.is_some()
            || !section.inline_options.redact.is_empty()
            || section.inline_options.unordered_arrays;

        if !has_any_inline_options {
            continue;
        }

        match section.section_type {
            SectionType::Response => {
                // All known options are supported for RESPONSE section
            }
            SectionType::Error => {
                if section.inline_options.partial
                    || section.inline_options.tolerance.is_some()
                    || !section.inline_options.redact.is_empty()
                    || section.inline_options.unordered_arrays
                {
                    errors.push(ValidationError {
                        message: "ERROR section only supports with_asserts inline option"
                            .to_string(),
                        line: Some(section.start_line),
                        severity: ErrorSeverity::Warning,
                    });
                }
            }
            _ => {
                errors.push(ValidationError {
                    message: format!(
                        "Inline options are not supported for {:?} section",
                        section.section_type
                    ),
                    line: Some(section.start_line),
                    severity: ErrorSeverity::Warning,
                });
            }
        }
    }
}

/// Check if validation passed (no errors)
pub fn validation_passed(errors: &[ValidationError]) -> bool {
    !errors.iter().any(|e| e.severity == ErrorSeverity::Error)
}

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

    fn create_test_document() -> GctfDocument {
        let mut doc = GctfDocument::new("test.gctf".to_string());

        doc.sections = vec![
            Section {
                section_type: SectionType::Address,
                content: SectionContent::Single("localhost:4770".to_string()),
                inline_options: InlineOptions::default(),
                raw_content: "localhost:4770".to_string(),
                start_line: 1,
                end_line: 1,
            },
            Section {
                section_type: SectionType::Endpoint,
                content: SectionContent::Single("my.Service/Method".to_string()),
                inline_options: InlineOptions::default(),
                raw_content: "my.Service/Method".to_string(),
                start_line: 3,
                end_line: 3,
            },
        ];

        doc
    }

    #[test]
    fn test_validate_required_sections_pass() {
        let doc = create_test_document();
        let result = validate_document(&doc);
        // Should fail because no REQUEST or ASSERTS
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_endpoint_format() {
        let mut doc = create_test_document();
        doc.sections[1].content = SectionContent::Single("invalid_endpoint".to_string());

        let result = validate_document(&doc);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_address_format() {
        let mut doc = create_test_document();
        doc.sections[0].content = SectionContent::Single("invalid_address".to_string());

        let result = validate_document(&doc);
        assert!(result.is_err());
    }

    #[test]
    fn test_validation_passed() {
        let errors = vec![
            ValidationError {
                message: "Warning".to_string(),
                line: Some(1),
                severity: ErrorSeverity::Warning,
            },
            ValidationError {
                message: "Info".to_string(),
                line: Some(2),
                severity: ErrorSeverity::Info,
            },
        ];

        assert!(validation_passed(&errors));
    }

    #[test]
    fn test_validation_failed() {
        let errors = vec![
            ValidationError {
                message: "Warning".to_string(),
                line: Some(1),
                severity: ErrorSeverity::Warning,
            },
            ValidationError {
                message: "Error".to_string(),
                line: Some(2),
                severity: ErrorSeverity::Error,
            },
        ];

        assert!(!validation_passed(&errors));
    }

    #[test]
    fn test_validate_document_diagnostics() {
        let doc = create_test_document();
        let errors = validate_document_diagnostics(&doc);
        // Should have some errors or warnings
        assert!(!errors.is_empty());
    }

    #[test]
    fn test_validate_document_with_response() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 5,
            end_line: 6,
        });

        let result = validate_document(&doc);
        // Should pass with ADDRESS, ENDPOINT, and RESPONSE
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_document_with_error_section() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Error,
            content: SectionContent::Json(serde_json::json!({"code": 5})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"code\": 5}".to_string(),
            start_line: 5,
            end_line: 6,
        });

        let result = validate_document(&doc);
        // Should pass with ADDRESS, ENDPOINT, and ERROR
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_document_with_asserts() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Asserts,
            content: SectionContent::Assertions(vec![".id == 1".to_string()]),
            inline_options: InlineOptions::default(),
            raw_content: ".id == 1".to_string(),
            start_line: 5,
            end_line: 5,
        });

        let result = validate_document(&doc);
        // Should pass with ADDRESS, ENDPOINT, and ASSERTS
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_document_missing_endpoint() {
        let mut doc = create_test_document();
        doc.sections.remove(1); // Remove ENDPOINT

        let errors = validate_document_diagnostics(&doc);
        let has_endpoint_error = errors.iter().any(|e| e.message.contains("ENDPOINT"));
        assert!(has_endpoint_error);
    }

    #[test]
    fn test_validate_document_response_error_conflict() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 5,
            end_line: 6,
        });
        doc.sections.push(Section {
            section_type: SectionType::Error,
            content: SectionContent::Json(serde_json::json!({"code": 5})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"code\": 5}".to_string(),
            start_line: 7,
            end_line: 8,
        });

        let errors = validate_document_diagnostics(&doc);
        let has_conflict_error = errors
            .iter()
            .any(|e| e.message.contains("RESPONSE") && e.message.contains("ERROR"));
        assert!(has_conflict_error);
    }

    #[test]
    fn test_validate_document_empty_requests() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Request,
            content: SectionContent::Empty,
            inline_options: InlineOptions::default(),
            raw_content: "".to_string(),
            start_line: 5,
            end_line: 5,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 6,
            end_line: 7,
        });

        let result = validate_document(&doc);
        // Empty REQUEST is allowed
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_document_invalid_request_json() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Request,
            content: SectionContent::Json(serde_json::json!({"key": "value"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"key\": \"value\"}".to_string(),
            start_line: 5,
            end_line: 6,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 7,
            end_line: 8,
        });

        let result = validate_document(&doc);
        // Valid JSON should pass
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_document_invalid_response_json() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Request,
            content: SectionContent::Json(serde_json::json!({"key": "value"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"key\": \"value\"}".to_string(),
            start_line: 5,
            end_line: 6,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 7,
            end_line: 8,
        });

        let errors = validate_document_diagnostics(&doc);
        // Valid JSON should have no errors
        let has_json_errors = errors.iter().any(|e| e.message.contains("JSON"));
        assert!(!has_json_errors);
    }

    #[test]
    fn test_validate_error_details_must_be_array() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Error,
            content: SectionContent::Json(serde_json::json!({
                "code": 3,
                "details": {"@type": "type.googleapis.com/google.rpc.ErrorInfo"}
            })),
            inline_options: InlineOptions::default(),
            raw_content: "".to_string(),
            start_line: 5,
            end_line: 8,
        });

        let errors = validate_document_diagnostics(&doc);
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("field 'details' must be an array"))
        );
    }

    #[test]
    fn test_validate_error_details_items_must_be_objects() {
        let mut doc = create_test_document();
        doc.sections.push(Section {
            section_type: SectionType::Error,
            content: SectionContent::Json(serde_json::json!({
                "code": 3,
                "details": ["not-an-object"]
            })),
            inline_options: InlineOptions::default(),
            raw_content: "".to_string(),
            start_line: 5,
            end_line: 8,
        });

        let errors = validate_document_diagnostics(&doc);
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("'details' items must be objects"))
        );
    }

    #[test]
    fn test_validate_document_address_from_env() {
        // Set env var
        unsafe {
            std::env::set_var(crate::config::ENV_GRPCTESTIFY_ADDRESS, "env:5000");
        }

        let mut doc = GctfDocument::new("test.gctf".to_string());
        doc.sections.push(Section {
            section_type: SectionType::Endpoint,
            content: SectionContent::Single("Service/Method".to_string()),
            inline_options: InlineOptions::default(),
            raw_content: "Service/Method".to_string(),
            start_line: 1,
            end_line: 1,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 2,
            end_line: 3,
        });

        let result = validate_document(&doc);
        // Should pass because address comes from env
        assert!(result.is_ok());

        // Clean up
        unsafe {
            std::env::remove_var(crate::config::ENV_GRPCTESTIFY_ADDRESS);
        }
    }

    #[test]
    fn test_validate_options_unknown_key_warning() {
        let mut doc = create_test_document();
        let mut options = std::collections::HashMap::new();
        options.insert("unknown".to_string(), "value".to_string());
        doc.sections.push(Section {
            section_type: SectionType::Options,
            content: SectionContent::KeyValues(options),
            inline_options: InlineOptions::default(),
            raw_content: "unknown: value".to_string(),
            start_line: 5,
            end_line: 6,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 7,
            end_line: 8,
        });

        let diagnostics = validate_document_diagnostics(&doc);
        assert!(diagnostics.iter().any(|d| {
            d.severity == ErrorSeverity::Warning && d.message.contains("Unknown OPTIONS key")
        }));
    }

    #[test]
    fn test_validate_options_dry_run_is_unknown_key_warning() {
        let mut doc = create_test_document();
        let mut options = std::collections::HashMap::new();
        options.insert("dry_run".to_string(), "true".to_string());
        doc.sections.push(Section {
            section_type: SectionType::Options,
            content: SectionContent::KeyValues(options),
            inline_options: InlineOptions::default(),
            raw_content: "dry_run: true".to_string(),
            start_line: 5,
            end_line: 6,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 7,
            end_line: 8,
        });

        let diagnostics = validate_document_diagnostics(&doc);
        assert!(diagnostics.iter().any(|d| {
            d.severity == ErrorSeverity::Warning
                && d.message
                    .contains("Unknown OPTIONS key 'dry_run'. Supported keys: timeout, retry, retry-delay, no-retry, compression")
        }));
    }

    #[test]
    fn test_validate_options_timeout_invalid_error() {
        let mut doc = create_test_document();
        let mut options = std::collections::HashMap::new();
        options.insert("timeout".to_string(), "0".to_string());
        doc.sections.push(Section {
            section_type: SectionType::Options,
            content: SectionContent::KeyValues(options),
            inline_options: InlineOptions::default(),
            raw_content: "timeout: 0".to_string(),
            start_line: 5,
            end_line: 6,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 7,
            end_line: 8,
        });

        let diagnostics = validate_document_diagnostics(&doc);
        assert!(diagnostics.iter().any(|d| {
            d.severity == ErrorSeverity::Error
                && d.message
                    .contains("OPTIONS.timeout must be a positive integer")
        }));
    }

    #[test]
    fn test_validate_options_kebab_case_keys_are_supported() {
        let mut doc = create_test_document();
        let mut options = std::collections::HashMap::new();
        options.insert("timeout".to_string(), "5".to_string());
        options.insert("retry".to_string(), "2".to_string());
        options.insert("retry-delay".to_string(), "0.5".to_string());
        options.insert("no-retry".to_string(), "false".to_string());
        options.insert("compression".to_string(), "gzip".to_string());
        doc.sections.push(Section {
            section_type: SectionType::Options,
            content: SectionContent::KeyValues(options),
            inline_options: InlineOptions::default(),
            raw_content: "".to_string(),
            start_line: 5,
            end_line: 8,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 9,
            end_line: 10,
        });

        let diagnostics = validate_document_diagnostics(&doc);
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.message.contains("Unknown OPTIONS key"))
        );
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.severity == ErrorSeverity::Error)
        );
    }

    #[test]
    fn test_validate_options_compression_invalid_error() {
        let mut doc = create_test_document();
        let mut options = std::collections::HashMap::new();
        options.insert("compression".to_string(), "brotli".to_string());
        doc.sections.push(Section {
            section_type: SectionType::Options,
            content: SectionContent::KeyValues(options),
            inline_options: InlineOptions::default(),
            raw_content: "compression: brotli".to_string(),
            start_line: 5,
            end_line: 6,
        });
        doc.sections.push(Section {
            section_type: SectionType::Response,
            content: SectionContent::Json(serde_json::json!({"result": "ok"})),
            inline_options: InlineOptions::default(),
            raw_content: "{\"result\": \"ok\"}".to_string(),
            start_line: 7,
            end_line: 8,
        });

        let diagnostics = validate_document_diagnostics(&doc);
        assert!(diagnostics.iter().any(|d| {
            d.severity == ErrorSeverity::Error
                && d.message
                    .contains("OPTIONS.compression must be one of: none, gzip")
        }));
    }

    #[test]
    fn test_validation_error_debug() {
        let error = ValidationError {
            message: "test error".to_string(),
            line: Some(10),
            severity: ErrorSeverity::Error,
        };
        let debug_str = format!("{:?}", error);
        assert!(debug_str.contains("ValidationError"));
        assert!(debug_str.contains("test error"));
    }

    #[test]
    fn test_error_severity_serialize() {
        let error = ErrorSeverity::Error;
        let json = serde_json::to_string(&error).unwrap();
        assert_eq!(json, "\"error\"");

        let warning = ErrorSeverity::Warning;
        let json = serde_json::to_string(&warning).unwrap();
        assert_eq!(json, "\"warning\"");
    }
}