grpctestify 1.6.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
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
// Error handling for test execution

use prost::Message;
use prost_types::Any;
use serde_json::{Map, Value, json};

#[derive(Clone, PartialEq, Message)]
struct GoogleRpcStatus {
    #[prost(int32, tag = "1")]
    code: i32,
    #[prost(string, tag = "2")]
    message: String,
    #[prost(message, repeated, tag = "3")]
    details: Vec<Any>,
}

#[derive(Clone, PartialEq, Message)]
struct GoogleRpcErrorInfo {
    #[prost(string, tag = "1")]
    reason: String,
    #[prost(string, tag = "2")]
    domain: String,
    #[prost(map = "string, string", tag = "3")]
    metadata: std::collections::HashMap<String, String>,
}

#[derive(Clone, PartialEq, Message)]
struct GoogleRpcBadRequest {
    #[prost(message, repeated, tag = "1")]
    field_violations: Vec<GoogleRpcBadRequestFieldViolation>,
}

#[derive(Clone, PartialEq, Message)]
struct GoogleRpcBadRequestFieldViolation {
    #[prost(string, tag = "1")]
    field: String,
    #[prost(string, tag = "2")]
    description: String,
}

/// Error handler for gRPC test execution
pub struct ErrorHandler;

impl ErrorHandler {
    /// Check if error matches expected error
    pub fn error_matches_expected(error_text: &str, expected: &Value) -> bool {
        Self::message_matches_error_text(error_text, expected)
            && Self::code_matches_error_text(error_text, expected)
            && expected.get("details").is_none()
    }

    /// Check if tonic::Status matches expected error JSON (supports details)
    pub fn status_matches_expected(status: &tonic::Status, expected: &Value) -> bool {
        Self::status_matches_expected_with_options(status, expected, false)
    }

    /// Check if tonic::Status matches expected error JSON, optionally as partial subset.
    pub fn status_matches_expected_with_options(
        status: &tonic::Status,
        expected: &Value,
        partial: bool,
    ) -> bool {
        if !partial && !Self::status_has_no_unexpected_top_level_fields(status, expected) {
            return false;
        }

        if partial {
            let actual = Self::status_to_json(status);
            return Self::is_subset_match(&actual, expected);
        }

        if !Self::message_matches_status(status, expected)
            || !Self::code_matches_status(status, expected)
        {
            return false;
        }

        let expects_details = expected.get("details").is_some();
        if !expects_details {
            return status.details().is_empty();
        }

        let Some(actual_details) = Self::decode_status_details(status.details()) else {
            return false;
        };

        Self::compare_details(expected, actual_details).is_none()
    }

    /// Convert tonic::Status details to JSON array
    pub fn status_details_json(status: &tonic::Status) -> Value {
        match Self::decode_status_details(status.details()) {
            Some(details) => Value::Array(details),
            None => Value::Null,
        }
    }

    /// Convert tonic::Status to JSON object for diff output
    pub fn status_to_json(status: &tonic::Status) -> Value {
        let mut obj = Map::with_capacity(3);
        obj.insert("code".into(), Value::from(status.code() as i64));
        obj.insert("message".into(), Value::from(status.message()));

        if let Some(details) = Self::decode_status_details(status.details())
            && !details.is_empty()
        {
            obj.insert("details".into(), Value::Array(details));
        }

        Value::Object(obj)
    }

    /// Returns a human-readable mismatch reason for tonic::Status comparison
    pub fn status_mismatch_reason(status: &tonic::Status, expected: &Value) -> Option<String> {
        Self::status_mismatch_reason_with_options(status, expected, false)
    }

    /// Returns mismatch reason for tonic::Status comparison with optional partial mode.
    pub fn status_mismatch_reason_with_options(
        status: &tonic::Status,
        expected: &Value,
        partial: bool,
    ) -> Option<String> {
        if !partial
            && let Some(reason) = Self::status_unexpected_top_level_field_reason(status, expected)
        {
            return Some(reason);
        }

        if partial {
            let actual = Self::status_to_json(status);
            return Self::subset_mismatch_reason(&actual, expected, "$");
        }

        if !Self::message_matches_status(status, expected) {
            let actual = status.message();
            if let Some(expected_msg) = expected.get("message").and_then(|v| v.as_str()) {
                return Some(format!(
                    "message mismatch: expected '{}', got '{}'",
                    expected_msg, actual
                ));
            }
            if expected.is_string()
                && let Some(s) = expected.as_str()
            {
                return Some(format!(
                    "message mismatch: expected '{}', got '{}'",
                    s, actual
                ));
            }
            return Some("message mismatch".to_string());
        }

        if !Self::code_matches_status(status, expected) {
            if let Some(code) = expected.get("code").and_then(|v| v.as_i64()) {
                let expected_name = Self::grpc_code_name_from_numeric(code).unwrap_or("Unknown");
                return Some(format!(
                    "code mismatch: expected {} ({}), got {} ({:?})",
                    code,
                    expected_name,
                    status.code() as i64,
                    status.code()
                ));
            }
            return Some("code mismatch".to_string());
        }

        let actual_details = match Self::decode_status_details(status.details()) {
            Some(details) => details,
            None => return Some("cannot decode gRPC status details".to_string()),
        };

        Self::compare_details(expected, actual_details)
    }

    fn is_subset_match(actual: &Value, expected: &Value) -> bool {
        Self::subset_mismatch_reason(actual, expected, "$").is_none()
    }

    fn status_has_no_unexpected_top_level_fields(status: &tonic::Status, expected: &Value) -> bool {
        Self::status_unexpected_top_level_field_reason(status, expected).is_none()
    }

    fn status_unexpected_top_level_field_reason(
        status: &tonic::Status,
        expected: &Value,
    ) -> Option<String> {
        let Value::Object(expected_obj) = expected else {
            return None;
        };
        let Value::Object(actual_obj) = Self::status_to_json(status) else {
            return None;
        };

        for key in actual_obj.keys() {
            if key == "details" && !expected_obj.contains_key("details") {
                return Some(format!(
                    "backend returned details, but ERROR.details is missing in gctf; actual details: {}",
                    Self::status_details_json(status)
                ));
            }
            if !expected_obj.contains_key(key) {
                return Some(format!(
                    "unexpected field in actual error: '{}' is present but missing in ERROR section (use partial=true or ASSERTS)",
                    key
                ));
            }
        }

        None
    }

    fn subset_mismatch_reason(actual: &Value, expected: &Value, path: &str) -> Option<String> {
        match (actual, expected) {
            (Value::Object(act_map), Value::Object(exp_map)) => {
                for (k, exp_val) in exp_map {
                    let key_path = format!("{}.{}", path, k);
                    let Some(act_val) = act_map.get(k) else {
                        return Some(format!("partial mismatch: missing key '{}'", key_path));
                    };
                    if let Some(reason) = Self::subset_mismatch_reason(act_val, exp_val, &key_path)
                    {
                        return Some(reason);
                    }
                }
                None
            }
            (Value::Array(act_arr), Value::Array(exp_arr)) => {
                let mut used_actual = vec![false; act_arr.len()];
                for (exp_idx, exp_item) in exp_arr.iter().enumerate() {
                    let mut matched = false;
                    for (act_idx, act_item) in act_arr.iter().enumerate() {
                        if used_actual[act_idx] {
                            continue;
                        }
                        if Self::subset_mismatch_reason(act_item, exp_item, path).is_none() {
                            used_actual[act_idx] = true;
                            matched = true;
                            break;
                        }
                    }

                    if !matched {
                        return Some(format!(
                            "partial mismatch: expected array item at '{}[{}]' not found",
                            path, exp_idx
                        ));
                    }
                }
                None
            }
            _ => {
                if actual == expected {
                    None
                } else {
                    Some(format!(
                        "partial mismatch at '{}': expected {}, got {}",
                        path, expected, actual
                    ))
                }
            }
        }
    }

    fn message_matches_error_text(error_text: &str, expected: &Value) -> bool {
        // Check message
        if let Some(expected_msg) = expected.get("message").and_then(|v| v.as_str()) {
            if !error_text.contains(expected_msg) {
                return false;
            }
        } else if expected.is_string()
            && let Some(s) = expected.as_str()
            && !error_text.contains(s)
        {
            return false;
        }

        true
    }

    fn message_matches_status(status: &tonic::Status, expected: &Value) -> bool {
        if let Some(expected_msg) = expected.get("message").and_then(|v| v.as_str()) {
            return status.message() == expected_msg;
        }

        if expected.is_string()
            && let Some(s) = expected.as_str()
        {
            return status.message() == s;
        }

        true
    }

    fn code_matches_error_text(error_text: &str, expected: &Value) -> bool {
        // Check code
        if let Some(code) = expected.get("code").and_then(|v| v.as_i64())
            && let Some(code_name) = Self::grpc_code_name_from_numeric(code)
        {
            let status_marker = format!("status: {}", code_name);
            if !error_text.contains(&status_marker)
                && !error_text.contains(&format!("code: {}", code))
            {
                return false;
            }
        }

        true
    }

    fn code_matches_status(status: &tonic::Status, expected: &Value) -> bool {
        if let Some(code) = expected.get("code").and_then(|v| v.as_i64()) {
            return status.code() as i64 == code;
        }
        true
    }

    fn compare_details(expected: &Value, actual_details: Vec<Value>) -> Option<String> {
        if let Some(expected_details) = expected.get("details") {
            let expected_array = match expected_details.as_array() {
                Some(array) => array,
                None => return Some("expected ERROR.details must be an array".to_string()),
            };

            if expected_array.len() != actual_details.len() {
                return Some(format!(
                    "details mismatch: expected {} item(s), got {}",
                    expected_array.len(),
                    actual_details.len()
                ));
            }

            for (idx, (exp, act)) in expected_array.iter().zip(actual_details.iter()).enumerate() {
                if exp != act {
                    return Some(format!(
                        "details mismatch at index {}: expected {} but got {}",
                        idx, exp, act
                    ));
                }
            }

            return None;
        }

        if expected.is_object() && !actual_details.is_empty() {
            return Some(format!(
                "backend returned details, but ERROR.details is missing in gctf; actual details: {}",
                Value::Array(actual_details)
            ));
        }

        None
    }

    fn decode_status_details(raw: &[u8]) -> Option<Vec<Value>> {
        if raw.is_empty() {
            return Some(Vec::new());
        }

        let status = GoogleRpcStatus::decode(raw).ok()?;
        Some(status.details.into_iter().map(Self::any_to_json).collect())
    }

    fn any_to_json(any: Any) -> Value {
        let type_url = any.type_url;
        let value = any.value;

        if type_url.ends_with("/google.rpc.ErrorInfo") {
            if let Ok(info) = GoogleRpcErrorInfo::decode(value.as_slice()) {
                let mut metadata = Map::new();
                for (k, v) in info.metadata {
                    metadata.insert(k, Value::String(v));
                }

                return json!({
                    "@type": type_url,
                    "reason": info.reason,
                    "domain": info.domain,
                    "metadata": metadata,
                });
            }

            return json!({
                "@type": type_url,
                "_decodeError": "failed to decode ErrorInfo",
                "_valueHex": Self::hex_encode(value.as_slice()),
            });
        }

        if type_url.ends_with("/google.rpc.BadRequest") {
            if let Ok(bad_request) = GoogleRpcBadRequest::decode(value.as_slice()) {
                let field_violations = bad_request
                    .field_violations
                    .into_iter()
                    .map(|violation| {
                        json!({
                            "field": violation.field,
                            "description": violation.description,
                        })
                    })
                    .collect::<Vec<_>>();

                return json!({
                    "@type": type_url,
                    "fieldViolations": field_violations,
                });
            }

            return json!({
                "@type": type_url,
                "_decodeError": "failed to decode BadRequest",
                "_valueHex": Self::hex_encode(value.as_slice()),
            });
        }

        json!({
            "@type": type_url,
            "_valueHex": Self::hex_encode(value.as_slice()),
        })
    }

    fn hex_encode(bytes: &[u8]) -> String {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        let mut output = String::with_capacity(bytes.len() * 2);
        for byte in bytes {
            output.push(HEX[(byte >> 4) as usize] as char);
            output.push(HEX[(byte & 0x0f) as usize] as char);
        }
        output
    }

    /// Get gRPC code name from numeric code
    pub fn grpc_code_name_from_numeric(code: i64) -> Option<&'static str> {
        match code {
            0 => Some("OK"),
            1 => Some("Cancelled"),
            2 => Some("Unknown"),
            3 => Some("InvalidArgument"),
            4 => Some("DeadlineExceeded"),
            5 => Some("NotFound"),
            6 => Some("AlreadyExists"),
            7 => Some("PermissionDenied"),
            8 => Some("ResourceExhausted"),
            9 => Some("FailedPrecondition"),
            10 => Some("Aborted"),
            11 => Some("OutOfRange"),
            12 => Some("Unimplemented"),
            13 => Some("Internal"),
            14 => Some("Unavailable"),
            15 => Some("DataLoss"),
            16 => Some("Unauthenticated"),
            _ => None,
        }
    }

    /// Format error message for display
    pub fn format_error_message(_error_text: &str, expected: &Value) -> String {
        let mut parts = Vec::new();

        if let Some(msg) = expected.get("message").and_then(|v| v.as_str()) {
            parts.push(format!("expected message: {}", msg));
        }

        if let Some(code) = expected.get("code").and_then(|v| v.as_i64()) {
            if let Some(code_name) = Self::grpc_code_name_from_numeric(code) {
                parts.push(format!("expected code: {} ({})", code, code_name));
            } else {
                parts.push(format!("expected code: {}", code));
            }
        }

        if expected.get("details").is_some() {
            parts.push("expected details".to_string());
        }

        if parts.is_empty() {
            "error expected".to_string()
        } else {
            parts.join(", ")
        }
    }

    /// Check if error text contains expected code
    pub fn error_contains_code(error_text: &str, expected_code: i64) -> bool {
        if let Some(code_name) = Self::grpc_code_name_from_numeric(expected_code) {
            error_text.contains(&format!("status: {}", code_name))
                || error_text.contains(&format!("code: {}", expected_code))
        } else {
            error_text.contains(&format!("code: {}", expected_code))
        }
    }

    /// Check if error text contains expected message
    pub fn error_contains_message(error_text: &str, expected_message: &str) -> bool {
        error_text.contains(expected_message)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use prost::Message;
    use serde_json::json;
    use tonic::Code;

    fn status_with_details() -> tonic::Status {
        let error_info = GoogleRpcErrorInfo {
            reason: "API_DISABLED".to_string(),
            domain: "your.service.com".to_string(),
            metadata: std::collections::HashMap::from([
                ("service".to_string(), "your.service.com".to_string()),
                ("consumer".to_string(), "projects/123".to_string()),
            ]),
        };

        let bad_request = GoogleRpcBadRequest {
            field_violations: vec![GoogleRpcBadRequestFieldViolation {
                field: "name".to_string(),
                description: "Name must be at least 3 characters".to_string(),
            }],
        };

        let status_proto = GoogleRpcStatus {
            code: Code::InvalidArgument as i32,
            message: "Invalid argument provided".to_string(),
            details: vec![
                Any {
                    type_url: "type.googleapis.com/google.rpc.ErrorInfo".to_string(),
                    value: error_info.encode_to_vec(),
                },
                Any {
                    type_url: "type.googleapis.com/google.rpc.BadRequest".to_string(),
                    value: bad_request.encode_to_vec(),
                },
            ],
        };

        tonic::Status::with_details(
            Code::InvalidArgument,
            "Invalid argument provided",
            status_proto.encode_to_vec().into(),
        )
    }

    fn status_without_details() -> tonic::Status {
        tonic::Status::new(Code::InvalidArgument, "Invalid argument provided")
    }

    #[test]
    fn test_error_matches_expected_message() {
        let error_text = "Error: status: NotFound, message: Resource not found";
        let expected = json!({"message": "Resource not found"});

        assert!(ErrorHandler::error_matches_expected(error_text, &expected));
    }

    #[test]
    fn test_error_matches_expected_code() {
        let error_text = "Error: status: NotFound, message: Resource not found";
        let expected = json!({"code": 5});

        assert!(ErrorHandler::error_matches_expected(error_text, &expected));
    }

    #[test]
    fn test_error_matches_expected_both() {
        let error_text = "Error: status: NotFound, message: Resource not found";
        let expected = json!({"code": 5, "message": "Resource not found"});

        assert!(ErrorHandler::error_matches_expected(error_text, &expected));
    }

    #[test]
    fn test_error_matches_expected_wrong_message() {
        let error_text = "Error: status: NotFound, message: Resource not found";
        let expected = json!({"message": "Wrong message"});

        assert!(!ErrorHandler::error_matches_expected(error_text, &expected));
    }

    #[test]
    fn test_error_matches_expected_wrong_code() {
        let error_text = "Error: status: NotFound, message: Resource not found";
        let expected = json!({"code": 3});

        assert!(!ErrorHandler::error_matches_expected(error_text, &expected));
    }

    #[test]
    fn test_grpc_code_name_from_numeric() {
        assert_eq!(ErrorHandler::grpc_code_name_from_numeric(0), Some("OK"));
        assert_eq!(
            ErrorHandler::grpc_code_name_from_numeric(5),
            Some("NotFound")
        );
        assert_eq!(
            ErrorHandler::grpc_code_name_from_numeric(13),
            Some("Internal")
        );
        assert_eq!(ErrorHandler::grpc_code_name_from_numeric(999), None);
    }

    #[test]
    fn test_format_error_message() {
        let expected = json!({"code": 5, "message": "Resource not found"});
        let formatted = ErrorHandler::format_error_message("", &expected);

        assert!(formatted.contains("expected message: Resource not found"));
        assert!(formatted.contains("expected code: 5 (NotFound)"));
    }

    #[test]
    fn test_error_contains_code() {
        let error_text = "Error: status: NotFound, code: 5";

        assert!(ErrorHandler::error_contains_code(error_text, 5));
        assert!(!ErrorHandler::error_contains_code(error_text, 3));
    }

    #[test]
    fn test_error_contains_message() {
        let error_text = "Error: Resource not found";

        assert!(ErrorHandler::error_contains_message(
            error_text,
            "Resource not found"
        ));
        assert!(!ErrorHandler::error_contains_message(
            error_text,
            "Wrong message"
        ));
    }

    #[test]
    fn test_error_matches_expected_string() {
        let error_text = "Error: Resource not found";
        let expected = json!("Resource not found");

        assert!(ErrorHandler::error_matches_expected(error_text, &expected));
    }

    #[test]
    fn test_status_matches_expected_with_details() {
        let status = status_with_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided",
            "details": [
                {
                    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                    "reason": "API_DISABLED",
                    "domain": "your.service.com",
                    "metadata": {
                        "service": "your.service.com",
                        "consumer": "projects/123"
                    }
                },
                {
                    "@type": "type.googleapis.com/google.rpc.BadRequest",
                    "fieldViolations": [
                        {
                            "field": "name",
                            "description": "Name must be at least 3 characters"
                        }
                    ]
                }
            ]
        });

        assert!(ErrorHandler::status_matches_expected(&status, &expected));
    }

    #[test]
    fn test_status_matches_expected_with_wrong_details() {
        let status = status_with_details();
        let expected = json!({
            "details": [
                {
                    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                    "reason": "WRONG_REASON"
                }
            ]
        });

        assert!(!ErrorHandler::status_matches_expected(&status, &expected));
    }

    #[test]
    fn test_status_matches_expected_fails_when_actual_has_unexpected_details() {
        let status = status_with_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided"
        });

        assert!(!ErrorHandler::status_matches_expected(&status, &expected));
    }

    #[test]
    fn test_status_matches_expected_fails_when_expected_requires_details() {
        let status = status_without_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided",
            "details": [
                {
                    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                    "reason": "API_DISABLED"
                }
            ]
        });

        assert!(!ErrorHandler::status_matches_expected(&status, &expected));
    }

    #[test]
    fn test_status_matches_expected_passes_when_no_details_on_both_sides() {
        let status = status_without_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided"
        });

        assert!(ErrorHandler::status_matches_expected(&status, &expected));
    }

    #[test]
    fn test_status_matches_expected_rejects_partial_message_match() {
        let status = status_without_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument"
        });

        assert!(!ErrorHandler::status_matches_expected(&status, &expected));
        let reason = ErrorHandler::status_mismatch_reason(&status, &expected).unwrap();
        assert!(reason.contains("expected 'Invalid argument'"));
        assert!(reason.contains("got 'Invalid argument provided'"));
    }

    #[test]
    fn test_status_matches_expected_partial_allows_subset_top_level_fields() {
        let status = status_with_details();
        let expected = json!({
            "code": 3
        });

        assert!(ErrorHandler::status_matches_expected_with_options(
            &status, &expected, true
        ));
    }

    #[test]
    fn test_status_matches_expected_partial_allows_subset_details_payload() {
        let status = status_with_details();
        let expected = json!({
            "code": 3,
            "details": [
                {
                    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                    "reason": "API_DISABLED"
                }
            ]
        });

        assert!(ErrorHandler::status_matches_expected_with_options(
            &status, &expected, true
        ));
    }

    #[test]
    fn test_status_matches_expected_partial_fails_when_expected_detail_item_missing() {
        let status = status_with_details();
        let expected = json!({
            "code": 3,
            "details": [
                {
                    "@type": "type.googleapis.com/google.rpc.DebugInfo",
                    "detail": "not-present"
                }
            ]
        });

        assert!(!ErrorHandler::status_matches_expected_with_options(
            &status, &expected, true
        ));
        let reason = ErrorHandler::status_mismatch_reason_with_options(&status, &expected, true)
            .expect("partial mismatch reason");
        assert!(reason.contains("expected array item"));
    }

    #[test]
    fn test_status_matches_expected_strict_fails_when_message_omitted() {
        let status = status_without_details();
        let expected = json!({
            "code": 3
        });

        assert!(!ErrorHandler::status_matches_expected_with_options(
            &status, &expected, false
        ));
        let reason = ErrorHandler::status_mismatch_reason_with_options(&status, &expected, false)
            .expect("strict mismatch reason");
        assert!(reason.contains("unexpected field"));
        assert!(reason.contains("message"));
    }

    #[test]
    fn test_status_matches_expected_partial_passes_when_message_omitted() {
        let status = status_without_details();
        let expected = json!({
            "code": 3
        });

        assert!(ErrorHandler::status_matches_expected_with_options(
            &status, &expected, true
        ));
    }

    #[test]
    fn test_status_matches_expected_strict_allows_missing_details_when_not_present_in_actual() {
        let status = status_without_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided"
        });

        assert!(ErrorHandler::status_matches_expected_with_options(
            &status, &expected, false
        ));
    }

    #[test]
    fn test_status_mismatch_reason_for_unexpected_details() {
        let status = status_with_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided"
        });

        let reason = ErrorHandler::status_mismatch_reason(&status, &expected).unwrap();
        assert!(reason.contains("ERROR.details is missing"));
        assert!(reason.contains("actual details"));
        assert!(reason.contains("type.googleapis.com/google.rpc.ErrorInfo"));
    }

    #[test]
    fn test_status_mismatch_reason_for_missing_required_details() {
        let status = status_without_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided",
            "details": [
                {"@type": "type.googleapis.com/google.rpc.ErrorInfo"}
            ]
        });

        let reason = ErrorHandler::status_mismatch_reason(&status, &expected).unwrap();
        assert!(reason.contains("details mismatch"));
    }

    #[test]
    fn test_status_to_json_contains_details() {
        let status = status_with_details();
        let json = ErrorHandler::status_to_json(&status);
        assert_eq!(json["code"], 3);
        assert_eq!(json["message"], "Invalid argument provided");
        assert!(json.get("details").is_some());
    }

    #[test]
    fn test_status_matches_expected_fails_when_details_field_is_missing_in_expected_object() {
        let status = status_with_details();
        let expected = json!({
            "code": 3,
            "message": "Invalid argument provided",
            "details": [
                {
                    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                    "reason": "API_DISABLED",
                    "domain": "your.service.com",
                    "metadata": {
                        "service": "your.service.com",
                        "consumer": "projects/123"
                    }
                },
                {
                    "@type": "type.googleapis.com/google.rpc.BadRequest",
                    "fieldViolations": [
                        {
                            "description": "Name must be at least 3 characters"
                        }
                    ]
                }
            ]
        });

        assert!(!ErrorHandler::status_matches_expected(&status, &expected));
        let reason = ErrorHandler::status_mismatch_reason(&status, &expected).unwrap();
        assert!(reason.contains("details mismatch at index 1"));
    }
}