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, 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    source: Option<Box<MockError>>,
28}
29
30impl MockError {
31    /// Create a new [MockError] without backtrace.
32    pub fn new(code: StatusCode) -> MockError {
33        MockError { code, source: None }
34    }
35
36    /// Create a new [MockError] with source.
37    pub fn with_source(source: MockError) -> MockError {
38        MockError {
39            code: source.code,
40            source: Some(Box::new(source)),
41        }
42    }
43}
44
45impl fmt::Display for MockError {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "{}", self.code)
48    }
49}
50
51impl std::error::Error for MockError {
52    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
53        self.source.as_ref().map(|e| e as _)
54    }
55}
56
57impl ErrorExt for MockError {
58    fn status_code(&self) -> StatusCode {
59        self.code
60    }
61
62    fn as_any(&self) -> &dyn Any {
63        self
64    }
65}
66
67impl StackError for MockError {
68    fn debug_fmt(&self, _: usize, _: &mut Vec<String>) {}
69
70    fn next(&self) -> Option<&dyn StackError> {
71        None
72    }
73}