toasty_driver_integration_suite/
test.rs

1use std::{
2    error::Error,
3    sync::{Arc, Mutex, RwLock},
4};
5
6use toasty::Db;
7use tokio::runtime::Runtime;
8
9use crate::{ExecLog, Isolate, LoggingDriver, Setup};
10
11/// Global lock for coordinating serial vs parallel tests.
12/// Normal tests acquire a read lock (allowing parallelism).
13/// Serial tests acquire a write lock (exclusive access).
14static TEST_LOCK: RwLock<()> = RwLock::new(());
15
16/// Wraps the Tokio runtime and ensures cleanup happens.
17///
18/// This also passes necessary
19pub struct Test {
20    /// Handle to the DB suite setup
21    setup: Arc<dyn Setup>,
22
23    /// Handles isolating tables between tests
24    isolate: Isolate,
25
26    /// Tokio runtime used by the test
27    runtime: Option<Runtime>,
28
29    exec_log: ExecLog,
30
31    /// List of all tables created during the test. These will need to be removed later.
32    tables: Vec<String>,
33
34    /// Whether this test requires exclusive (serial) execution
35    serial: bool,
36}
37
38impl Test {
39    pub fn new(setup: Arc<dyn Setup>) -> Self {
40        let runtime = tokio::runtime::Builder::new_current_thread()
41            .enable_all()
42            .build()
43            .expect("failed to create Tokio runtime");
44
45        Test {
46            setup,
47            isolate: Isolate::new(),
48            runtime: Some(runtime),
49            exec_log: ExecLog::new(Arc::new(Mutex::new(Vec::new()))),
50            tables: vec![],
51            serial: false,
52        }
53    }
54
55    /// Try to setup a database with models, returns Result for error handling
56    pub async fn try_setup_db(&mut self, mut builder: toasty::db::Builder) -> toasty::Result<Db> {
57        // Set the table prefix
58        builder.table_name_prefix(&self.isolate.table_prefix());
59
60        // Always wrap with logging
61        let logging_driver = LoggingDriver::new(self.setup.driver());
62        let ops_log = logging_driver.ops_log_handle();
63        self.exec_log = ExecLog::new(ops_log);
64
65        // Build the database with the logging driver
66        let mut db = builder.build(logging_driver).await?;
67        db.push_schema().await?;
68
69        for table in &db.schema().db.tables {
70            self.tables.push(table.name.clone());
71        }
72
73        Ok(db)
74    }
75
76    /// Setup a database with models, always with logging enabled
77    pub async fn setup_db(&mut self, builder: toasty::db::Builder) -> Db {
78        self.try_setup_db(builder).await.unwrap()
79    }
80
81    /// Get the driver capability
82    pub fn capability(&self) -> &'static toasty_core::driver::Capability {
83        self.setup.driver().capability()
84    }
85
86    /// Get the execution log for assertions
87    pub fn log(&mut self) -> &mut ExecLog {
88        &mut self.exec_log
89    }
90
91    /// Set whether this test requires exclusive (serial) execution
92    pub fn set_serial(&mut self, serial: bool) {
93        self.serial = serial;
94    }
95
96    /// Run an async test function using the internal runtime
97    pub fn run<R>(&mut self, f: impl AsyncFn(&mut Test) -> R)
98    where
99        R: Into<TestResult>,
100    {
101        // Acquire the appropriate lock: write lock for serial tests (exclusive),
102        // read lock for normal tests (parallel).
103        let _guard: Box<dyn std::any::Any> = if self.serial {
104            Box::new(TEST_LOCK.write().unwrap_or_else(|e| e.into_inner()))
105        } else {
106            Box::new(TEST_LOCK.read().unwrap_or_else(|e| e.into_inner()))
107        };
108
109        // Temporarily take the runtime to avoid borrow checker issues
110        let runtime = self.runtime.take().expect("runtime already consumed");
111        let f: std::pin::Pin<Box<dyn std::future::Future<Output = R>>> = Box::pin(f(self));
112        let result = runtime.block_on(f).into();
113
114        // now, wut
115        for table in &self.tables {
116            runtime.block_on(self.setup.delete_table(table));
117        }
118
119        if let Some(error) = result.error {
120            panic!("Driver test returned an error: {error}");
121        }
122
123        self.runtime = Some(runtime);
124    }
125}
126
127pub struct TestResult {
128    error: Option<Box<dyn Error>>,
129}
130
131impl From<()> for TestResult {
132    fn from(_: ()) -> Self {
133        TestResult { error: None }
134    }
135}
136
137impl<O, E> From<Result<O, E>> for TestResult
138where
139    E: Into<Box<dyn Error>>,
140{
141    fn from(value: Result<O, E>) -> Self {
142        TestResult {
143            error: value.err().map(Into::into),
144        }
145    }
146}