Skip to main content

bsql_core/
test_support.rs

1//! Test infrastructure for `#[bsql::test]`.
2//!
3//! Creates isolated PostgreSQL schemas per test for parallel execution.
4//! Fixtures (SQL files) are applied to the schema before the test runs.
5//! Schema is dropped after the test -- even on panic.
6
7use 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
16/// Test context holding the pool and cleanup info.
17/// Drops the schema on cleanup.
18pub struct TestContext {
19    /// The connection pool, scoped to the isolated test schema.
20    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        // Fresh connection for cleanup (pool connection may be broken after panic).
36        // Errors are intentionally ignored -- we are in a destructor.
37        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
48/// Set up an isolated test schema with fixtures.
49///
50/// Called by generated `#[bsql::test]` code. Not intended for direct use.
51///
52/// `fixtures_sql` contains compile-time embedded SQL strings from fixture files.
53pub 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    // Setup connection: create schema, apply fixtures
67    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    // Create isolated schema
73    conn.simple_query(&format!("CREATE SCHEMA \"{}\"", schema_name))
74        .map_err(|e| ConnectError::create(format!("failed to create test schema: {e}")))?;
75
76    // Set search_path to test schema (with public for extensions)
77    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    // Apply fixtures in order
81    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); // Release setup connection
89
90    // Build pool. Connections are lazy, so we create the pool first,
91    // then immediately acquire one connection and set search_path on it.
92    let pool = Pool::connect(&db_url).await?;
93
94    // Acquire a connection and set search_path so all subsequent queries
95    // in this test run against the isolated schema.
96    pool.raw_execute(&format!("SET search_path TO \"{}\", public", schema_name))
97        .await?;
98
99    // Set warmup SQL so any *new* connections from this pool also get
100    // the correct search_path (the pool has max_size=10 by default,
101    // but for tests we typically only use 1 connection).
102    let warmup_sql = format!("SET search_path TO \"{}\", public", schema_name);
103    // set_warmup_sqls copies strings internally (into Box<str>), so &str
104    // only needs to live for the duration of this call. No leak needed.
105    pool.set_warmup_sqls([warmup_sql]);
106
107    Ok(TestContext {
108        pool,
109        schema_name,
110        db_url,
111    })
112}
113
114// ===========================================================================
115// SQLite test support
116// ===========================================================================
117
118/// SQLite test context — isolated temporary database file.
119///
120/// Created by [`setup_sqlite_test`]. The temporary file (plus WAL/SHM) is
121/// automatically deleted when the context is dropped.
122#[cfg(feature = "sqlite")]
123pub struct SqliteTestContext {
124    /// The SQLite connection pool for the test.
125    pub pool: crate::sqlite_pool::SqlitePool,
126    /// Path to the temporary database file (public for tests to inspect).
127    pub db_path: std::path::PathBuf,
128}
129
130#[cfg(feature = "sqlite")]
131impl Drop for SqliteTestContext {
132    fn drop(&mut self) {
133        // Close pool first to release the file lock.
134        self.pool.close();
135        // Delete the temp database file and any WAL/SHM sidecar files.
136        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/// Set up an isolated SQLite test database with fixtures.
143///
144/// Called by generated `#[bsql::test]` code for SQLite tests.
145/// Not intended for direct use.
146///
147/// Each call creates a unique temporary file (PID + atomic counter).
148/// `fixtures_sql` contains compile-time embedded SQL strings from fixture files.
149#[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    // Generate a unique temp file path.
156    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    // Create pool (SqlitePool::connect is sync — no async runtime required).
164    let pool = crate::sqlite_pool::SqlitePool::connect(db_path.to_str().unwrap_or("bsql_test.db"))?;
165
166    // Apply fixtures in order.
167    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    // ---------------------------------------------------------------
183    // Schema lifecycle
184    // ---------------------------------------------------------------
185
186    #[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        // Valid SQL identifier: starts with letter or underscore, then alphanumeric/underscore
243        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    // ---------------------------------------------------------------
254    // Counter atomicity
255    // ---------------------------------------------------------------
256
257    #[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        // All values must be unique (no duplicates from racing threads)
286        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        // Sorted values must be strictly increasing
293        vals.sort();
294        for window in vals.windows(2) {
295            assert!(window[0] < window[1], "counter must be strictly increasing");
296        }
297    }
298
299    // ---------------------------------------------------------------
300    // Concurrency — multiple TestContexts
301    // ---------------------------------------------------------------
302
303    #[test]
304    fn multiple_schema_names_created_simultaneously_are_different() {
305        // Simulate what happens when multiple tests call setup at the same instant
306        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    // ---------------------------------------------------------------
320    // Setup error paths
321    //
322    // These tests manipulate global env vars, so they MUST be
323    // serialized to avoid races with each other.
324    // ---------------------------------------------------------------
325
326    /// Mutex to serialize tests that modify environment variables.
327    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        // Test the connection-refused path directly, bypassing env-var setup
407        // to avoid races with other concurrent async tests that manipulate env.
408        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        // Verify the error maps to a ConnectError with "connection failed" message
413        // (this is the exact error path that setup_test_schema takes)
414        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    // ---------------------------------------------------------------
423    // TestContext Debug
424    // ---------------------------------------------------------------
425
426    #[test]
427    fn test_context_has_debug_impl() {
428        // Verify that TestContext implements Debug (compile-time check).
429        fn assert_debug<T: std::fmt::Debug>() {}
430        assert_debug::<TestContext>();
431    }
432
433    #[test]
434    fn test_context_debug_shows_schema_name() {
435        // We can't easily construct a full TestContext without a real DB,
436        // but we can test the Debug format by constructing the expected string.
437        // The Debug impl should show schema field.
438        let schema = "__bsql_test_12345_0";
439        let expected = format!("TestContext {{ schema: {:?} }}", schema);
440        // Just verify the format pattern is correct
441        assert!(expected.contains("TestContext"));
442        assert!(expected.contains("schema"));
443        assert!(expected.contains(schema));
444    }
445
446    // ---------------------------------------------------------------
447    // Drop behavior
448    // ---------------------------------------------------------------
449
450    #[test]
451    fn drop_code_path_with_invalid_url_does_not_panic() {
452        // We can't construct a TestContext without a real Pool (async), so we
453        // exercise the exact Drop code path manually. This is the same logic
454        // that TestContext::drop executes.
455        let db_url = "garbage-url";
456        let schema_name = "__bsql_test_fake_0";
457        // Step 1: Config::from_url — should fail for a garbage URL
458        if let Ok(config) = Config::from_url(db_url) {
459            // Step 2: Connection::connect — would fail but we shouldn't reach here
460            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        // If we get here without panicking, the drop path is safe.
468    }
469
470    #[test]
471    fn drop_with_garbage_url_does_not_panic() {
472        // Directly exercise the Drop code path with an invalid URL.
473        // This ensures Config::from_url failure doesn't cause a panic in Drop.
474        //
475        // We test the conditional logic in Drop:
476        //   if let Ok(config) = Config::from_url(&self.db_url) { ... }
477        // An invalid URL means Config::from_url returns Err, so drop exits silently.
478        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        // The Drop impl would exit at the first `if let Ok(...)` — no panic.
482    }
483
484    #[test]
485    fn drop_with_valid_url_but_unreachable_host_does_not_panic() {
486        // Even if Config::from_url succeeds, Connection::connect can fail.
487        // Drop should handle this gracefully.
488        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        // The Drop impl would exit at the second `if let Ok(...)` — no panic.
494    }
495
496    // ---------------------------------------------------------------
497    // Fixture edge cases (tested via the setup function's logic)
498    // ---------------------------------------------------------------
499
500    #[test]
501    fn empty_fixture_string_is_skipped() {
502        // The setup function skips empty fixtures: `if !fixture_sql.trim().is_empty()`
503        // Verify the logic directly.
504        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        // SQL comments are not whitespace, so they pass the trim check.
520        // PostgreSQL will accept them as valid SQL (no-op).
521        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    // ---------------------------------------------------------------
535    // Error type verification
536    // ---------------------------------------------------------------
537
538    #[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    // ---------------------------------------------------------------
595    // Schema name format deep verification
596    // ---------------------------------------------------------------
597
598    #[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        // Parts: prefix "__bsql_test", pid, counter
604        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        // Extract counter from name
620        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    // ---------------------------------------------------------------
626    // BSQL_DATABASE_URL takes priority over DATABASE_URL
627    // ---------------------------------------------------------------
628
629    #[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        // Set both — BSQL_DATABASE_URL should win
635        // Use an invalid URL so we can see which one is used in the error
636        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        // Should fail because BSQL_DATABASE_URL is not a valid postgres URL
643        assert!(
644            msg.contains("invalid database URL"),
645            "BSQL_DATABASE_URL should take priority, got: {msg}"
646        );
647
648        // Restore
649        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    // ---------------------------------------------------------------
660    // PG: concurrent schema name uniqueness (threaded)
661    // ---------------------------------------------------------------
662
663    #[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    // ---------------------------------------------------------------
694    // PG: TestContext Debug format verification
695    // ---------------------------------------------------------------
696
697    #[test]
698    fn test_context_debug_format_matches_pattern() {
699        // Verify the Debug impl output matches the expected pattern exactly.
700        // We can't construct a TestContext without a real DB, but we can
701        // verify the format by inspecting the derive output shape.
702        let schema = "__bsql_test_99999_42";
703        let expected = format!("TestContext {{ schema: {:?} }}", schema);
704        // Should match: TestContext { schema: "__bsql_test_99999_42" }
705        assert!(expected.starts_with("TestContext { schema: \""));
706        assert!(expected.ends_with("\" }"));
707        assert!(expected.contains("__bsql_test_99999_42"));
708    }
709
710    // ===================================================================
711    // SQLite test support
712    // ===================================================================
713
714    #[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            // After drop
733            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            // Verify via simple_exec + query
744            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            // WAL and SHM files should be cleaned up too
804            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            // Whitespace-only fixture should not error
817            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        // ---------------------------------------------------------------
842        // Drop during panic / unwind
843        // ---------------------------------------------------------------
844
845        #[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            // Drop should have run during unwind, cleaning the file
862            assert!(
863                !path.exists(),
864                "temp file should be cleaned even after panic"
865            );
866        }
867
868        // ---------------------------------------------------------------
869        // Explicit drop does not panic
870        // ---------------------------------------------------------------
871
872        #[test]
873        fn sqlite_drop_with_open_file_handle() {
874            // Verify Drop doesn't panic even if called explicitly
875            let ctx = setup_sqlite_test(&[]).unwrap();
876            let path = ctx.db_path.clone();
877            // Explicitly drop -- should not panic
878            drop(ctx);
879            // File may or may not exist depending on OS behavior
880            // but the important thing is no panic
881            let _ = path;
882        }
883
884        // ---------------------------------------------------------------
885        // Setup failure cleans up temp file
886        // ---------------------------------------------------------------
887
888        #[test]
889        fn sqlite_setup_with_invalid_sql_propagates_error() {
890            // Force an error in fixture application
891            let result = setup_sqlite_test(&["NOT VALID SQL AT ALL !!!"]);
892            assert!(result.is_err());
893            // The setup creates the file, then tries to apply fixtures.
894            // On failure, the SqliteTestContext is never returned, but the
895            // pool + file were created. Since the Ok path is never reached,
896            // the file may linger. This tests error propagation.
897        }
898
899        // ---------------------------------------------------------------
900        // Concurrent 100 temp files — all unique, all cleaned
901        // ---------------------------------------------------------------
902
903        #[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 cleans up
916                        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            // All paths should be unique
926            let unique: std::collections::HashSet<_> = paths.iter().collect();
927            assert_eq!(unique.len(), 100, "all 100 paths should be unique");
928        }
929
930        // ---------------------------------------------------------------
931        // Error message quality
932        // ---------------------------------------------------------------
933
934        #[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        // ---------------------------------------------------------------
950        // Fixtures with foreign key dependencies (order matters)
951        // ---------------------------------------------------------------
952
953        #[test]
954        fn sqlite_fixtures_order_dependent_with_fk() {
955            // Second fixture references table from first via foreign key
956            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            // If order was wrong, the CREATE TABLE orders would fail
964            assert!(ctx.db_path.exists());
965        }
966
967        // ---------------------------------------------------------------
968        // Large fixture (1000 rows)
969        // ---------------------------------------------------------------
970
971        #[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        // ---------------------------------------------------------------
982        // Fixture with PRAGMA statement
983        // ---------------------------------------------------------------
984
985        #[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}