Skip to main content

common_error/
mock.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Utils for mock.
16
17use std::any::Any;
18use std::fmt;
19
20use crate::ext::{ErrorExt, RetryHint, StackError};
21use crate::status_code::StatusCode;
22
23/// A mock error mainly for test.
24#[derive(Debug)]
25pub struct MockError {
26    pub code: StatusCode,
27    retry_hint: RetryHint,
28    source: Option<Box<MockError>>,
29}
30
31impl MockError {
32    /// Create a new [MockError] without backtrace.
33    pub fn new(code: StatusCode) -> MockError {
34        MockError {
35            code,
36            retry_hint: RetryHint::NonRetryable,
37            source: None,
38        }
39    }
40
41    /// Sets the retry hint independently of the status code.
42    pub fn with_retry_hint(mut self, retry_hint: RetryHint) -> Self {
43        self.retry_hint = retry_hint;
44        self
45    }
46
47    /// Create a new [MockError] with source.
48    pub fn with_source(source: MockError) -> MockError {
49        MockError {
50            code: source.code,
51            retry_hint: source.retry_hint,
52            source: Some(Box::new(source)),
53        }
54    }
55}
56
57impl fmt::Display for MockError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(f, "{}", self.code)
60    }
61}
62
63impl std::error::Error for MockError {
64    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
65        self.source.as_ref().map(|e| e as _)
66    }
67}
68
69impl ErrorExt for MockError {
70    fn status_code(&self) -> StatusCode {
71        self.code
72    }
73
74    fn as_any(&self) -> &dyn Any {
75        self
76    }
77
78    fn retry_hint(&self) -> RetryHint {
79        self.retry_hint
80    }
81}
82
83impl StackError for MockError {
84    fn debug_fmt(&self, _: usize, _: &mut Vec<String>) {}
85
86    fn next(&self) -> Option<&dyn StackError> {
87        None
88    }
89}