1use std::sync::atomic::{AtomicU64, Ordering};
8
9use bsql_driver_postgres::{Config, Connection};
10
11use crate::error::{BsqlError, ConnectError};
12use crate::pool::Pool;
13
14static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);
15
16pub struct TestContext {
19 pub pool: Pool,
21 schema_name: String,
22 db_url: String,
23}
24
25impl std::fmt::Debug for TestContext {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 f.debug_struct("TestContext")
28 .field("schema", &self.schema_name)
29 .finish()
30 }
31}
32
33impl Drop for TestContext {
34 fn drop(&mut self) {
35 if let Ok(config) = Config::from_url(&self.db_url) {
38 if let Ok(mut conn) = Connection::connect(&config) {
39 let _ = conn.simple_query(&format!(
40 "DROP SCHEMA IF EXISTS \"{}\" CASCADE",
41 self.schema_name
42 ));
43 }
44 }
45 }
46}
47
48pub async fn setup_test_schema(fixtures_sql: &[&str]) -> Result<TestContext, BsqlError> {
54 let db_url = std::env::var("BSQL_DATABASE_URL")
55 .or_else(|_| std::env::var("DATABASE_URL"))
56 .map_err(|_| {
57 ConnectError::create("BSQL_DATABASE_URL or DATABASE_URL must be set for #[bsql::test]")
58 })?;
59
60 let schema_name = format!(
61 "__bsql_test_{}_{}",
62 std::process::id(),
63 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
64 );
65
66 let config = Config::from_url(&db_url)
68 .map_err(|e| ConnectError::create(format!("invalid database URL: {e}")))?;
69 let mut conn = Connection::connect(&config)
70 .map_err(|e| ConnectError::create(format!("connection failed: {e}")))?;
71
72 conn.simple_query(&format!("CREATE SCHEMA \"{}\"", schema_name))
74 .map_err(|e| ConnectError::create(format!("failed to create test schema: {e}")))?;
75
76 conn.simple_query(&format!("SET search_path TO \"{}\", public", schema_name))
78 .map_err(|e| ConnectError::create(format!("failed to set search_path: {e}")))?;
79
80 for fixture_sql in fixtures_sql {
82 if !fixture_sql.trim().is_empty() {
83 conn.simple_query(fixture_sql)
84 .map_err(|e| ConnectError::create(format!("fixture failed: {e}")))?;
85 }
86 }
87
88 drop(conn); let pool = Pool::connect(&db_url).await?;
93
94 pool.raw_execute(&format!("SET search_path TO \"{}\", public", schema_name))
97 .await?;
98
99 let warmup_sql = format!("SET search_path TO \"{}\", public", schema_name);
103 pool.set_warmup_sqls([warmup_sql]);
106
107 Ok(TestContext {
108 pool,
109 schema_name,
110 db_url,
111 })
112}
113
114#[cfg(feature = "sqlite")]
123pub struct SqliteTestContext {
124 pub pool: crate::sqlite_pool::SqlitePool,
126 pub db_path: std::path::PathBuf,
128}
129
130#[cfg(feature = "sqlite")]
131impl Drop for SqliteTestContext {
132 fn drop(&mut self) {
133 self.pool.close();
135 let _ = std::fs::remove_file(&self.db_path);
137 let _ = std::fs::remove_file(format!("{}-wal", self.db_path.display()));
138 let _ = std::fs::remove_file(format!("{}-shm", self.db_path.display()));
139 }
140}
141
142#[cfg(feature = "sqlite")]
150pub fn setup_sqlite_test(
151 fixtures_sql: &[&str],
152) -> Result<SqliteTestContext, crate::error::BsqlError> {
153 use crate::error::ConnectError;
154
155 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
157 let db_path = std::env::temp_dir().join(format!(
158 "bsql_test_{}_{}.db",
159 std::process::id(),
160 COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
161 ));
162
163 let pool = crate::sqlite_pool::SqlitePool::connect(db_path.to_str().unwrap_or("bsql_test.db"))?;
165
166 for fixture_sql in fixtures_sql {
168 if !fixture_sql.trim().is_empty() {
169 pool.simple_exec(fixture_sql)
170 .map_err(|e| ConnectError::create(format!("SQLite fixture failed: {e}")))?;
171 }
172 }
173
174 Ok(SqliteTestContext { pool, db_path })
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180 use std::collections::HashSet;
181
182 #[test]
187 fn schema_name_is_unique() {
188 let name1 = format!(
189 "__bsql_test_{}_{}",
190 std::process::id(),
191 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
192 );
193 let name2 = format!(
194 "__bsql_test_{}_{}",
195 std::process::id(),
196 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
197 );
198 assert_ne!(name1, name2);
199 }
200
201 #[test]
202 fn schema_name_contains_pid() {
203 let name = format!(
204 "__bsql_test_{}_{}",
205 std::process::id(),
206 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
207 );
208 assert!(name.contains(&std::process::id().to_string()));
209 }
210
211 #[test]
212 fn schema_name_starts_with_prefix() {
213 let name = format!(
214 "__bsql_test_{}_{}",
215 std::process::id(),
216 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
217 );
218 assert!(name.starts_with("__bsql_test_"));
219 }
220
221 #[test]
222 fn schema_names_never_collide_100_sequential() {
223 let mut names = HashSet::new();
224 for _ in 0..100 {
225 let name = format!(
226 "__bsql_test_{}_{}",
227 std::process::id(),
228 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
229 );
230 assert!(names.insert(name.clone()), "duplicate schema name: {name}");
231 }
232 assert_eq!(names.len(), 100);
233 }
234
235 #[test]
236 fn schema_name_is_valid_sql_identifier() {
237 let name = format!(
238 "__bsql_test_{}_{}",
239 std::process::id(),
240 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
241 );
242 assert!(
244 name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
245 "schema name contains invalid chars: {name}"
246 );
247 assert!(
248 name.starts_with('_') || name.starts_with(|c: char| c.is_ascii_alphabetic()),
249 "schema name must start with letter or underscore: {name}"
250 );
251 }
252
253 #[test]
258 fn test_counter_is_monotonic() {
259 let a = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
260 let b = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
261 let c = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
262 assert!(a < b);
263 assert!(b < c);
264 }
265
266 #[test]
267 fn counter_increments_atomically_across_threads() {
268 use std::sync::Arc;
269 let results: Arc<std::sync::Mutex<Vec<u64>>> = Arc::new(std::sync::Mutex::new(Vec::new()));
270 let mut handles = Vec::new();
271 for _ in 0..10 {
272 let results = Arc::clone(&results);
273 handles.push(std::thread::spawn(move || {
274 for _ in 0..10 {
275 let val = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
276 results.lock().unwrap().push(val);
277 }
278 }));
279 }
280 for h in handles {
281 h.join().unwrap();
282 }
283 let mut vals = results.lock().unwrap().clone();
284 assert_eq!(vals.len(), 100, "expected 100 counter values");
285 let set: HashSet<u64> = vals.iter().copied().collect();
287 assert_eq!(
288 set.len(),
289 100,
290 "counter values must be unique across threads"
291 );
292 vals.sort();
294 for window in vals.windows(2) {
295 assert!(window[0] < window[1], "counter must be strictly increasing");
296 }
297 }
298
299 #[test]
304 fn multiple_schema_names_created_simultaneously_are_different() {
305 let names: Vec<String> = (0..50)
307 .map(|_| {
308 format!(
309 "__bsql_test_{}_{}",
310 std::process::id(),
311 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
312 )
313 })
314 .collect();
315 let set: HashSet<&String> = names.iter().collect();
316 assert_eq!(set.len(), names.len(), "all schema names must be unique");
317 }
318
319 static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
328
329 struct EnvGuard {
330 orig_bsql: Option<String>,
331 orig_db: Option<String>,
332 _lock: std::sync::MutexGuard<'static, ()>,
333 }
334
335 impl EnvGuard {
336 fn lock() -> Self {
337 let lock = ENV_MUTEX.lock().unwrap();
338 let orig_bsql = std::env::var("BSQL_DATABASE_URL").ok();
339 let orig_db = std::env::var("DATABASE_URL").ok();
340 Self {
341 orig_bsql,
342 orig_db,
343 _lock: lock,
344 }
345 }
346 }
347
348 impl Drop for EnvGuard {
349 fn drop(&mut self) {
350 std::env::remove_var("BSQL_DATABASE_URL");
351 std::env::remove_var("DATABASE_URL");
352 if let Some(v) = &self.orig_bsql {
353 std::env::set_var("BSQL_DATABASE_URL", v);
354 }
355 if let Some(v) = &self.orig_db {
356 std::env::set_var("DATABASE_URL", v);
357 }
358 }
359 }
360
361 #[tokio::test]
362 async fn missing_db_url_returns_clear_error() {
363 let _guard = EnvGuard::lock();
364 std::env::remove_var("BSQL_DATABASE_URL");
365 std::env::remove_var("DATABASE_URL");
366
367 let result = setup_test_schema(&[]).await;
368 assert!(result.is_err(), "missing env vars should produce an error");
369 }
370
371 #[tokio::test]
372 async fn missing_bsql_database_url_falls_back_to_database_url() {
373 let _guard = EnvGuard::lock();
374 std::env::remove_var("BSQL_DATABASE_URL");
375 std::env::set_var("DATABASE_URL", "postgres://user:pass@127.0.0.1:1/nope");
376
377 let result = setup_test_schema(&[]).await;
378 assert!(
379 result.is_err(),
380 "fallback to DATABASE_URL should still fail on bogus host"
381 );
382 }
383
384 #[tokio::test]
385 async fn invalid_db_url_returns_clear_error() {
386 let _guard = EnvGuard::lock();
387 std::env::set_var("BSQL_DATABASE_URL", "postgres://user:pass@127.0.0.1:1/nope");
388 std::env::remove_var("DATABASE_URL");
389
390 let result = setup_test_schema(&[]).await;
391 assert!(result.is_err(), "connecting to bogus URL should fail");
392 }
393
394 #[tokio::test]
395 async fn invalid_db_url_not_postgres_scheme() {
396 let _guard = EnvGuard::lock();
397 std::env::set_var("BSQL_DATABASE_URL", "mysql://user:pass@127.0.0.1:1/db");
398 std::env::remove_var("DATABASE_URL");
399
400 let result = setup_test_schema(&[]).await;
401 assert!(result.is_err(), "non-postgres scheme should fail");
402 }
403
404 #[test]
405 fn connection_refused_unreachable_host() {
406 let url = "postgres://user:pass@127.0.0.1:1/testdb";
409 let config = Config::from_url(url).expect("URL should parse");
410 let conn_result = Connection::connect(&config);
411 assert!(conn_result.is_err(), "connection to port 1 should fail");
412 let err = ConnectError::create(format!("connection failed: {}", conn_result.unwrap_err()));
415 let msg = err.to_string();
416 assert!(
417 msg.contains("connection failed"),
418 "unreachable host should produce 'connection failed' error, got: {msg}"
419 );
420 }
421
422 #[test]
427 fn test_context_has_debug_impl() {
428 fn assert_debug<T: std::fmt::Debug>() {}
430 assert_debug::<TestContext>();
431 }
432
433 #[test]
434 fn test_context_debug_shows_schema_name() {
435 let schema = "__bsql_test_12345_0";
439 let expected = format!("TestContext {{ schema: {:?} }}", schema);
440 assert!(expected.contains("TestContext"));
442 assert!(expected.contains("schema"));
443 assert!(expected.contains(schema));
444 }
445
446 #[test]
451 fn drop_code_path_with_invalid_url_does_not_panic() {
452 let db_url = "garbage-url";
456 let schema_name = "__bsql_test_fake_0";
457 if let Ok(config) = Config::from_url(db_url) {
459 if let Ok(mut conn) = Connection::connect(&config) {
461 let _ = conn.simple_query(&format!(
462 "DROP SCHEMA IF EXISTS \"{}\" CASCADE",
463 schema_name
464 ));
465 }
466 }
467 }
469
470 #[test]
471 fn drop_with_garbage_url_does_not_panic() {
472 let db_url = "not-a-postgres-url";
479 let config_result = Config::from_url(db_url);
480 assert!(config_result.is_err(), "garbage URL should not parse");
481 }
483
484 #[test]
485 fn drop_with_valid_url_but_unreachable_host_does_not_panic() {
486 let db_url = "postgres://user:pass@127.0.0.1:1/testdb";
489 let config = Config::from_url(db_url);
490 assert!(config.is_ok(), "URL should parse");
491 let conn_result = Connection::connect(&config.unwrap());
492 assert!(conn_result.is_err(), "connection to port 1 should fail");
493 }
495
496 #[test]
501 fn empty_fixture_string_is_skipped() {
502 let fixture = "";
505 assert!(fixture.trim().is_empty(), "empty string should be skipped");
506 }
507
508 #[test]
509 fn whitespace_only_fixture_is_skipped() {
510 let fixture = " \n\t \n ";
511 assert!(
512 fixture.trim().is_empty(),
513 "whitespace-only fixture should be skipped"
514 );
515 }
516
517 #[test]
518 fn fixture_with_only_comments_is_not_empty() {
519 let fixture = "-- just a comment\n/* block comment */";
522 assert!(
523 !fixture.trim().is_empty(),
524 "comment-only fixture should NOT be skipped (PG handles it)"
525 );
526 }
527
528 #[test]
529 fn fixture_with_multiple_statements_passes_trim_check() {
530 let fixture = "CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);";
531 assert!(!fixture.trim().is_empty());
532 }
533
534 #[test]
539 fn missing_env_error_is_connect_variant() {
540 let err =
541 ConnectError::create("BSQL_DATABASE_URL or DATABASE_URL must be set for #[bsql::test]");
542 match err {
543 BsqlError::Connect(ref ce) => {
544 assert!(ce.message.contains("BSQL_DATABASE_URL"));
545 }
546 _ => panic!("expected Connect variant"),
547 }
548 }
549
550 #[test]
551 fn invalid_url_error_is_connect_variant() {
552 let err = ConnectError::create("invalid database URL: missing postgres:// prefix");
553 match err {
554 BsqlError::Connect(ref ce) => {
555 assert!(ce.message.contains("invalid database URL"));
556 }
557 _ => panic!("expected Connect variant"),
558 }
559 }
560
561 #[test]
562 fn connection_failed_error_is_connect_variant() {
563 let err = ConnectError::create("connection failed: Connection refused");
564 match err {
565 BsqlError::Connect(ref ce) => {
566 assert!(ce.message.contains("connection failed"));
567 }
568 _ => panic!("expected Connect variant"),
569 }
570 }
571
572 #[test]
573 fn fixture_failed_error_is_connect_variant() {
574 let err = ConnectError::create("fixture failed: syntax error at position 5");
575 match err {
576 BsqlError::Connect(ref ce) => {
577 assert!(ce.message.contains("fixture failed"));
578 }
579 _ => panic!("expected Connect variant"),
580 }
581 }
582
583 #[test]
584 fn schema_creation_failed_error_is_connect_variant() {
585 let err = ConnectError::create("failed to create test schema: permission denied");
586 match err {
587 BsqlError::Connect(ref ce) => {
588 assert!(ce.message.contains("failed to create test schema"));
589 }
590 _ => panic!("expected Connect variant"),
591 }
592 }
593
594 #[test]
599 fn schema_name_has_three_parts() {
600 let counter = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
601 let pid = std::process::id();
602 let name = format!("__bsql_test_{}_{}", pid, counter);
603 assert!(name.starts_with("__bsql_test_"));
605 let suffix = &name["__bsql_test_".len()..];
606 let parts: Vec<&str> = suffix.split('_').collect();
607 assert_eq!(parts.len(), 2, "expected PID_COUNTER suffix, got: {suffix}");
608 assert_eq!(parts[0], pid.to_string());
609 assert_eq!(parts[1], counter.to_string());
610 }
611
612 #[test]
613 fn schema_name_counter_part_increases() {
614 let c1 = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
615 let c2 = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
616 let pid = std::process::id();
617 let name1 = format!("__bsql_test_{}_{}", pid, c1);
618 let name2 = format!("__bsql_test_{}_{}", pid, c2);
619 let counter1: u64 = name1.rsplit('_').next().unwrap().parse().unwrap();
621 let counter2: u64 = name2.rsplit('_').next().unwrap().parse().unwrap();
622 assert!(counter2 > counter1);
623 }
624
625 #[tokio::test]
630 async fn bsql_database_url_takes_priority_over_database_url() {
631 let orig_bsql = std::env::var("BSQL_DATABASE_URL").ok();
632 let orig_db = std::env::var("DATABASE_URL").ok();
633
634 std::env::set_var("BSQL_DATABASE_URL", "not-postgres-bsql");
637 std::env::set_var("DATABASE_URL", "postgres://user:pass@127.0.0.1:1/realdb");
638
639 let result = setup_test_schema(&[]).await;
640 assert!(result.is_err());
641 let msg = result.unwrap_err().to_string();
642 assert!(
644 msg.contains("invalid database URL"),
645 "BSQL_DATABASE_URL should take priority, got: {msg}"
646 );
647
648 std::env::remove_var("BSQL_DATABASE_URL");
650 std::env::remove_var("DATABASE_URL");
651 if let Some(v) = orig_bsql {
652 std::env::set_var("BSQL_DATABASE_URL", v);
653 }
654 if let Some(v) = orig_db {
655 std::env::set_var("DATABASE_URL", v);
656 }
657 }
658
659 #[test]
664 fn pg_schema_names_100_unique_across_threads() {
665 use std::sync::Arc;
666 let results: Arc<std::sync::Mutex<Vec<String>>> =
667 Arc::new(std::sync::Mutex::new(Vec::new()));
668 let handles: Vec<_> = (0..100)
669 .map(|_| {
670 let results = Arc::clone(&results);
671 std::thread::spawn(move || {
672 let name = format!(
673 "__bsql_test_{}_{}",
674 std::process::id(),
675 TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
676 );
677 results.lock().unwrap().push(name);
678 })
679 })
680 .collect();
681 for h in handles {
682 h.join().unwrap();
683 }
684 let names = results.lock().unwrap();
685 let unique: HashSet<&String> = names.iter().collect();
686 assert_eq!(
687 unique.len(),
688 100,
689 "all 100 schema names must be unique across threads"
690 );
691 }
692
693 #[test]
698 fn test_context_debug_format_matches_pattern() {
699 let schema = "__bsql_test_99999_42";
703 let expected = format!("TestContext {{ schema: {:?} }}", schema);
704 assert!(expected.starts_with("TestContext { schema: \""));
706 assert!(expected.ends_with("\" }"));
707 assert!(expected.contains("__bsql_test_99999_42"));
708 }
709
710 #[cfg(feature = "sqlite")]
715 mod sqlite_tests {
716 use super::super::*;
717
718 #[test]
719 fn sqlite_test_context_creates_file() {
720 let ctx = setup_sqlite_test(&["CREATE TABLE t (id INTEGER PRIMARY KEY)"]).unwrap();
721 assert!(ctx.db_path.exists());
722 }
723
724 #[test]
725 fn sqlite_test_context_drop_removes_file() {
726 let path;
727 {
728 let ctx = setup_sqlite_test(&[]).unwrap();
729 path = ctx.db_path.clone();
730 assert!(path.exists());
731 }
732 assert!(!path.exists(), "temp db should be deleted on drop");
734 }
735
736 #[test]
737 fn sqlite_fixtures_applied() {
738 let ctx = setup_sqlite_test(&[
739 "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
740 "INSERT INTO users (name) VALUES ('Alice')",
741 ])
742 .unwrap();
743 let sql = "SELECT name FROM users";
745 let hash = crate::rapid_hash_str(sql);
746 let (result, arena) = ctx
747 .pool
748 .query_readonly(sql, hash, smallvec::SmallVec::new())
749 .unwrap();
750 assert_eq!(result.len(), 1);
751 assert_eq!(result.get_str(0, 0, &arena), Some("Alice"));
752 }
753
754 #[test]
755 fn sqlite_unique_paths() {
756 let ctx1 = setup_sqlite_test(&[]).unwrap();
757 let ctx2 = setup_sqlite_test(&[]).unwrap();
758 assert_ne!(ctx1.db_path, ctx2.db_path);
759 }
760
761 #[test]
762 fn sqlite_empty_fixture_works() {
763 let ctx = setup_sqlite_test(&[""]).unwrap();
764 assert!(ctx.db_path.exists());
765 }
766
767 #[test]
768 fn sqlite_multiple_fixtures_order() {
769 let ctx = setup_sqlite_test(&[
770 "CREATE TABLE t (id INTEGER PRIMARY KEY, val TEXT)",
771 "INSERT INTO t (val) VALUES ('first')",
772 "INSERT INTO t (val) VALUES ('second')",
773 ])
774 .unwrap();
775 let sql = "SELECT val FROM t ORDER BY id";
776 let hash = crate::rapid_hash_str(sql);
777 let (result, arena) = ctx
778 .pool
779 .query_readonly(sql, hash, smallvec::SmallVec::new())
780 .unwrap();
781 assert_eq!(result.len(), 2);
782 assert_eq!(result.get_str(0, 0, &arena), Some("first"));
783 assert_eq!(result.get_str(1, 0, &arena), Some("second"));
784 }
785
786 #[test]
787 fn sqlite_fixture_error_propagates() {
788 let result = setup_sqlite_test(&["NOT VALID SQL AT ALL !@#"]);
789 assert!(result.is_err(), "bad SQL should propagate as Err");
790 }
791
792 #[test]
793 fn sqlite_wal_shm_cleaned() {
794 let path;
795 {
796 let ctx = setup_sqlite_test(&[
797 "CREATE TABLE t (id INTEGER PRIMARY KEY)",
798 "INSERT INTO t VALUES (1)",
799 ])
800 .unwrap();
801 path = ctx.db_path.clone();
802 }
803 assert!(
805 !std::path::Path::new(&format!("{}-wal", path.display())).exists(),
806 "WAL file should be removed"
807 );
808 assert!(
809 !std::path::Path::new(&format!("{}-shm", path.display())).exists(),
810 "SHM file should be removed"
811 );
812 }
813
814 #[test]
815 fn sqlite_whitespace_only_fixture_skipped() {
816 let ctx = setup_sqlite_test(&[" \n\t "]).unwrap();
818 assert!(ctx.db_path.exists());
819 }
820
821 #[test]
822 fn sqlite_path_contains_pid() {
823 let ctx = setup_sqlite_test(&[]).unwrap();
824 let path_str = ctx.db_path.to_string_lossy().to_string();
825 assert!(
826 path_str.contains(&std::process::id().to_string()),
827 "path should contain PID: {path_str}"
828 );
829 }
830
831 #[test]
832 fn sqlite_path_has_db_extension() {
833 let ctx = setup_sqlite_test(&[]).unwrap();
834 let path_str = ctx.db_path.to_string_lossy().to_string();
835 assert!(
836 path_str.ends_with(".db"),
837 "path should end with .db: {path_str}"
838 );
839 }
840
841 #[test]
846 fn sqlite_cleanup_on_panic() {
847 use std::sync::Arc;
848 use std::sync::Mutex;
849
850 let captured_path = Arc::new(Mutex::new(None));
851 let path_clone = captured_path.clone();
852
853 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
854 let ctx = setup_sqlite_test(&["CREATE TABLE t (id INTEGER)"]).unwrap();
855 *path_clone.lock().unwrap() = Some(ctx.db_path.clone());
856 panic!("simulated failure");
857 }));
858
859 assert!(result.is_err());
860 let path = captured_path.lock().unwrap().clone().unwrap();
861 assert!(
863 !path.exists(),
864 "temp file should be cleaned even after panic"
865 );
866 }
867
868 #[test]
873 fn sqlite_drop_with_open_file_handle() {
874 let ctx = setup_sqlite_test(&[]).unwrap();
876 let path = ctx.db_path.clone();
877 drop(ctx);
879 let _ = path;
882 }
883
884 #[test]
889 fn sqlite_setup_with_invalid_sql_propagates_error() {
890 let result = setup_sqlite_test(&["NOT VALID SQL AT ALL !!!"]);
892 assert!(result.is_err());
893 }
898
899 #[test]
904 fn sqlite_concurrent_100_temp_files() {
905 let handles: Vec<_> = (0..100)
906 .map(|_| {
907 std::thread::spawn(|| {
908 let ctx = setup_sqlite_test(&[
909 "CREATE TABLE t (id INTEGER PRIMARY KEY)",
910 "INSERT INTO t VALUES (1)",
911 ])
912 .unwrap();
913 let path = ctx.db_path.clone();
914 assert!(path.exists());
915 drop(ctx);
917 assert!(!path.exists());
918 path
919 })
920 })
921 .collect();
922
923 let paths: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
924
925 let unique: std::collections::HashSet<_> = paths.iter().collect();
927 assert_eq!(unique.len(), 100, "all 100 paths should be unique");
928 }
929
930 #[test]
935 fn sqlite_error_message_is_descriptive() {
936 let result = setup_sqlite_test(&["INVALID SQL"]);
937 match result {
938 Err(e) => {
939 let msg = e.to_string();
940 assert!(
941 msg.contains("fixture"),
942 "error should mention fixture: {msg}"
943 );
944 }
945 Ok(_) => panic!("should have failed"),
946 }
947 }
948
949 #[test]
954 fn sqlite_fixtures_order_dependent_with_fk() {
955 let ctx = setup_sqlite_test(&[
957 "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
958 "CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER REFERENCES users(id))",
959 "INSERT INTO users VALUES (1, 'Alice')",
960 "INSERT INTO orders VALUES (1, 1)",
961 ])
962 .unwrap();
963 assert!(ctx.db_path.exists());
965 }
966
967 #[test]
972 fn sqlite_large_fixture() {
973 let mut sql = String::from("CREATE TABLE big (id INTEGER PRIMARY KEY, data TEXT);\n");
974 for i in 0..1000 {
975 sql.push_str(&format!("INSERT INTO big VALUES ({i}, 'row_{i}');\n"));
976 }
977 let ctx = setup_sqlite_test(&[&sql]).unwrap();
978 assert!(ctx.db_path.exists());
979 }
980
981 #[test]
986 fn sqlite_fixture_with_pragma() {
987 let ctx = setup_sqlite_test(&[
988 "PRAGMA foreign_keys = ON",
989 "CREATE TABLE t (id INTEGER PRIMARY KEY)",
990 ])
991 .unwrap();
992 assert!(ctx.db_path.exists());
993 }
994 }
995}