Skip to main content

wae_testing/environment/
hooks.rs

1//! 测试生命周期钩子模块
2
3use wae_types::WaeResult as TestingResult;
4
5/// 测试生命周期钩子 trait
6///
7/// 定义测试环境在各个阶段执行的钩子函数,用于自定义测试环境的初始化和清理逻辑。
8pub trait TestLifecycleHook: Send + Sync {
9    /// 在测试环境初始化之前执行
10    ///
11    /// # Errors
12    ///
13    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
14    fn before_setup(&self, _env: &crate::TestEnv) -> TestingResult<()> {
15        Ok(())
16    }
17
18    /// 在测试环境初始化之后执行
19    ///
20    /// # Errors
21    ///
22    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
23    fn after_setup(&self, _env: &crate::TestEnv) -> TestingResult<()> {
24        Ok(())
25    }
26
27    /// 在测试环境清理之前执行
28    ///
29    /// # Errors
30    ///
31    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
32    fn before_teardown(&self, _env: &crate::TestEnv) -> TestingResult<()> {
33        Ok(())
34    }
35
36    /// 在测试环境清理之后执行
37    ///
38    /// # Errors
39    ///
40    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
41    fn after_teardown(&self, _env: &crate::TestEnv) -> TestingResult<()> {
42        Ok(())
43    }
44}
45
46impl<F> TestLifecycleHook for F
47where
48    F: Fn(&crate::TestEnv) -> TestingResult<()> + Send + Sync,
49{
50    fn after_setup(&self, env: &crate::TestEnv) -> TestingResult<()> {
51        self(env)
52    }
53}
54
55/// 异步测试生命周期钩子 trait
56///
57/// 定义测试环境在各个阶段执行的异步钩子函数,支持异步操作的初始化和清理。
58#[async_trait::async_trait]
59pub trait AsyncTestLifecycleHook: Send + Sync {
60    /// 在测试环境初始化之前异步执行
61    ///
62    /// # Errors
63    ///
64    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
65    async fn before_setup_async(&self, _env: &crate::TestEnv) -> TestingResult<()> {
66        Ok(())
67    }
68
69    /// 在测试环境初始化之后异步执行
70    ///
71    /// # Errors
72    ///
73    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
74    async fn after_setup_async(&self, _env: &crate::TestEnv) -> TestingResult<()> {
75        Ok(())
76    }
77
78    /// 在测试环境清理之前异步执行
79    ///
80    /// # Errors
81    ///
82    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
83    async fn before_teardown_async(&self, _env: &crate::TestEnv) -> TestingResult<()> {
84        Ok(())
85    }
86
87    /// 在测试环境清理之后异步执行
88    ///
89    /// # Errors
90    ///
91    /// 如果钩子执行失败,将返回 [`WaeError`] 错误。
92    async fn after_teardown_async(&self, _env: &crate::TestEnv) -> TestingResult<()> {
93        Ok(())
94    }
95}