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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
// Workflow events - semantic execution flow from ExecutionPlan
// Supports: N requests, N responses, multiple backends, interleaved streaming

use serde::{Deserialize, Serialize};

/// Workflow event - represents a semantic step in test execution
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum WorkflowEvent {
    /// Test file loaded
    TestLoaded { file_path: String },

    /// Connecting to a backend service
    Connect { backend: String, address: String },

    /// Connected to backend
    Connected { backend: String, address: String },

    /// Loading service descriptors
    LoadDescriptors { backend: String, service: String },

    /// Descriptors loaded
    DescriptorsLoaded {
        backend: String,
        service: String,
        method_count: usize,
    },

    /// Sending a request
    SendRequest {
        backend: String,
        request_index: usize,
        content_type: String,
        line_range: (usize, usize),
    },

    /// Request sent
    RequestSent {
        backend: String,
        request_index: usize,
    },

    /// Receiving a response
    ReceiveResponse {
        backend: String,
        response_index: usize,
        expectation_type: String,
    },

    /// Response received
    ResponseReceived {
        backend: String,
        response_index: usize,
        has_content: bool,
        options: ResponseOptions,
    },

    /// Extracting variables from response
    Extract {
        variables: Vec<String>,
        source_response_index: Option<usize>,
        line_range: (usize, usize),
    },

    /// Variables extracted
    Extracted { variables: Vec<String> },

    /// Running assertions
    Assert {
        count: usize,
        target_response_index: Option<usize>,
        line_range: (usize, usize),
    },

    /// Assertions completed
    Asserted { passed: usize, failed: usize },

    /// Error occurred
    Error { code: i32, message: String },

    /// Test execution complete
    Complete {
        total_requests: usize,
        total_responses: usize,
        total_extractions: usize,
        total_assertions: usize,
        backends_used: Vec<String>,
    },

    /// Semantic analysis results (type mismatches, unknown plugins)
    SemanticAnalysis {
        type_mismatches: Vec<SemanticError>,
        unknown_plugins: Vec<SemanticError>,
    },

    /// Optimization hints found during analysis
    OptimizationFound { hints: Vec<OptimizationHint> },

    /// Validation result
    ValidationResult { passed: bool, errors: Vec<String> },
}

/// Semantic error from type mismatches or unknown plugins
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SemanticError {
    pub line: usize,
    pub rule_id: String,
    pub message: String,
    pub expression: Option<String>,
    pub plugin_name: Option<String>,
}

/// Optimization hint from optimizer
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OptimizationHint {
    pub line: usize,
    pub rule_id: String,
    pub before: String,
    pub after: String,
}

/// Response options from inline options
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResponseOptions {
    pub partial: bool,
    pub redact: Vec<String>,
    pub has_tolerance: bool,
    pub unordered_arrays: bool,
    pub with_asserts: bool,
}

impl From<&crate::execution::ComparisonOptions> for ResponseOptions {
    fn from(opts: &crate::execution::ComparisonOptions) -> Self {
        Self {
            partial: opts.partial,
            redact: opts.redact.clone(),
            has_tolerance: opts.tolerance.is_some(),
            unordered_arrays: opts.unordered_arrays,
            with_asserts: opts.with_asserts,
        }
    }
}

/// Workflow - sequence of events for a test
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workflow {
    pub file_path: String,
    pub events: Vec<WorkflowEvent>,
    pub summary: WorkflowSummary,
}

/// Workflow summary
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WorkflowSummary {
    pub total_requests: usize,
    pub total_responses: usize,
    pub total_extractions: usize,
    pub total_assertions: usize,
    pub backends: Vec<String>,
    pub rpc_mode: String,
    pub has_streaming: bool,
    pub has_bidi_streaming: bool,
}

impl Workflow {
    pub fn has_streaming(&self) -> bool {
        let request_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::RequestSent { .. }))
            .count();
        let response_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::ResponseReceived { .. }))
            .count();
        request_count > 1 || response_count > 1
    }

    pub fn rpc_mode_name(&self) -> &str {
        let request_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::RequestSent { .. }))
            .count();
        let response_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::ResponseReceived { .. }))
            .count();
        if request_count > 1 && response_count == 1 {
            return "Client Streaming";
        }
        if request_count == 1 && response_count > 1 {
            return "Server Streaming";
        }
        if request_count > 1 && response_count > 1 {
            return "Bidi Streaming";
        }
        "Unary"
    }
    /// Build workflow from ExecutionPlan
    pub fn from_plan(plan: &crate::execution::ExecutionPlan) -> Self {
        let mut events = Vec::new();
        let backend = "default".to_string(); // In future, support multiple backends

        // Test loaded
        events.push(WorkflowEvent::TestLoaded {
            file_path: plan.file_path.clone(),
        });

        // Connect to backend
        events.push(WorkflowEvent::Connect {
            backend: backend.clone(),
            address: plan.connection.address.clone(),
        });
        events.push(WorkflowEvent::Connected {
            backend: backend.clone(),
            address: plan.connection.address.clone(),
        });

        // Load descriptors
        events.push(WorkflowEvent::LoadDescriptors {
            backend: backend.clone(),
            service: plan.target.endpoint.clone(),
        });
        events.push(WorkflowEvent::DescriptorsLoaded {
            backend: backend.clone(),
            service: plan.target.endpoint.clone(),
            method_count: 1,
        });

        // Process requests, responses, extractions, assertions in order
        // For now, we use the order from ExecutionPlan
        // In future, we'll track explicit ordering from .gctf file

        // Requests
        for request in &plan.requests {
            events.push(WorkflowEvent::SendRequest {
                backend: backend.clone(),
                request_index: request.index,
                content_type: request.content_type.clone(),
                line_range: (request.line_start, request.line_end),
            });
            events.push(WorkflowEvent::RequestSent {
                backend: backend.clone(),
                request_index: request.index,
            });
        }

        // Expectations (responses or error)
        for expectation in &plan.expectations {
            events.push(WorkflowEvent::ReceiveResponse {
                backend: backend.clone(),
                response_index: expectation.index,
                expectation_type: expectation.expectation_type.clone(),
            });

            // If this is an error expectation, add Error event
            if expectation.expectation_type == "error"
                && let Some(content) = &expectation.content
            {
                let code = content.get("code").and_then(|c| c.as_i64()).unwrap_or(0) as i32;
                let message = content
                    .get("message")
                    .and_then(|m| m.as_str())
                    .unwrap_or("Unknown error")
                    .to_string();
                events.push(WorkflowEvent::Error { code, message });
            }

            events.push(WorkflowEvent::ResponseReceived {
                backend: backend.clone(),
                response_index: expectation.index,
                has_content: expectation.content.is_some(),
                options: ResponseOptions::from(&expectation.comparison_options),
            });
        }

        // Extractions
        for extraction in &plan.extractions {
            events.push(WorkflowEvent::Extract {
                variables: extraction.variables.keys().cloned().collect(),
                source_response_index: None, // In future, track which response
                line_range: (extraction.line_start, extraction.line_end),
            });
            events.push(WorkflowEvent::Extracted {
                variables: extraction.variables.keys().cloned().collect(),
            });
        }

        // Assertions
        for assertion in &plan.assertions {
            events.push(WorkflowEvent::Assert {
                count: assertion.assertions.len(),
                target_response_index: None, // In future, track which response
                line_range: (assertion.line_start, assertion.line_end),
            });
            events.push(WorkflowEvent::Asserted {
                passed: assertion.assertions.len(),
                failed: 0,
            });
        }

        // Complete
        events.push(WorkflowEvent::Complete {
            total_requests: plan.requests.len(),
            total_responses: plan.expectations.len(),
            total_extractions: plan.extractions.len(),
            total_assertions: plan.assertions.iter().map(|a| a.assertions.len()).sum(),
            backends_used: vec![backend.clone()],
        });

        // Detect streaming mode
        let has_streaming = plan.requests.len() > 1 || plan.expectations.len() > 1;
        let has_bidi_streaming = plan.requests.len() > 1 && plan.expectations.len() > 1;

        Self {
            file_path: plan.file_path.clone(),
            events,
            summary: WorkflowSummary {
                total_requests: plan.summary.total_requests,
                total_responses: plan.summary.total_responses,
                total_extractions: plan.extractions.len(),
                total_assertions: plan.assertions.iter().map(|a| a.assertions.len()).sum(),
                backends: vec![backend],
                rpc_mode: plan.summary.rpc_mode_name.clone(),
                has_streaming,
                has_bidi_streaming,
            },
        }
    }

    /// Get events by type
    pub fn events_by_type(&self, event_type: &str) -> Vec<&WorkflowEvent> {
        self.events
            .iter()
            .filter(|e| {
                matches!(
                    (e, event_type),
                    (WorkflowEvent::TestLoaded { .. }, "TestLoaded")
                        | (WorkflowEvent::Connect { .. }, "Connect")
                        | (WorkflowEvent::Connected { .. }, "Connected")
                        | (WorkflowEvent::LoadDescriptors { .. }, "LoadDescriptors")
                        | (WorkflowEvent::DescriptorsLoaded { .. }, "DescriptorsLoaded")
                        | (WorkflowEvent::SendRequest { .. }, "SendRequest")
                        | (WorkflowEvent::RequestSent { .. }, "RequestSent")
                        | (WorkflowEvent::ReceiveResponse { .. }, "ReceiveResponse")
                        | (WorkflowEvent::ResponseReceived { .. }, "ResponseReceived")
                        | (WorkflowEvent::Extract { .. }, "Extract")
                        | (WorkflowEvent::Extracted { .. }, "Extracted")
                        | (WorkflowEvent::Assert { .. }, "Assert")
                        | (WorkflowEvent::Asserted { .. }, "Asserted")
                        | (WorkflowEvent::Error { .. }, "Error")
                        | (WorkflowEvent::Complete { .. }, "Complete")
                        | (WorkflowEvent::SemanticAnalysis { .. }, "SemanticAnalysis")
                        | (WorkflowEvent::OptimizationFound { .. }, "OptimizationFound")
                        | (WorkflowEvent::ValidationResult { .. }, "ValidationResult")
                )
            })
            .collect()
    }

    /// Get request events
    pub fn requests(&self) -> Vec<&WorkflowEvent> {
        self.events_by_type("SendRequest")
    }

    /// Get response events
    pub fn responses(&self) -> Vec<&WorkflowEvent> {
        self.events_by_type("ResponseReceived")
    }

    /// Get extraction events
    pub fn extractions(&self) -> Vec<&WorkflowEvent> {
        self.events_by_type("Extract")
    }

    /// Get assertion events
    pub fn assertions(&self) -> Vec<&WorkflowEvent> {
        self.events_by_type("Assert")
    }

    /// Get semantic analysis events
    pub fn semantic_analysis(&self) -> Vec<&WorkflowEvent> {
        self.events_by_type("SemanticAnalysis")
    }

    /// Get optimization hint events
    pub fn optimization_hints(&self) -> Vec<&WorkflowEvent> {
        self.events_by_type("OptimizationFound")
    }

    /// Get validation result events
    pub fn validation_results(&self) -> Vec<&WorkflowEvent> {
        self.events_by_type("ValidationResult")
    }

    /// Validate workflow structure
    pub fn validate(&self) -> ValidationResult {
        let mut errors = Vec::new();

        // Must start with TestLoaded
        if !matches!(self.events.first(), Some(WorkflowEvent::TestLoaded { .. })) {
            errors.push("Workflow must start with TestLoaded event".to_string());
        }

        // Must have Connect
        if !self
            .events
            .iter()
            .any(|e| matches!(e, WorkflowEvent::Connect { .. }))
        {
            errors.push("Workflow must have Connect event".to_string());
        }

        // Must end with Complete
        if !matches!(self.events.last(), Some(WorkflowEvent::Complete { .. })) {
            errors.push("Workflow must end with Complete event".to_string());
        }

        // Each SendRequest should be followed by RequestSent
        let send_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::SendRequest { .. }))
            .count();
        let sent_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::RequestSent { .. }))
            .count();
        if send_count != sent_count {
            errors.push(format!(
                "Mismatched request events: {} sends, {} sent",
                send_count, sent_count
            ));
        }

        // Each ReceiveResponse should be followed by ResponseReceived
        let receive_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::ReceiveResponse { .. }))
            .count();
        let received_count = self
            .events
            .iter()
            .filter(|e| matches!(e, WorkflowEvent::ResponseReceived { .. }))
            .count();
        if receive_count != received_count {
            errors.push(format!(
                "Mismatched response events: {} receives, {} received",
                receive_count, received_count
            ));
        }

        ValidationResult {
            passed: errors.is_empty(),
            errors,
        }
    }

    /// Analyze streaming pattern
    pub fn analyze_streaming(&self) -> StreamingPattern {
        let mut pattern = StreamingPattern::Unary;

        let request_count = self.requests().len();
        let response_count = self.responses().len();

        // Analyze event interleaving
        let mut max_consecutive_requests = 0;
        let mut max_consecutive_responses = 0;
        let mut current_requests = 0;
        let mut current_responses = 0;

        for event in &self.events {
            match event {
                WorkflowEvent::SendRequest { .. } | WorkflowEvent::RequestSent { .. } => {
                    current_requests += 1;
                    current_responses = 0;
                    max_consecutive_requests = max_consecutive_requests.max(current_requests);
                }
                WorkflowEvent::ReceiveResponse { .. } | WorkflowEvent::ResponseReceived { .. } => {
                    current_responses += 1;
                    current_requests = 0;
                    max_consecutive_responses = max_consecutive_responses.max(current_responses);
                }
                _ => {}
            }
        }

        if request_count > 1 && response_count > 1 {
            pattern = StreamingPattern::Bidirectional {
                request_count,
                response_count,
                max_consecutive_requests,
                max_consecutive_responses,
            };
        } else if request_count > 1 {
            pattern = StreamingPattern::ClientStreaming {
                request_count,
                max_consecutive_requests,
            };
        } else if response_count > 1 {
            pattern = StreamingPattern::ServerStreaming {
                response_count,
                max_consecutive_responses,
            };
        }

        pattern
    }

    /// Build workflow from GctfDocument with full semantic analysis
    pub fn from_document_with_analysis(doc: &crate::parser::GctfDocument) -> Workflow {
        let mut events = Vec::new();

        // Test loaded
        events.push(WorkflowEvent::TestLoaded {
            file_path: doc.file_path.clone(),
        });

        // Run semantic analysis
        let type_mismatches: Vec<SemanticError> =
            crate::semantics::collect_assertion_type_mismatches(doc)
                .into_iter()
                .map(|m| SemanticError {
                    line: m.line,
                    rule_id: m.rule_id,
                    message: m.message,
                    expression: Some(m.expression),
                    plugin_name: None,
                })
                .collect();

        let unknown_plugins: Vec<SemanticError> =
            crate::semantics::collect_unknown_plugin_calls(doc)
                .into_iter()
                .map(|u| SemanticError {
                    line: u.line,
                    rule_id: u.rule_id,
                    message: u.message,
                    expression: Some(u.expression),
                    plugin_name: Some(u.plugin_name),
                })
                .collect();

        events.push(WorkflowEvent::SemanticAnalysis {
            type_mismatches,
            unknown_plugins,
        });

        // Run optimizer analysis
        let hints: Vec<OptimizationHint> = crate::optimizer::collect_assertion_optimizations(doc)
            .into_iter()
            .map(|h| OptimizationHint {
                line: h.line,
                rule_id: h.rule_id,
                before: h.before,
                after: h.after,
            })
            .collect();

        if !hints.is_empty() {
            events.push(WorkflowEvent::OptimizationFound { hints });
        }

        // Run validation
        let validation_result = crate::parser::validate_document(doc);
        let passed = validation_result.is_ok();
        let errors = match validation_result {
            Err(e) => vec![e.to_string()],
            Ok(_) => vec![],
        };

        events.push(WorkflowEvent::ValidationResult { passed, errors });

        // Build execution plan events from document
        let plan = crate::execution::ExecutionPlan::from_document(doc);
        Self::add_execution_events_from_plan(&mut events, &plan);

        // Detect streaming mode
        let has_streaming = plan.requests.len() > 1 || plan.expectations.len() > 1;
        let has_bidi_streaming = plan.requests.len() > 1 && plan.expectations.len() > 1;

        Workflow {
            file_path: doc.file_path.clone(),
            events,
            summary: WorkflowSummary {
                total_requests: plan.summary.total_requests,
                total_responses: plan.summary.total_responses,
                total_extractions: plan.extractions.len(),
                total_assertions: plan.assertions.iter().map(|a| a.assertions.len()).sum(),
                backends: vec!["default".to_string()],
                rpc_mode: plan.summary.rpc_mode_name.clone(),
                has_streaming,
                has_bidi_streaming,
            },
        }
    }

    /// Add execution events from ExecutionPlan
    fn add_execution_events_from_plan(
        events: &mut Vec<WorkflowEvent>,
        plan: &crate::execution::ExecutionPlan,
    ) {
        let backend = "default".to_string();

        // Connect to backend
        events.push(WorkflowEvent::Connect {
            backend: backend.clone(),
            address: plan.connection.address.clone(),
        });
        events.push(WorkflowEvent::Connected {
            backend: backend.clone(),
            address: plan.connection.address.clone(),
        });

        // Load descriptors
        events.push(WorkflowEvent::LoadDescriptors {
            backend: backend.clone(),
            service: plan.target.endpoint.clone(),
        });
        events.push(WorkflowEvent::DescriptorsLoaded {
            backend: backend.clone(),
            service: plan.target.endpoint.clone(),
            method_count: 1,
        });

        // Requests
        for request in &plan.requests {
            events.push(WorkflowEvent::SendRequest {
                backend: backend.clone(),
                request_index: request.index,
                content_type: request.content_type.clone(),
                line_range: (request.line_start, request.line_end),
            });
            events.push(WorkflowEvent::RequestSent {
                backend: backend.clone(),
                request_index: request.index,
            });
        }

        // Expectations (responses or error)
        for expectation in &plan.expectations {
            events.push(WorkflowEvent::ReceiveResponse {
                backend: backend.clone(),
                response_index: expectation.index,
                expectation_type: expectation.expectation_type.clone(),
            });

            if expectation.expectation_type == "error"
                && let Some(content) = &expectation.content
            {
                let code = content.get("code").and_then(|c| c.as_i64()).unwrap_or(0) as i32;
                let message = content
                    .get("message")
                    .and_then(|m| m.as_str())
                    .unwrap_or("Unknown error")
                    .to_string();
                events.push(WorkflowEvent::Error { code, message });
            }

            events.push(WorkflowEvent::ResponseReceived {
                backend: backend.clone(),
                response_index: expectation.index,
                has_content: expectation.content.is_some(),
                options: ResponseOptions::from(&expectation.comparison_options),
            });
        }

        // Extractions
        for extraction in &plan.extractions {
            events.push(WorkflowEvent::Extract {
                variables: extraction.variables.keys().cloned().collect(),
                source_response_index: None,
                line_range: (extraction.line_start, extraction.line_end),
            });
            events.push(WorkflowEvent::Extracted {
                variables: extraction.variables.keys().cloned().collect(),
            });
        }

        // Assertions
        for assertion in &plan.assertions {
            events.push(WorkflowEvent::Assert {
                count: assertion.assertions.len(),
                target_response_index: None,
                line_range: (assertion.line_start, assertion.line_end),
            });
            events.push(WorkflowEvent::Asserted {
                passed: assertion.assertions.len(),
                failed: 0,
            });
        }

        // Complete
        events.push(WorkflowEvent::Complete {
            total_requests: plan.requests.len(),
            total_responses: plan.expectations.len(),
            total_extractions: plan.extractions.len(),
            total_assertions: plan.assertions.iter().map(|a| a.assertions.len()).sum(),
            backends_used: vec![backend],
        });
    }
}

/// Streaming pattern analysis
#[derive(Debug, Clone)]
pub enum StreamingPattern {
    Unary,
    ServerStreaming {
        response_count: usize,
        max_consecutive_responses: usize,
    },
    ClientStreaming {
        request_count: usize,
        max_consecutive_requests: usize,
    },
    Bidirectional {
        request_count: usize,
        response_count: usize,
        max_consecutive_requests: usize,
        max_consecutive_responses: usize,
    },
}

/// Validation result
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub passed: bool,
    pub errors: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::{
        ConnectionInfo, ExecutionPlan, ExecutionSummary, ExpectationInfo, RequestInfo, TargetInfo,
    };
    use serde_json::json;

    fn create_test_plan() -> ExecutionPlan {
        ExecutionPlan {
            file_path: "test.gctf".to_string(),
            connection: ConnectionInfo {
                address: "localhost:50051".to_string(),
                source: "test".to_string(),
            },
            target: TargetInfo {
                endpoint: "test.Service/Method".to_string(),
                package: Some("test".to_string()),
                service: Some("Service".to_string()),
                method: Some("Method".to_string()),
            },
            headers: None,
            requests: vec![RequestInfo {
                index: 1,
                content: json!({"key": "value"}),
                content_type: "json".to_string(),
                line_start: 5,
                line_end: 8,
            }],
            expectations: vec![ExpectationInfo {
                index: 1,
                expectation_type: "response".to_string(),
                content: Some(json!({"result": "ok"})),
                message_count: None,
                comparison_options: Default::default(),
                line_start: 10,
                line_end: 13,
            }],
            assertions: vec![],
            extractions: vec![],
            rpc_mode: crate::execution::RpcMode::Unary,
            summary: ExecutionSummary {
                rpc_mode_name: "Unary".to_string(),
                ..Default::default()
            },
        }
    }

    #[test]
    fn test_workflow_from_plan() {
        let plan = create_test_plan();
        let workflow = Workflow::from_plan(&plan);

        assert_eq!(workflow.file_path, "test.gctf");
        assert_eq!(workflow.summary.rpc_mode, "Unary");
        assert!(workflow.events.len() >= 10);
    }

    #[test]
    fn test_workflow_validate() {
        let plan = create_test_plan();
        let workflow = Workflow::from_plan(&plan);
        let result = workflow.validate();

        assert!(result.passed, "Validation failed: {:?}", result.errors);
    }

    #[test]
    fn test_workflow_events_by_type() {
        let plan = create_test_plan();
        let workflow = Workflow::from_plan(&plan);

        let requests = workflow.requests();
        assert_eq!(requests.len(), 1);

        let responses = workflow.responses();
        assert_eq!(responses.len(), 1);
    }

    #[test]
    fn test_workflow_streaming_analysis_unary() {
        let plan = create_test_plan();
        let workflow = Workflow::from_plan(&plan);
        let pattern = workflow.analyze_streaming();

        assert!(matches!(pattern, StreamingPattern::Unary));
    }

    #[test]
    fn test_workflow_streaming_analysis_server() {
        let mut plan = create_test_plan();
        plan.expectations.push(ExpectationInfo {
            index: 2,
            expectation_type: "response".to_string(),
            content: Some(json!({"result": "ok2"})),
            message_count: None,
            comparison_options: Default::default(),
            line_start: 15,
            line_end: 18,
        });

        let workflow = Workflow::from_plan(&plan);
        let pattern = workflow.analyze_streaming();

        assert!(matches!(pattern, StreamingPattern::ServerStreaming { .. }));
    }
}