toasty_driver_integration_suite/
test.rs1use 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
11static TEST_LOCK: RwLock<()> = RwLock::new(());
15
16pub struct Test {
20 setup: Arc<dyn Setup>,
22
23 isolate: Isolate,
25
26 runtime: Option<Runtime>,
28
29 exec_log: ExecLog,
30
31 tables: Vec<String>,
33
34 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 pub async fn try_setup_db(&mut self, mut builder: toasty::db::Builder) -> toasty::Result<Db> {
57 builder.table_name_prefix(&self.isolate.table_prefix());
59
60 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 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 pub async fn setup_db(&mut self, builder: toasty::db::Builder) -> Db {
78 self.try_setup_db(builder).await.unwrap()
79 }
80
81 pub fn capability(&self) -> &'static toasty_core::driver::Capability {
83 self.setup.driver().capability()
84 }
85
86 pub fn log(&mut self) -> &mut ExecLog {
88 &mut self.exec_log
89 }
90
91 pub fn set_serial(&mut self, serial: bool) {
93 self.serial = serial;
94 }
95
96 pub fn run<R>(&mut self, f: impl AsyncFn(&mut Test) -> R)
98 where
99 R: Into<TestResult>,
100 {
101 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 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 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}