mockforge-grpc 0.3.117

gRPC protocol support for MockForge
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
//! Proto file parsing and service discovery
//!
//! This module handles parsing of .proto files and extracting service definitions
//! to generate dynamic gRPC service implementations.

use prost_reflect::DescriptorPool;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;
use tracing::{debug, error, info, warn};

/// A parsed proto service definition
#[derive(Debug, Clone)]
pub struct ProtoService {
    /// The service name (e.g., "mockforge.greeter.Greeter")
    pub name: String,
    /// The package name (e.g., "mockforge.greeter")
    pub package: String,
    /// The short service name (e.g., "Greeter")
    pub short_name: String,
    /// List of methods in this service
    pub methods: Vec<ProtoMethod>,
}

/// A parsed proto method definition
#[derive(Debug, Clone)]
pub struct ProtoMethod {
    /// The method name (e.g., "SayHello")
    pub name: String,
    /// The input message type
    pub input_type: String,
    /// The output message type
    pub output_type: String,
    /// Whether this is a client streaming method
    pub client_streaming: bool,
    /// Whether this is a server streaming method
    pub server_streaming: bool,
}

/// A proto file parser that can extract service definitions
pub struct ProtoParser {
    /// The descriptor pool containing parsed proto files
    pool: DescriptorPool,
    /// Map of service names to their definitions
    services: HashMap<String, ProtoService>,
    /// Include paths for proto compilation
    include_paths: Vec<PathBuf>,
    /// Temporary directory for compilation artifacts
    temp_dir: Option<TempDir>,
}

impl ProtoParser {
    /// Create a new proto parser
    pub fn new() -> Self {
        Self {
            pool: DescriptorPool::new(),
            services: HashMap::new(),
            include_paths: vec![],
            temp_dir: None,
        }
    }

    /// Create a new proto parser with include paths
    pub fn with_include_paths(include_paths: Vec<PathBuf>) -> Self {
        Self {
            pool: DescriptorPool::new(),
            services: HashMap::new(),
            include_paths,
            temp_dir: None,
        }
    }

    /// Parse proto files from a directory
    ///
    /// If the directory doesn't exist, this function will gracefully return Ok
    /// with an empty service registry, allowing the gRPC server to start
    /// even when only OpenAPI/HTTP is being used.
    pub async fn parse_directory(
        &mut self,
        proto_dir: &str,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        info!("Parsing proto files from directory: {}", proto_dir);

        let proto_path = Path::new(proto_dir);
        if !proto_path.exists() {
            info!(
                "No proto directory found at {}. gRPC server will start with built-in services only.",
                proto_dir
            );
            return Ok(());
        }

        // Discover all proto files
        let proto_files = self.discover_proto_files(proto_path)?;
        if proto_files.is_empty() {
            warn!("No proto files found in directory: {}", proto_dir);
            return Ok(());
        }

        info!("Found {} proto files: {:?}", proto_files.len(), proto_files);

        // Optimize: Batch compile all proto files in a single protoc invocation
        if proto_files.len() > 1 {
            if let Err(e) = self.compile_protos_batch(&proto_files).await {
                warn!("Batch compilation failed, falling back to individual compilation: {}", e);
                // Fall back to individual compilation
                for proto_file in proto_files {
                    if let Err(e) = self.parse_proto_file(&proto_file).await {
                        error!("Failed to parse proto file {}: {}", proto_file, e);
                        // Continue with other files
                    }
                }
            }
        } else if !proto_files.is_empty() {
            // Single file - use existing method
            if let Err(e) = self.parse_proto_file(&proto_files[0]).await {
                error!("Failed to parse proto file {}: {}", proto_files[0], e);
            }
        }

        // Extract services from the descriptor pool only if there are any services in the pool
        if self.pool.services().count() > 0 {
            self.extract_services()?;
        } else {
            debug!("No services found in descriptor pool, keeping mock services");
        }

        info!("Successfully parsed {} services", self.services.len());
        Ok(())
    }

    /// Discover proto files in a directory recursively
    #[allow(clippy::only_used_in_recursion)]
    fn discover_proto_files(
        &self,
        dir: &Path,
    ) -> Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> {
        let mut proto_files = Vec::new();

        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();

                if path.is_dir() {
                    // Recursively search subdirectories
                    proto_files.extend(self.discover_proto_files(&path)?);
                } else if path.extension().and_then(|s| s.to_str()) == Some("proto") {
                    // Found a .proto file
                    proto_files.push(path.to_string_lossy().to_string());
                }
            }
        }

        Ok(proto_files)
    }

    /// Parse a single proto file using protoc compilation
    async fn parse_proto_file(
        &mut self,
        proto_file: &str,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        debug!("Parsing proto file: {}", proto_file);

        // Create temporary directory for compilation artifacts if not exists
        if self.temp_dir.is_none() {
            self.temp_dir = Some(TempDir::new()?);
        }

        // Safe to unwrap here: we just created it above if it was None
        let temp_dir = self.temp_dir.as_ref().ok_or_else(|| {
            Box::<dyn std::error::Error + Send + Sync>::from("Temp directory not initialized")
        })?;
        let descriptor_path = temp_dir.path().join("descriptors.bin");

        // Try real protoc compilation first
        match self.compile_with_protoc(proto_file, &descriptor_path).await {
            Ok(()) => {
                // Load the compiled descriptor set into the pool
                let descriptor_bytes = fs::read(&descriptor_path)?;
                match self.pool.decode_file_descriptor_set(&*descriptor_bytes) {
                    Ok(()) => {
                        info!("Successfully compiled and loaded proto file: {}", proto_file);
                        // Extract services from the descriptor pool if successful
                        if self.pool.services().count() > 0 {
                            self.extract_services()?;
                        }
                        return Ok(());
                    }
                    Err(e) => {
                        warn!("Failed to decode descriptor set, falling back to mock: {}", e);
                    }
                }
            }
            Err(e) => {
                // This is expected behavior if protoc is not installed or proto files don't require compilation
                // MockForge will use fallback mock services, which is fine for basic usage
                warn!(
                    "protoc not available or compilation failed (this is OK for basic usage, using fallback): {}",
                    e
                );
            }
        }

        // Fallback to mock service for testing
        if proto_file.contains("gretter.proto") || proto_file.contains("greeter.proto") {
            debug!("Adding mock greeter service for {}", proto_file);
            self.add_mock_greeter_service();
        }

        Ok(())
    }

    /// Batch compile multiple proto files in a single protoc invocation
    /// This is significantly faster than compiling files individually
    async fn compile_protos_batch(
        &mut self,
        proto_files: &[String],
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if proto_files.is_empty() {
            return Ok(());
        }

        info!("Batch compiling {} proto files", proto_files.len());

        // Create temporary directory for compilation artifacts if not exists
        if self.temp_dir.is_none() {
            self.temp_dir = Some(TempDir::new()?);
        }

        let temp_dir = self.temp_dir.as_ref().ok_or_else(|| {
            Box::<dyn std::error::Error + Send + Sync>::from("Temp directory not initialized")
        })?;
        let descriptor_path = temp_dir.path().join("descriptors_batch.bin");

        // Build protoc command
        let mut cmd = Command::new("protoc");

        // Collect unique parent directories for include paths
        let mut parent_dirs = std::collections::HashSet::new();
        for proto_file in proto_files {
            if let Some(parent_dir) = Path::new(proto_file).parent() {
                parent_dirs.insert(parent_dir.to_path_buf());
            }
        }

        // Add include paths
        for include_path in &self.include_paths {
            cmd.arg("-I").arg(include_path);
        }

        // Add proto file parent directories as include paths
        for parent_dir in &parent_dirs {
            cmd.arg("-I").arg(parent_dir);
        }

        // Add well-known types include path (common protoc installation paths)
        let well_known_paths = [
            "/usr/local/include",
            "/usr/include",
            "/opt/homebrew/include",
        ];

        for path in &well_known_paths {
            if Path::new(path).exists() {
                cmd.arg("-I").arg(path);
            }
        }

        // Set output path and format
        cmd.arg("--descriptor_set_out")
            .arg(&descriptor_path)
            .arg("--include_imports")
            .arg("--include_source_info");

        // Add all proto files to compile
        for proto_file in proto_files {
            cmd.arg(proto_file);
        }

        debug!("Running batch protoc command for {} files", proto_files.len());

        // Execute protoc
        let output = cmd.output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(format!("Batch protoc compilation failed: {}", stderr).into());
        }

        // Load the compiled descriptor set into the pool
        let descriptor_bytes = fs::read(&descriptor_path)?;
        match self.pool.decode_file_descriptor_set(&*descriptor_bytes) {
            Ok(()) => {
                info!("Successfully batch compiled and loaded {} proto files", proto_files.len());
                // Extract services from the descriptor pool if successful
                if self.pool.services().count() > 0 {
                    self.extract_services()?;
                }
                Ok(())
            }
            Err(e) => Err(format!("Failed to decode batch descriptor set: {}", e).into()),
        }
    }

    /// Compile proto file using protoc
    async fn compile_with_protoc(
        &self,
        proto_file: &str,
        output_path: &Path,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        debug!("Compiling proto file with protoc: {}", proto_file);

        // Build protoc command
        let mut cmd = Command::new("protoc");

        // Add include paths
        for include_path in &self.include_paths {
            cmd.arg("-I").arg(include_path);
        }

        // Add proto file's directory as include path
        if let Some(parent_dir) = Path::new(proto_file).parent() {
            cmd.arg("-I").arg(parent_dir);
        }

        // Add well-known types include path (common protoc installation paths)
        let well_known_paths = [
            "/usr/local/include",
            "/usr/include",
            "/opt/homebrew/include",
        ];

        for path in &well_known_paths {
            if Path::new(path).exists() {
                cmd.arg("-I").arg(path);
            }
        }

        // Set output path and format
        cmd.arg("--descriptor_set_out")
            .arg(output_path)
            .arg("--include_imports")
            .arg("--include_source_info")
            .arg(proto_file);

        debug!("Running protoc command: {:?}", cmd);

        // Execute protoc
        let output = cmd.output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(format!("protoc failed: {}", stderr).into());
        }

        info!("Successfully compiled proto file with protoc: {}", proto_file);
        Ok(())
    }

    /// Add a mock greeter service (for demonstration)
    fn add_mock_greeter_service(&mut self) {
        let service = ProtoService {
            name: "mockforge.greeter.Greeter".to_string(),
            package: "mockforge.greeter".to_string(),
            short_name: "Greeter".to_string(),
            methods: vec![
                ProtoMethod {
                    name: "SayHello".to_string(),
                    input_type: "mockforge.greeter.HelloRequest".to_string(),
                    output_type: "mockforge.greeter.HelloReply".to_string(),
                    client_streaming: false,
                    server_streaming: false,
                },
                ProtoMethod {
                    name: "SayHelloStream".to_string(),
                    input_type: "mockforge.greeter.HelloRequest".to_string(),
                    output_type: "mockforge.greeter.HelloReply".to_string(),
                    client_streaming: false,
                    server_streaming: true,
                },
                ProtoMethod {
                    name: "SayHelloClientStream".to_string(),
                    input_type: "mockforge.greeter.HelloRequest".to_string(),
                    output_type: "mockforge.greeter.HelloReply".to_string(),
                    client_streaming: true,
                    server_streaming: false,
                },
                ProtoMethod {
                    name: "Chat".to_string(),
                    input_type: "mockforge.greeter.HelloRequest".to_string(),
                    output_type: "mockforge.greeter.HelloReply".to_string(),
                    client_streaming: true,
                    server_streaming: true,
                },
            ],
        };

        self.services.insert(service.name.clone(), service);
    }

    /// Extract services from the descriptor pool
    fn extract_services(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        debug!("Extracting services from descriptor pool");

        // Clear existing services (except mock ones)
        let mock_services: HashMap<String, ProtoService> = self
            .services
            .drain()
            .filter(|(name, _)| name.contains("mockforge.greeter"))
            .collect();

        self.services = mock_services;

        // Extract services from the descriptor pool
        for service_descriptor in self.pool.services() {
            let service_name = service_descriptor.full_name().to_string();
            let package_name = service_descriptor.parent_file().package_name().to_string();
            let short_name = service_descriptor.name().to_string();

            debug!("Found service: {} in package: {}", service_name, package_name);

            // Extract methods for this service
            let mut methods = Vec::new();
            for method_descriptor in service_descriptor.methods() {
                let method = ProtoMethod {
                    name: method_descriptor.name().to_string(),
                    input_type: method_descriptor.input().full_name().to_string(),
                    output_type: method_descriptor.output().full_name().to_string(),
                    client_streaming: method_descriptor.is_client_streaming(),
                    server_streaming: method_descriptor.is_server_streaming(),
                };

                debug!(
                    "  Found method: {} ({} -> {})",
                    method.name, method.input_type, method.output_type
                );

                methods.push(method);
            }

            let service = ProtoService {
                name: service_name.clone(),
                package: package_name,
                short_name,
                methods,
            };

            self.services.insert(service_name, service);
        }

        info!("Extracted {} services from descriptor pool", self.services.len());
        Ok(())
    }

    /// Get all discovered services
    pub fn services(&self) -> &HashMap<String, ProtoService> {
        &self.services
    }

    /// Get a specific service by name
    pub fn get_service(&self, name: &str) -> Option<&ProtoService> {
        self.services.get(name)
    }

    /// Get the descriptor pool
    pub fn pool(&self) -> &DescriptorPool {
        &self.pool
    }

    /// Consume the parser and return the descriptor pool
    pub fn into_pool(self) -> DescriptorPool {
        self.pool
    }
}

impl Default for ProtoParser {
    fn default() -> Self {
        Self::new()
    }
}

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

    // ==================== ProtoService Tests ====================

    #[test]
    fn test_proto_service_creation() {
        let service = ProtoService {
            name: "mypackage.MyService".to_string(),
            package: "mypackage".to_string(),
            short_name: "MyService".to_string(),
            methods: vec![],
        };

        assert_eq!(service.name, "mypackage.MyService");
        assert_eq!(service.package, "mypackage");
        assert_eq!(service.short_name, "MyService");
        assert!(service.methods.is_empty());
    }

    #[test]
    fn test_proto_service_with_methods() {
        let method = ProtoMethod {
            name: "GetData".to_string(),
            input_type: "mypackage.Request".to_string(),
            output_type: "mypackage.Response".to_string(),
            client_streaming: false,
            server_streaming: false,
        };

        let service = ProtoService {
            name: "mypackage.DataService".to_string(),
            package: "mypackage".to_string(),
            short_name: "DataService".to_string(),
            methods: vec![method],
        };

        assert_eq!(service.methods.len(), 1);
        assert_eq!(service.methods[0].name, "GetData");
    }

    #[test]
    fn test_proto_service_clone() {
        let service = ProtoService {
            name: "test.Service".to_string(),
            package: "test".to_string(),
            short_name: "Service".to_string(),
            methods: vec![ProtoMethod {
                name: "Method".to_string(),
                input_type: "Request".to_string(),
                output_type: "Response".to_string(),
                client_streaming: false,
                server_streaming: false,
            }],
        };

        let cloned = service.clone();
        assert_eq!(cloned.name, service.name);
        assert_eq!(cloned.methods.len(), service.methods.len());
    }

    // ==================== ProtoMethod Tests ====================

    #[test]
    fn test_proto_method_unary() {
        let method = ProtoMethod {
            name: "UnaryMethod".to_string(),
            input_type: "Request".to_string(),
            output_type: "Response".to_string(),
            client_streaming: false,
            server_streaming: false,
        };

        assert_eq!(method.name, "UnaryMethod");
        assert!(!method.client_streaming);
        assert!(!method.server_streaming);
    }

    #[test]
    fn test_proto_method_server_streaming() {
        let method = ProtoMethod {
            name: "StreamMethod".to_string(),
            input_type: "Request".to_string(),
            output_type: "Response".to_string(),
            client_streaming: false,
            server_streaming: true,
        };

        assert!(!method.client_streaming);
        assert!(method.server_streaming);
    }

    #[test]
    fn test_proto_method_client_streaming() {
        let method = ProtoMethod {
            name: "ClientStreamMethod".to_string(),
            input_type: "Request".to_string(),
            output_type: "Response".to_string(),
            client_streaming: true,
            server_streaming: false,
        };

        assert!(method.client_streaming);
        assert!(!method.server_streaming);
    }

    #[test]
    fn test_proto_method_bidi_streaming() {
        let method = ProtoMethod {
            name: "BidiStreamMethod".to_string(),
            input_type: "Request".to_string(),
            output_type: "Response".to_string(),
            client_streaming: true,
            server_streaming: true,
        };

        assert!(method.client_streaming);
        assert!(method.server_streaming);
    }

    #[test]
    fn test_proto_method_clone() {
        let method = ProtoMethod {
            name: "TestMethod".to_string(),
            input_type: "Input".to_string(),
            output_type: "Output".to_string(),
            client_streaming: true,
            server_streaming: true,
        };

        let cloned = method.clone();
        assert_eq!(cloned.name, method.name);
        assert_eq!(cloned.input_type, method.input_type);
        assert_eq!(cloned.output_type, method.output_type);
        assert_eq!(cloned.client_streaming, method.client_streaming);
        assert_eq!(cloned.server_streaming, method.server_streaming);
    }

    // ==================== ProtoParser Tests ====================

    #[test]
    fn test_proto_parser_new() {
        let parser = ProtoParser::new();
        assert!(parser.services().is_empty());
    }

    #[test]
    fn test_proto_parser_default() {
        let parser = ProtoParser::default();
        assert!(parser.services().is_empty());
    }

    #[test]
    fn test_proto_parser_with_include_paths() {
        let paths = vec![PathBuf::from("/usr/include"), PathBuf::from("/opt/proto")];
        let parser = ProtoParser::with_include_paths(paths);
        assert!(parser.services().is_empty());
    }

    #[test]
    fn test_proto_parser_get_service_nonexistent() {
        let parser = ProtoParser::new();
        assert!(parser.get_service("nonexistent").is_none());
    }

    #[test]
    fn test_proto_parser_pool() {
        let parser = ProtoParser::new();
        let _pool = parser.pool();
        // Pool should be accessible
    }

    #[test]
    fn test_proto_parser_into_pool() {
        let parser = ProtoParser::new();
        let _pool = parser.into_pool();
        // Should consume the parser and return the pool
    }

    #[test]
    fn test_proto_parser_add_mock_greeter_service() {
        let mut parser = ProtoParser::new();
        parser.add_mock_greeter_service();

        let services = parser.services();
        assert_eq!(services.len(), 1);
        assert!(services.contains_key("mockforge.greeter.Greeter"));

        let service = &services["mockforge.greeter.Greeter"];
        assert_eq!(service.short_name, "Greeter");
        assert_eq!(service.package, "mockforge.greeter");
        assert_eq!(service.methods.len(), 4);
    }

    #[test]
    fn test_proto_parser_discover_empty_dir() {
        let temp_dir = TempDir::new().unwrap();
        let parser = ProtoParser::new();

        let result = parser.discover_proto_files(temp_dir.path()).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_proto_parser_discover_with_proto_files() {
        let temp_dir = TempDir::new().unwrap();

        // Create a fake proto file
        let proto_path = temp_dir.path().join("test.proto");
        fs::write(&proto_path, "syntax = \"proto3\";").unwrap();

        let parser = ProtoParser::new();
        let result = parser.discover_proto_files(temp_dir.path()).unwrap();

        assert_eq!(result.len(), 1);
        assert!(result[0].ends_with("test.proto"));
    }

    #[test]
    fn test_proto_parser_discover_recursive() {
        let temp_dir = TempDir::new().unwrap();

        // Create subdirectory with proto files
        let sub_dir = temp_dir.path().join("subdir");
        fs::create_dir(&sub_dir).unwrap();
        fs::write(temp_dir.path().join("root.proto"), "").unwrap();
        fs::write(sub_dir.join("nested.proto"), "").unwrap();

        let parser = ProtoParser::new();
        let result = parser.discover_proto_files(temp_dir.path()).unwrap();

        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_proto_parser_discover_ignores_non_proto() {
        let temp_dir = TempDir::new().unwrap();

        // Create various files
        fs::write(temp_dir.path().join("test.proto"), "").unwrap();
        fs::write(temp_dir.path().join("test.txt"), "").unwrap();
        fs::write(temp_dir.path().join("test.json"), "").unwrap();

        let parser = ProtoParser::new();
        let result = parser.discover_proto_files(temp_dir.path()).unwrap();

        assert_eq!(result.len(), 1);
        assert!(result[0].ends_with(".proto"));
    }

    // ==================== Async Tests ====================

    #[tokio::test]
    async fn test_parse_nonexistent_directory() {
        let mut parser = ProtoParser::new();
        let result = parser.parse_directory("/nonexistent/path").await;

        // Should succeed gracefully with empty services
        assert!(result.is_ok());
        assert!(parser.services().is_empty());
    }

    #[tokio::test]
    async fn test_parse_empty_directory() {
        let temp_dir = TempDir::new().unwrap();
        let mut parser = ProtoParser::new();

        let result = parser.parse_directory(temp_dir.path().to_str().unwrap()).await;

        // Should succeed gracefully with empty services
        assert!(result.is_ok());
        assert!(parser.services().is_empty());
    }

    #[tokio::test]
    async fn test_parse_proto_file() {
        // Test with the existing greeter.proto file
        let proto_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap() + "/proto";
        let proto_path = format!("{}/gretter.proto", proto_dir);

        // Parse the proto file
        let mut parser = ProtoParser::new();
        parser.parse_proto_file(&proto_path).await.unwrap();

        // Verify the service was parsed correctly
        let services = parser.services();
        assert_eq!(services.len(), 1);

        let service_name = "mockforge.greeter.Greeter";
        assert!(services.contains_key(service_name));

        let service = &services[service_name];
        assert_eq!(service.name, service_name);
        assert_eq!(service.methods.len(), 4); // SayHello, SayHelloStream, SayHelloClientStream, Chat

        // Check SayHello method (unary)
        let say_hello = service.methods.iter().find(|m| m.name == "SayHello").unwrap();
        assert_eq!(say_hello.input_type, "mockforge.greeter.HelloRequest");
        assert_eq!(say_hello.output_type, "mockforge.greeter.HelloReply");
        assert!(!say_hello.client_streaming);
        assert!(!say_hello.server_streaming);

        // Check SayHelloStream method (server streaming)
        let say_hello_stream = service.methods.iter().find(|m| m.name == "SayHelloStream").unwrap();
        assert!(!say_hello_stream.client_streaming);
        assert!(say_hello_stream.server_streaming);
    }

    #[tokio::test]
    async fn test_parse_directory() {
        // Test with the existing proto directory
        let proto_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap() + "/proto";

        // Parse the directory
        let mut parser = ProtoParser::new();
        parser.parse_directory(&proto_dir).await.unwrap();

        // Verify services were discovered
        let services = parser.services();
        assert_eq!(services.len(), 1);

        let service_name = "mockforge.greeter.Greeter";
        assert!(services.contains_key(service_name));

        let service = &services[service_name];
        assert_eq!(service.methods.len(), 4);

        // Check all methods exist
        let method_names: Vec<&str> = service.methods.iter().map(|m| m.name.as_str()).collect();
        assert!(method_names.contains(&"SayHello"));
        assert!(method_names.contains(&"SayHelloStream"));
        assert!(method_names.contains(&"SayHelloClientStream"));
        assert!(method_names.contains(&"Chat"));
    }
}