testkit-core 0.1.1

Core utilities for testkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;

use crate::DatabasePool;
use crate::TestContext;
use crate::handlers::TransactionHandler;
use crate::testdb::DatabaseBackend;
use crate::testdb::DatabaseConfig;
use async_trait::async_trait;

// Type aliases to simplify complex types
/// Type for a boxed setup function that can be executed on a database pool connection
pub type BoxedSetupFn<DB> = Box<
    dyn for<'a> FnOnce(
            &'a mut <<DB as DatabaseBackend>::Pool as crate::DatabasePool>::Connection,
        ) -> Pin<
            Box<dyn Future<Output = Result<(), <DB as DatabaseBackend>::Error>> + Send + 'a>,
        > + Send
        + Sync,
>;

/// Type for a boxed transaction function that can be executed on a database connection
pub type BoxedTransactionFn<DB> = Box<
    dyn for<'a> FnOnce(
            &'a mut <DB as DatabaseBackend>::Connection,
        ) -> Pin<
            Box<dyn Future<Output = Result<(), <DB as DatabaseBackend>::Error>> + Send + 'a>,
        > + Send
        + Sync,
>;

/// Entry point for database operations with automatic boxing of closures
///
/// This provides functionality for database operations with automatic boxing
/// of future closures to solve lifetime issues. Use the `boxed_async!` macro
/// to easily create boxed async blocks.
pub struct BoxedDatabaseEntryPoint<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    backend: DB,
}

/// Handler that stores a setup function
pub struct BoxedSetupHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    backend: DB,
    setup_fn: BoxedSetupFn<DB>,
}

/// Handler that stores both setup and transaction functions
pub struct BoxedTransactionHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    backend: DB,
    setup_fn: BoxedSetupFn<DB>,
    transaction_fn: BoxedTransactionFn<DB>,
}

/// Handler that stores just a transaction function without setup
pub struct BoxedTransactionOnlyHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    backend: DB,
    transaction_fn: BoxedTransactionFn<DB>,
}

impl<DB> BoxedDatabaseEntryPoint<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    /// Create a new entry point with the given backend
    pub fn new(backend: DB) -> Self {
        Self { backend }
    }

    /// Set up the database with the given function
    ///
    /// This method takes a closure that will be executed during setup.
    /// Use the `boxed_async!` macro to create an async block that captures
    /// variables without lifetime issues.
    pub fn setup<F>(self, setup_fn: F) -> BoxedSetupHandler<DB>
    where
        F: for<'a> FnOnce(
                &'a mut <DB::Pool as crate::DatabasePool>::Connection,
            )
                -> Pin<Box<dyn Future<Output = Result<(), DB::Error>> + Send + 'a>>
            + Send
            + Sync
            + 'static,
    {
        BoxedSetupHandler {
            backend: self.backend,
            setup_fn: Box::new(setup_fn),
        }
    }

    /// Initialize a database with a transaction
    pub fn with_transaction<F>(self, transaction_fn: F) -> BoxedTransactionOnlyHandler<DB>
    where
        F: for<'a> FnOnce(
                &'a mut <DB as DatabaseBackend>::Connection,
            )
                -> Pin<Box<dyn Future<Output = Result<(), DB::Error>> + Send + 'a>>
            + Send
            + Sync
            + 'static,
    {
        BoxedTransactionOnlyHandler {
            backend: self.backend,
            transaction_fn: Box::new(transaction_fn),
        }
    }

    /// Execute this handler
    pub async fn execute(self) -> Result<crate::TestContext<DB>, DB::Error> {
        // Create the database instance
        let db_instance =
            crate::testdb::TestDatabaseInstance::new(self.backend, DatabaseConfig::default())
                .await?;

        // Create and return the context
        Ok(crate::TestContext::new(db_instance))
    }

    /// Add an async setup function without requiring boxed_async
    ///
    /// This method provides a more ergonomic API without requiring manual boxing
    pub fn setup_async<F, Fut>(self, setup_fn: F) -> BoxedSetupHandler<DB>
    where
        F: FnOnce(&mut <DB::Pool as DatabasePool>::Connection) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), DB::Error>> + Send + 'static,
    {
        self.setup(move |conn| {
            Box::pin(setup_fn(conn))
                as Pin<Box<dyn Future<Output = Result<(), DB::Error>> + Send + '_>>
        })
    }

    /// Add a transaction function without requiring boxed_async
    ///
    /// This method provides a more ergonomic API without requiring manual boxing
    pub fn transaction<F, Fut>(self, transaction_fn: F) -> BoxedTransactionOnlyHandler<DB>
    where
        F: FnOnce(&mut <DB as DatabaseBackend>::Connection) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), DB::Error>> + Send + 'static,
    {
        self.with_transaction(move |conn| {
            Box::pin(transaction_fn(conn))
                as Pin<Box<dyn Future<Output = Result<(), DB::Error>> + Send + '_>>
        })
    }

    /// Run the handler
    ///
    /// This is an alias for execute() with a more intuitive name
    pub async fn run(self) -> Result<crate::TestContext<DB>, DB::Error> {
        self.execute().await
    }
}

#[async_trait]
impl<DB> TransactionHandler<DB> for BoxedDatabaseEntryPoint<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    type Item = TestContext<DB>;
    type Error = DB::Error;

    async fn execute(self, _ctx: &mut TestContext<DB>) -> Result<Self::Item, Self::Error> {
        // Create the database instance
        let db_instance =
            crate::testdb::TestDatabaseInstance::new(self.backend, DatabaseConfig::default())
                .await?;

        // Create and return the context
        Ok(crate::TestContext::new(db_instance))
    }
}

impl<DB> BoxedTransactionOnlyHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    /// Execute this handler
    pub async fn execute(self) -> Result<crate::TestContext<DB>, DB::Error> {
        // Create the database instance
        let db_instance =
            crate::testdb::TestDatabaseInstance::new(self.backend, DatabaseConfig::default())
                .await?;

        // Create the context
        let ctx = crate::TestContext::new(db_instance.clone());

        // TRANSACTION: Get a connection for the transaction
        let mut conn = ctx.db.pool.acquire().await?;

        // Call the transaction function with a reference to the connection
        (self.transaction_fn)(&mut conn).await?;

        // Release the connection
        ctx.db.pool.release(conn).await?;

        // Return the context
        Ok(ctx)
    }

    /// Run the handler
    ///
    /// This is an alias for execute() with a more intuitive name
    pub async fn run(self) -> Result<crate::TestContext<DB>, DB::Error> {
        self.execute().await
    }
}

#[async_trait]
impl<DB> TransactionHandler<DB> for BoxedTransactionOnlyHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    type Item = TestContext<DB>;
    type Error = DB::Error;

    async fn execute(self, _ctx: &mut TestContext<DB>) -> Result<Self::Item, Self::Error> {
        self.execute().await
    }
}

impl<DB> BoxedSetupHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    /// Add a transaction function
    ///
    /// This method takes a closure that will be executed during transaction.
    /// Use the `boxed_async!` macro to create an async block that captures
    /// variables without lifetime issues.
    pub fn with_transaction<F>(self, transaction_fn: F) -> BoxedTransactionHandler<DB>
    where
        F: for<'a> FnOnce(
                &'a mut <DB as DatabaseBackend>::Connection,
            )
                -> Pin<Box<dyn Future<Output = Result<(), DB::Error>> + Send + 'a>>
            + Send
            + Sync
            + 'static,
    {
        BoxedTransactionHandler {
            backend: self.backend,
            setup_fn: self.setup_fn,
            transaction_fn: Box::new(transaction_fn),
        }
    }

    /// Execute this handler
    pub async fn execute(self) -> Result<crate::TestContext<DB>, DB::Error> {
        // Create the database instance
        let db_instance =
            crate::testdb::TestDatabaseInstance::new(self.backend, DatabaseConfig::default())
                .await?;

        // Create the context
        let ctx = crate::TestContext::new(db_instance);

        // Get a connection from the pool
        let mut conn = ctx.db.pool.acquire().await?;

        // Call the setup function with a reference to the connection
        (self.setup_fn)(&mut conn).await?;

        // Release the connection back to the pool
        ctx.db.pool.release(conn).await?;

        // Return the context
        Ok(ctx)
    }

    /// Add a transaction function without requiring boxed_async
    ///
    /// This method provides a more ergonomic API without requiring manual boxing
    pub fn transaction<F, Fut>(self, transaction_fn: F) -> BoxedTransactionHandler<DB>
    where
        F: FnOnce(&mut <DB as DatabaseBackend>::Connection) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), DB::Error>> + Send + 'static,
    {
        self.with_transaction(move |conn| {
            Box::pin(transaction_fn(conn))
                as Pin<Box<dyn Future<Output = Result<(), DB::Error>> + Send + '_>>
        })
    }

    /// Run the handler
    ///
    /// This is an alias for execute() with a more intuitive name
    pub async fn run(self) -> Result<crate::TestContext<DB>, DB::Error> {
        self.execute().await
    }
}

#[async_trait]
impl<DB> TransactionHandler<DB> for BoxedSetupHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    type Item = TestContext<DB>;
    type Error = DB::Error;

    async fn execute(self, _ctx: &mut TestContext<DB>) -> Result<Self::Item, Self::Error> {
        self.execute().await
    }
}

impl<DB> BoxedTransactionHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    /// Execute this handler
    pub async fn execute(self) -> Result<crate::TestContext<DB>, DB::Error> {
        // Create the database instance
        let db_instance =
            crate::testdb::TestDatabaseInstance::new(self.backend, DatabaseConfig::default())
                .await?;

        // Create the context
        let ctx = crate::TestContext::new(db_instance);

        // SETUP: Get a connection from the pool
        let mut conn = ctx.db.pool.acquire().await?;

        // Call the setup function with a reference to the connection
        (self.setup_fn)(&mut conn).await?;

        // Release the connection back to the pool
        ctx.db.pool.release(conn).await?;

        // TRANSACTION: Get a new connection for the transaction
        let mut conn = ctx.db.pool.acquire().await?;

        // Call the transaction function with a reference to the connection
        (self.transaction_fn)(&mut conn).await?;

        // Release the connection
        ctx.db.pool.release(conn).await?;

        // Return the context
        Ok(ctx)
    }

    /// Run the handler
    ///
    /// This is an alias for execute() with a more intuitive name
    pub async fn run(self) -> Result<crate::TestContext<DB>, DB::Error> {
        self.execute().await
    }
}

#[async_trait]
impl<DB> TransactionHandler<DB> for BoxedTransactionHandler<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    type Item = TestContext<DB>;
    type Error = DB::Error;

    async fn execute(self, _ctx: &mut TestContext<DB>) -> Result<Self::Item, Self::Error> {
        self.execute().await
    }
}

/// Create a new database entry point with the given backend
///
/// This function creates a new entry point for working with databases.
/// Use the `boxed_async!` macro with `setup` and `with_transaction` to avoid lifetime issues.
pub fn with_boxed_database<DB>(backend: DB) -> BoxedDatabaseEntryPoint<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    BoxedDatabaseEntryPoint::new(backend)
}

/// Create a new database entry point with the given backend and config
///
/// This function creates a new entry point for working with databases.
/// Use the `boxed_async!` macro with `setup` and `with_transaction` to avoid lifetime issues.
pub fn with_boxed_database_config<DB>(
    backend: DB,
    _config: DatabaseConfig,
) -> BoxedDatabaseEntryPoint<DB>
where
    DB: DatabaseBackend + Send + Sync + Debug + 'static,
{
    BoxedDatabaseEntryPoint::new(backend)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testdb::TestDatabaseConnection;

    #[derive(Debug, Clone)]
    struct MockError(String);

    impl std::fmt::Display for MockError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "Mock error: {}", self.0)
        }
    }

    impl std::error::Error for MockError {}

    impl From<String> for MockError {
        fn from(s: String) -> Self {
            MockError(s)
        }
    }

    #[derive(Debug, Clone)]
    struct MockConnection;

    impl TestDatabaseConnection for MockConnection {
        fn connection_string(&self) -> String {
            "mock://test".to_string()
        }
    }

    #[derive(Debug, Clone)]
    struct MockPool;

    #[async_trait]
    impl crate::DatabasePool for MockPool {
        type Connection = MockConnection;
        type Error = MockError;

        async fn acquire(&self) -> Result<Self::Connection, Self::Error> {
            Ok(MockConnection)
        }

        async fn release(&self, _conn: Self::Connection) -> Result<(), Self::Error> {
            Ok(())
        }

        fn connection_string(&self) -> String {
            "mock://test".to_string()
        }
    }

    #[derive(Debug, Clone)]
    struct MockBackend;

    impl MockBackend {
        fn new() -> Self {
            MockBackend
        }
    }

    #[async_trait]
    impl crate::DatabaseBackend for MockBackend {
        type Connection = MockConnection;
        type Pool = MockPool;
        type Error = MockError;

        async fn new(_config: crate::DatabaseConfig) -> Result<Self, Self::Error> {
            Ok(Self)
        }

        async fn connect(
            &self,
            _name: &crate::DatabaseName,
        ) -> Result<Self::Connection, Self::Error> {
            Ok(MockConnection)
        }

        async fn connect_with_string(
            &self,
            _connection_string: &str,
        ) -> Result<Self::Connection, Self::Error> {
            Ok(MockConnection)
        }

        async fn create_pool(
            &self,
            _name: &crate::DatabaseName,
            _config: &crate::DatabaseConfig,
        ) -> Result<Self::Pool, Self::Error> {
            Ok(MockPool)
        }

        async fn create_database(
            &self,
            _pool: &Self::Pool,
            _name: &crate::DatabaseName,
        ) -> Result<(), Self::Error> {
            Ok(())
        }

        fn drop_database(&self, _name: &crate::DatabaseName) -> Result<(), Self::Error> {
            Ok(())
        }

        fn connection_string(&self, _name: &crate::DatabaseName) -> String {
            "mock://test".to_string()
        }
    }

    #[tokio::test]
    async fn test_boxed_database() {
        let backend = MockBackend::new();

        // Example with boxed_async macro
        let ctx = with_boxed_database(backend)
            .setup(|_conn| {
                crate::boxed_async!(async move {
                    // Use the connection to set up the database
                    Ok(())
                })
            })
            .with_transaction(|_conn| {
                crate::boxed_async!(async move {
                    // Use the connection to run a transaction
                    Ok(())
                })
            })
            .execute()
            .await;

        assert!(ctx.is_ok());
    }
}