grpctestify 1.5.0

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
// Error recovery parser for GCTF files
// Parses as much as possible and collects all errors

use crate::diagnostics::{DiagnosticCode, DiagnosticCollection, Range};
use crate::parser::assertions::strip_assertion_comments;
use crate::parser::ast::{
    DocumentMetadata, FileMeta, GctfDocument, Section, SectionContent, SectionType,
};
use crate::parser::gctf_tokenizer;
use std::path::Path;

/// Result of error recovery parsing
pub struct ErrorRecoveryResult {
    pub document: GctfDocument,
    pub diagnostics: DiagnosticCollection,
    pub recovered_sections: usize,
    pub failed_sections: usize,
}

/// Parse GCTF file with error recovery.
/// Supports multiple documents separated by `--- NEW ---`.
pub fn parse_with_recovery(file_path: &Path) -> ErrorRecoveryResult {
    let content = std::fs::read_to_string(file_path).unwrap_or_default();
    parse_content_with_recovery(&content, file_path.to_string_lossy().as_ref())
}

/// Parse GCTF content string with error recovery.
/// Documents are determined implicitly: REQUEST after RESPONSE/ERROR/ASSERTS,
/// or ENDPOINT/ADDRESS starts a new document.
pub fn parse_content_with_recovery(content: &str, file_path: &str) -> ErrorRecoveryResult {
    let single = parse_single_with_recovery(content, file_path);

    // Split by implicit boundaries
    let docs = crate::parser::split_sections_by_boundary(&single.document.sections);

    if docs.len() <= 1 {
        return single;
    }

    // Link in reverse
    let mut head: Option<GctfDocument> = None;
    let total_recovered = single.recovered_sections;
    let total_failed = single.failed_sections;

    for doc_sections in docs.into_iter().rev() {
        let mut doc = build_doc_from_sections(&doc_sections, file_path);
        doc.next_document = head.map(Box::new);
        head = Some(doc);
    }

    ErrorRecoveryResult {
        document: head.unwrap_or(single.document),
        diagnostics: single.diagnostics,
        recovered_sections: total_recovered,
        failed_sections: total_failed,
    }
}

fn build_doc_from_sections(sections: &[Section], file_path: &str) -> GctfDocument {
    GctfDocument {
        file_path: file_path.to_string(),
        sections: sections.to_vec(),
        metadata: DocumentMetadata {
            source: None,
            mtime: None,
            parsed_at: 0,
        },
        next_document: None,
    }
}

/// Parse a single document (no `--- NEW ---` splitting)
fn parse_single_with_recovery(content: &str, file_path: &str) -> ErrorRecoveryResult {
    let mut diagnostics = DiagnosticCollection::new();
    let mut sections = Vec::new();
    let mut recovered_sections = 0;
    let mut failed_sections = 0;

    let lines: Vec<&str> = content.lines().collect();
    let mut current_line = 0;

    // Parse sections one by one, collecting errors
    while current_line < lines.len() {
        match parse_section(&lines, current_line, &mut diagnostics) {
            Ok((section, end_line)) => {
                sections.push(section);
                recovered_sections += 1;
                current_line = end_line;
            }
            Err(end_line) => {
                failed_sections += 1;
                current_line = end_line;
            }
        }
    }

    let document = GctfDocument {
        file_path: file_path.to_string(),
        sections,
        metadata: DocumentMetadata {
            source: Some(content.to_string()),
            mtime: None,
            parsed_at: 0,
        },
        next_document: None,
    };

    ErrorRecoveryResult {
        document,
        diagnostics,
        recovered_sections,
        failed_sections,
    }
}

/// Parse a single section from lines
fn parse_section(
    lines: &[&str],
    start_line: usize,
    diagnostics: &mut DiagnosticCollection,
) -> Result<(Section, usize), usize> {
    let line = lines.get(start_line).copied().unwrap_or("");
    let trimmed = line.trim();

    // Skip empty lines and comments
    if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") {
        return Err(start_line + 1);
    }

    // Check for section header
    if !trimmed.starts_with("---") {
        // Not a section header, skip line
        return Err(start_line + 1);
    }

    // Parse section header
    let section_type = match parse_section_header(trimmed, start_line, diagnostics) {
        Some(t) => t,
        None => return Err(start_line + 1),
    };

    // Find section content
    let content_start = start_line + 1;
    let (content, content_end) = extract_section_content(lines, content_start, section_type);

    // Parse section content with error isolation
    let content_result = parse_section_content(&content, content_start, section_type, diagnostics);

    let section = Section {
        section_type,
        content: content_result,
        inline_options: Default::default(),
        raw_content: content.join("\n"),
        start_line,
        end_line: content_end,
    };

    Ok((section, content_end + 1))
}

/// Parse section header like "--- ENDPOINT ---"
fn parse_section_header(
    line: &str,
    line_num: usize,
    diagnostics: &mut DiagnosticCollection,
) -> Option<SectionType> {
    // Remove --- delimiters
    let without_delimiters = line.trim_start_matches('-').trim_end_matches('-').trim();

    // Extract section name and inline options
    let parts: Vec<&str> = without_delimiters.splitn(2, ' ').collect();
    let section_name = parts[0].trim();

    // Parse section type
    let section_type = match section_name.to_uppercase().as_str() {
        "ADDRESS" => SectionType::Address,
        "ENDPOINT" => SectionType::Endpoint,
        "REQUEST" => SectionType::Request,
        "RESPONSE" => SectionType::Response,
        "ERROR" => SectionType::Error,
        "EXTRACT" => SectionType::Extract,
        "ASSERTS" => SectionType::Asserts,
        "REQUEST_HEADERS" => SectionType::RequestHeaders,
        "HEADERS" => {
            diagnostics.warning(
                DiagnosticCode::DeprecatedSymbol,
                "HEADERS is deprecated, use REQUEST_HEADERS".to_string(),
                Range::at_line(line_num),
            );
            SectionType::RequestHeaders
        }
        "TLS" => SectionType::Tls,
        "PROTO" => SectionType::Proto,
        "OPTIONS" => SectionType::Options,
        "META" => SectionType::Meta,
        _ => {
            diagnostics.warning(
                DiagnosticCode::UnknownSectionType,
                format!("Unknown section type: {}", section_name),
                Range::at_line(line_num),
            );
            return None;
        }
    };

    // Parse inline options if present
    if parts.len() > 1 {
        parse_inline_options(parts[1], line_num, diagnostics);
    }

    Some(section_type)
}

/// Extract content lines for a section
fn extract_section_content(
    lines: &[&str],
    start: usize,
    _section_type: SectionType,
) -> (Vec<String>, usize) {
    let mut content = Vec::new();
    let mut end_line = start;

    for (i, line) in lines.iter().enumerate().skip(start) {
        let trimmed = line.trim();

        // Check for next section header
        if trimmed.starts_with("---") && trimmed.ends_with("---") {
            break;
        }

        content.push(line.to_string());
        end_line = i;
    }

    (content, end_line)
}

/// Parse section content based on type
fn parse_section_content(
    content: &[String],
    start_line: usize,
    section_type: SectionType,
    diagnostics: &mut DiagnosticCollection,
) -> SectionContent {
    let content_str = content.join("\n");

    match section_type {
        SectionType::Address | SectionType::Endpoint => {
            SectionContent::Single(content_str.trim().to_string())
        }
        SectionType::Request | SectionType::Response | SectionType::Error => {
            if content_str.trim().is_empty() {
                SectionContent::Empty
            } else {
                // Try to parse as JSON5 (with comments), but don't fail - just add diagnostic
                match super::json_mod::from_str(&content_str) {
                    Ok(value) => SectionContent::Json(value),
                    Err(e) => {
                        // Add error but continue parsing
                        diagnostics.error(
                            DiagnosticCode::JsonParseError,
                            format!("Failed to parse JSON: {}", e),
                            Range::at_line(start_line),
                        );
                        // Return as-is to allow further processing
                        SectionContent::Json(serde_json::Value::String(content_str))
                    }
                }
            }
        }
        SectionType::Extract => {
            // Parse extract variables
            let mut extractions = std::collections::HashMap::new();
            for (i, line) in content.iter().enumerate() {
                let trimmed = line.trim();
                if trimmed.is_empty() || trimmed.starts_with('#') {
                    continue;
                }

                if let Some(eq_pos) = trimmed.find('=') {
                    let name = trimmed[..eq_pos].trim().to_string();
                    let query = trimmed[eq_pos + 1..].trim().to_string();
                    extractions.insert(name, query);
                } else {
                    diagnostics.warning(
                        DiagnosticCode::InvalidSyntax,
                        "Invalid EXTRACT syntax, expected: name = query",
                        Range::at_line(start_line + i),
                    );
                }
            }
            SectionContent::Extract(extractions)
        }
        SectionType::Asserts => {
            // Collect assertion lines
            let assertions: Vec<String> = content
                .iter()
                .filter_map(|line| strip_assertion_comments(line))
                .collect();
            SectionContent::Assertions(assertions)
        }
        SectionType::RequestHeaders
        | SectionType::Tls
        | SectionType::Proto
        | SectionType::Options => {
            // Parse key-value pairs
            let mut key_values = std::collections::HashMap::new();
            for (i, line) in content.iter().enumerate() {
                let trimmed = line.trim();
                if trimmed.is_empty() || trimmed.starts_with('#') {
                    continue;
                }

                if let Some(colon_pos) = trimmed.find(':') {
                    let key = trimmed[..colon_pos].trim().to_string();
                    let value = trimmed[colon_pos + 1..].trim().to_string();
                    key_values.insert(key, value);
                } else {
                    diagnostics.warning(
                        DiagnosticCode::InvalidSyntax,
                        "Invalid key-value syntax, expected: key: value",
                        Range::at_line(start_line + i),
                    );
                }
            }
            SectionContent::KeyValues(key_values)
        }
        SectionType::Meta => {
            // Use tokenizer to strip GCTF comment lines before parsing YAML
            let raw = content.join("\n");
            let tokens = gctf_tokenizer::tokenize_gctf(&raw);
            let yaml_lines: Vec<String> = content
                .iter()
                .zip(tokens.iter())
                .filter(|(_, t)| !matches!(t.kind, gctf_tokenizer::GctfTokenKind::Comment(_)))
                .map(|(l, _)| l.clone())
                .collect();
            let cleaned = yaml_lines.join("\n");
            let meta = serde_yaml_ng::from_str::<FileMeta>(&cleaned).unwrap_or_default();
            SectionContent::Meta(meta)
        }
    }
}

/// Parse inline options like "with_asserts=true"
fn parse_inline_options(
    options_str: &str,
    line_num: usize,
    diagnostics: &mut DiagnosticCollection,
) {
    // Parse options like: with_asserts=true unordered_arrays=true
    for option in options_str.split_whitespace() {
        if let Some(eq_pos) = option.find('=') {
            let key = &option[..eq_pos];
            let value = &option[eq_pos + 1..];

            match key {
                "with_asserts" | "unordered_arrays" | "partial" => {
                    // Valid boolean options
                    if value != "true" && value != "false" {
                        diagnostics.warning(
                            DiagnosticCode::InvalidFieldValue,
                            format!("Invalid boolean value for {}: {}", key, value),
                            Range::at_line(line_num),
                        );
                    }
                }
                "tolerance" => {
                    // Numeric option
                    if value.parse::<f64>().is_err() {
                        diagnostics.warning(
                            DiagnosticCode::InvalidFieldValue,
                            format!("Invalid numeric value for {}: {}", key, value),
                            Range::at_line(line_num),
                        );
                    }
                }
                _ => {
                    diagnostics.hint(
                        DiagnosticCode::InvalidFieldValue,
                        format!("Unknown inline option: {}", key),
                        Range::at_line(line_num),
                    );
                }
            }
        }
    }
}

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

    #[test]
    fn test_parse_with_recovery_valid_file() {
        let content = r#"--- ENDPOINT ---
service/Method

--- REQUEST ---
{"key": "value"}

--- RESPONSE ---
{"result": "ok"}
"#;

        let result = parse_content_with_recovery(content, "test.gctf");

        assert_eq!(result.recovered_sections, 3);
        assert_eq!(result.failed_sections, 0);
        assert!(!result.document.sections.is_empty());
    }

    #[test]
    fn test_parse_with_recovery_invalid_json() {
        let content = r#"--- ENDPOINT ---
service/Method

--- REQUEST ---
{"key": "value"

--- RESPONSE ---
{"result": "ok"}
"#;

        let result = parse_content_with_recovery(content, "test.gctf");

        // Should recover and continue parsing
        assert_eq!(result.recovered_sections, 3);
        assert_eq!(result.failed_sections, 0);
        // Should have diagnostic for invalid JSON
        assert!(result.diagnostics.has_errors());
    }

    #[test]
    fn test_parse_with_recovery_multiple_errors() {
        let content = r#"--- ENDPOINT ---
service/Method

--- REQUEST ---
{invalid json

--- RESPONSE ---
{also invalid

--- EXTRACT ---
var = .field
"#;

        let result = parse_content_with_recovery(content, "test.gctf");

        // Should recover all sections
        assert_eq!(result.recovered_sections, 4);
        // Should have multiple diagnostics
        assert!(result.diagnostics.diagnostics.len() >= 2);
    }

    #[test]
    fn test_parse_with_recovery_unknown_section() {
        let content = r#"--- ENDPOINT ---
service/Method

--- UNKNOWN_SECTION ---
content

--- RESPONSE ---
{"ok": true}
"#;

        let result = parse_content_with_recovery(content, "test.gctf");

        // Should skip unknown section
        assert!(result.diagnostics.has_warnings());
    }

    #[test]
    fn test_parse_with_recovery_invalid_extract() {
        let content = r#"--- EXTRACT ---
valid = .field
invalid line without equals
another = .field2
"#;

        let result = parse_content_with_recovery(content, "test.gctf");

        // Should parse valid extracts and warn about invalid
        assert!(result.diagnostics.has_warnings());
    }

    #[test]
    fn test_parse_with_recovery_asserts_double_slash_comments() {
        let content = r#"--- ENDPOINT ---
grpc.health.v1.Health/Watch

--- REQUEST ---
{"service": "examples.health.watch"}

--- ASSERTS ---
// Watch delay in stubs.yaml is 10ms.
// Delay applies before the first message in the scope.
@scope_message_count() == 2
@elapsed_ms() >= 10
@total_elapsed_ms() >= 10
"#;

        let result = parse_content_with_recovery(content, "test.gctf");
        let asserts = result
            .document
            .sections
            .iter()
            .find(|s| s.section_type == SectionType::Asserts)
            .expect("ASSERTS section should be parsed");

        if let SectionContent::Assertions(lines) = &asserts.content {
            assert_eq!(lines.len(), 3);
            assert_eq!(lines[0], "@scope_message_count() == 2");
            assert_eq!(lines[1], "@elapsed_ms() >= 10");
            assert_eq!(lines[2], "@total_elapsed_ms() >= 10");
        } else {
            panic!("expected assertions content");
        }
    }

    #[test]
    fn test_parse_with_recovery_asserts_inline_comments() {
        let content = r#"--- ENDPOINT ---
grpc.health.v1.Health/Watch

--- REQUEST ---
{"service": "examples.health.watch"}

--- ASSERTS ---
@scope_message_count() == 2 // exactly two updates expected
@elapsed_ms() >= 10 # startup delay should be applied
@regex(.note, "^https://example.com")
"#;

        let result = parse_content_with_recovery(content, "test.gctf");
        let asserts = result
            .document
            .sections
            .iter()
            .find(|s| s.section_type == SectionType::Asserts)
            .expect("ASSERTS section should be parsed");

        if let SectionContent::Assertions(lines) = &asserts.content {
            assert_eq!(lines.len(), 3);
            assert_eq!(lines[0], "@scope_message_count() == 2");
            assert_eq!(lines[1], "@elapsed_ms() >= 10");
            assert_eq!(lines[2], "@regex(.note, \"^https://example.com\")");
        } else {
            panic!("expected assertions content");
        }
    }

    #[test]
    fn test_parse_with_recovery_headers_deprecated() {
        let content = r#"--- ENDPOINT ---
svc/Method

--- HEADERS ---
content-type: application/grpc

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert!(result.diagnostics.has_warnings());
        // Should still parse REQUEST and RESPONSE
        assert_eq!(result.recovered_sections, 4);
    }

    #[test]
    fn test_parse_with_recovery_tls_section_key_values() {
        let content = r#"--- TLS ---
enabled: true
cert_path: /path/to/cert

--- ENDPOINT ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert_eq!(result.recovered_sections, 4);
        let tls = result
            .document
            .sections
            .iter()
            .find(|s| s.section_type == SectionType::Tls)
            .expect("TLS section should be parsed");
        if let SectionContent::KeyValues(kvs) = &tls.content {
            assert_eq!(kvs.get("enabled"), Some(&"true".to_string()));
            assert_eq!(kvs.get("cert_path"), Some(&"/path/to/cert".to_string()));
        } else {
            panic!("expected key-values content");
        }
    }

    #[test]
    fn test_parse_with_recovery_options_section() {
        let content = r#"--- OPTIONS ---
timeout: 5000
retries: 3

--- ENDPOINT ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert_eq!(result.recovered_sections, 4);
        let opts = result
            .document
            .sections
            .iter()
            .find(|s| s.section_type == SectionType::Options)
            .expect("OPTIONS section should be parsed");
        if let SectionContent::KeyValues(kvs) = &opts.content {
            assert_eq!(kvs.get("timeout"), Some(&"5000".to_string()));
            assert_eq!(kvs.get("retries"), Some(&"3".to_string()));
        } else {
            panic!("expected key-values content");
        }
    }

    #[test]
    fn test_parse_with_recovery_proto_section() {
        let content = r#"--- PROTO ---
protos: ["service.proto"]
import_dirs: ["/protos"]

--- ENDPOINT ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert_eq!(result.recovered_sections, 4);
    }

    #[test]
    fn test_parse_with_recovery_empty_response() {
        let content = r#"--- ENDPOINT ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---

"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert_eq!(result.recovered_sections, 3);
        let response = result
            .document
            .sections
            .iter()
            .find(|s| s.section_type == SectionType::Response)
            .expect("RESPONSE section should exist");
        assert!(matches!(response.content, SectionContent::Empty));
    }

    #[test]
    fn test_parse_with_recovery_non_section_header_lines() {
        let content = r#"some random line
more text
--- ENDPOINT ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        // Non-section-header lines should be skipped
        assert_eq!(result.recovered_sections, 3);
    }

    #[test]
    fn test_parse_with_recovery_comment_lines() {
        let content = r#"# This is a comment
// Another comment

--- ENDPOINT ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert_eq!(result.recovered_sections, 3);
    }

    #[test]
    fn test_parse_with_recovery_inline_options_invalid_boolean() {
        let content = r#"--- ENDPOINT with_asserts=maybe ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert!(result.diagnostics.has_warnings());
        assert_eq!(result.recovered_sections, 3);
    }

    #[test]
    fn test_parse_with_recovery_inline_options_invalid_numeric() {
        let content = r#"--- ENDPOINT tolerance=abc ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert!(result.diagnostics.has_warnings());
    }

    #[test]
    fn test_parse_with_recovery_inline_options_unknown() {
        let content = r#"--- ENDPOINT unknown_option=value ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        // Unknown options produce hints, not warnings
        assert_eq!(result.recovered_sections, 3);
    }

    #[test]
    fn test_parse_with_recovery_inline_options_valid() {
        let content = r#"--- ENDPOINT with_asserts=true unordered_arrays=true partial=false tolerance=0.05 ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert_eq!(result.recovered_sections, 3);
    }

    #[test]
    fn test_parse_with_recovery_request_headers_section() {
        let content = r#"--- ENDPOINT ---
svc/Method

--- REQUEST_HEADERS ---
authorization: Bearer token
x-custom: value

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert_eq!(result.recovered_sections, 4);
        let headers = result
            .document
            .sections
            .iter()
            .find(|s| s.section_type == SectionType::RequestHeaders)
            .expect("REQUEST_HEADERS section should be parsed");
        if let SectionContent::KeyValues(kvs) = &headers.content {
            assert_eq!(kvs.get("authorization"), Some(&"Bearer token".to_string()));
            assert_eq!(kvs.get("x-custom"), Some(&"value".to_string()));
        } else {
            panic!("expected key-values content");
        }
    }

    #[test]
    fn test_parse_with_recovery_invalid_key_value_syntax() {
        let content = r#"--- TLS ---
enabled: true
invalid line without colon

--- ENDPOINT ---
svc/Method

--- REQUEST ---
{}

--- RESPONSE ---
{}
"#;
        let result = parse_content_with_recovery(content, "test.gctf");
        assert!(result.diagnostics.has_warnings());
        assert_eq!(result.recovered_sections, 4);
    }
}