Skip to main content

openlark_core/testing/
mock_context.rs

1//! Mock 服务器配置和测试运行时
2//!
3//! 提供异步测试运行时的统一创建方式和 Mock 服务器配置。
4
5use tokio::runtime::Runtime;
6
7/// 异步测试运行时助手
8///
9/// 封装 Tokio Runtime 的创建,提供清晰的错误消息。
10///
11/// # 示例
12///
13/// ```rust,ignore
14/// let rt = TestRuntime::new();
15/// let result = rt.block_on(async { some_api().await });
16/// ```
17#[derive(Debug)]
18pub struct TestRuntime {
19    rt: Runtime,
20}
21
22impl TestRuntime {
23    /// 创建新的测试运行时
24    ///
25    /// 如果创建失败,会 panic 并显示清晰的错误信息。
26    pub fn new() -> Self {
27        Self {
28            rt: Runtime::new().expect(
29                "Failed to create test runtime. This may indicate insufficient system resources.",
30            ),
31        }
32    }
33
34    /// 在运行时中执行异步代码
35    pub fn block_on<F>(&self, future: F) -> F::Output
36    where
37        F: std::future::Future,
38    {
39        self.rt.block_on(future)
40    }
41}
42
43impl Default for TestRuntime {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49/// 快捷方法:创建默认测试运行时
50///
51/// # 示例
52///
53/// ```rust,ignore
54/// let rt = test_runtime();
55/// ```
56pub fn test_runtime() -> Runtime {
57    Runtime::new()
58        .expect("Failed to create test runtime. This may indicate insufficient system resources.")
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_test_runtime_creation() {
67        let _rt = TestRuntime::new();
68        // 如果到达这里,说明 Runtime 创建成功
69    }
70
71    #[test]
72    fn test_test_runtime_block_on() {
73        let rt = TestRuntime::new();
74        let result = rt.block_on(async { 42 });
75        assert_eq!(result, 42);
76    }
77
78    #[test]
79    fn test_test_runtime_default() {
80        let rt = TestRuntime::default();
81        let result = rt.block_on(async { "test".to_string() });
82        assert_eq!(result, "test");
83    }
84}