fabrique-derive 0.4.0

Derive macros for Fabrique
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Code generation for `#[fabrique::test]` and `#[fabrique::doctest]`.
//!
//! Parses an async test function, detects the database backend from
//! the `Pool<T>` parameter, and generates a `#[tokio::test]` function
//! that creates a temporary pool with migrations applied.

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{
    FnArg, GenericArgument, GenericParam, Generics, Ident, ItemFn, Pat, PathArguments, Type,
};

// ── Analysis ────────────────────────────────────────────────────

/// A concrete database backend.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConcreteBackend {
    Sqlite,
    Postgres,
    MySql,
}

/// Database backend detected from the `Pool<T>` parameter type.
#[derive(Debug, PartialEq)]
pub enum Backend {
    Concrete(ConcreteBackend),
    /// Generic backend from `<DB: Dialect>`. Generates one test
    /// per backend, each cfg-gated by feature.
    Multi(Ident),
}

/// Parsed representation of a `#[fabrique::test]` function.
///
/// Extracts the function name, parameter name, body, and database
/// backend from the function signature.
#[derive(Debug)]
pub struct TestAnalysis {
    pub fn_name: Ident,
    pub param_name: Ident,
    pub body: syn::Block,
    pub backend: Backend,
}

impl TestAnalysis {
    /// Parses an async test function into its components.
    ///
    /// Expects exactly one parameter of type `Pool<Sqlite>`,
    /// `Pool<Postgres>`, `Pool<MySql>`, or `Pool<DB>` where `DB`
    /// is a generic type parameter (multi-backend).
    pub fn try_from_item(input: &ItemFn) -> Result<Self, syn::Error> {
        let fn_name = input.sig.ident.clone();
        let body = (*input.block).clone();

        let param = input.sig.inputs.first().ok_or_else(|| {
            syn::Error::new_spanned(
                &input.sig,
                "expected a pool parameter, \
                 e.g. `pool: Pool<Sqlite>`",
            )
        })?;

        let (param_name, backend) = match param {
            FnArg::Typed(pat_type) => {
                let name = match &*pat_type.pat {
                    Pat::Ident(pi) => pi.ident.clone(),
                    _ => {
                        return Err(syn::Error::new_spanned(
                            &pat_type.pat,
                            "expected a simple identifier",
                        ));
                    }
                };
                let backend = Self::parse_backend(&pat_type.ty, &input.sig.generics)?;
                (name, backend)
            }
            _ => return Err(syn::Error::new_spanned(param, "expected a typed parameter")),
        };

        Ok(Self {
            fn_name,
            param_name,
            body,
            backend,
        })
    }

    /// Extracts the backend variant from a `Pool<T>` type.
    ///
    /// Recognises `Sqlite`, `Postgres`, and `MySql` as the last
    /// segment of the inner type path (e.g. `sqlx::Sqlite`).
    /// If the inner type matches a generic type parameter from the
    /// function signature, returns `Backend::Multi`.
    fn parse_backend(ty: &Type, generics: &Generics) -> Result<Backend, syn::Error> {
        let type_path = match ty {
            Type::Path(tp) => tp,
            _ => {
                return Err(syn::Error::new_spanned(
                    ty,
                    "expected Pool<Sqlite|Postgres|MySql>",
                ));
            }
        };

        let segment = type_path
            .path
            .segments
            .last()
            .ok_or_else(|| syn::Error::new_spanned(ty, "expected Pool<…>"))?;

        if segment.ident != "Pool" {
            return Err(syn::Error::new_spanned(
                &segment.ident,
                "expected Pool type",
            ));
        }

        let args = match &segment.arguments {
            PathArguments::AngleBracketed(a) => a,
            _ => {
                return Err(syn::Error::new_spanned(
                    segment,
                    "expected Pool<…> with angle brackets",
                ));
            }
        };

        let arg = args
            .args
            .first()
            .ok_or_else(|| syn::Error::new_spanned(args, "expected a type argument"))?;

        let inner = match arg {
            GenericArgument::Type(Type::Path(tp)) => tp,
            _ => {
                return Err(syn::Error::new_spanned(
                    arg,
                    "expected a path type argument",
                ));
            }
        };

        let ident = &inner
            .path
            .segments
            .last()
            .ok_or_else(|| syn::Error::new_spanned(inner, "empty path"))?
            .ident;

        match ident.to_string().as_str() {
            "Sqlite" => Ok(Backend::Concrete(ConcreteBackend::Sqlite)),
            "Postgres" => Ok(Backend::Concrete(ConcreteBackend::Postgres)),
            "MySql" => Ok(Backend::Concrete(ConcreteBackend::MySql)),
            _ => {
                let is_generic = generics
                    .params
                    .iter()
                    .any(|p| matches!(p, GenericParam::Type(tp) if tp.ident == *ident));
                if is_generic {
                    Ok(Backend::Multi(ident.clone()))
                } else {
                    Err(syn::Error::new_spanned(
                        ident,
                        format!("unsupported backend: {ident}"),
                    ))
                }
            }
        }
    }
}

// ── Codegen ─────────────────────────────────────────────────────

/// All concrete backends, in generation order.
const CONCRETE_BACKENDS: [ConcreteBackend; 3] = [
    ConcreteBackend::Sqlite,
    ConcreteBackend::Postgres,
    ConcreteBackend::MySql,
];

impl ConcreteBackend {
    /// Feature flag name for cfg-gating.
    fn feature(&self) -> &'static str {
        match self {
            ConcreteBackend::Sqlite => "sqlite",
            ConcreteBackend::Postgres => "postgres",
            ConcreteBackend::MySql => "mysql",
        }
    }

    /// Fully-qualified sqlx type path.
    fn sqlx_type(&self) -> TokenStream {
        match self {
            ConcreteBackend::Sqlite => quote! { ::sqlx::Sqlite },
            ConcreteBackend::Postgres => quote! { ::sqlx::Postgres },
            ConcreteBackend::MySql => quote! { ::sqlx::MySql },
        }
    }
}

/// Generates pool creation tokens for a concrete backend.
fn pool_setup_tokens(backend: &ConcreteBackend, param: &Ident, path: &str) -> TokenStream {
    match backend {
        ConcreteBackend::Sqlite => quote! {
            let #param =
                ::fabrique::__private::create_sqlite_pool(#path)
                    .await
                    .expect("Failed to create test pool");
        },
        ConcreteBackend::Postgres => quote! {
            let (#param, __base_url, __db_name) =
                ::fabrique::__private::create_postgres_pool(#path)
                    .await
                    .expect("Failed to create test pool");
        },
        ConcreteBackend::MySql => quote! {
            let (#param, __base_url, __db_name) =
                ::fabrique::__private::create_mysql_pool(#path)
                    .await
                    .expect("Failed to create test pool");
        },
    }
}

/// Generates cleanup tokens for a concrete backend.
fn cleanup_tokens(backend: &ConcreteBackend, param: &Ident) -> TokenStream {
    match backend {
        ConcreteBackend::Sqlite => quote! {},
        ConcreteBackend::Postgres => quote! {
            drop(#param);
            ::fabrique::__private::cleanup_test_db_postgres(
                &__base_url,
                &__db_name,
            )
            .await;
        },
        ConcreteBackend::MySql => quote! {
            drop(#param);
            ::fabrique::__private::cleanup_test_db_mysql(
                &__base_url,
                &__db_name,
            )
            .await;
        },
    }
}

/// Code generator for `#[fabrique::test]` and `#[fabrique::doctest]`.
///
/// Takes a parsed test function and generates a `#[tokio::test]`
/// wrapper that creates a pool with migrations applied and runs
/// cleanup when needed.
pub struct TestCodegen<'a> {
    analysis: &'a TestAnalysis,
    migration_path: String,
}

impl<'a> TestCodegen<'a> {
    /// Creates a code generator, resolving the migration path
    /// from the workspace root.
    pub fn new(analysis: &'a TestAnalysis) -> Self {
        let migration_path = match &analysis.backend {
            Backend::Multi(_) => String::new(),
            Backend::Concrete(concrete) => Self::resolve_migration_path(concrete),
        };
        Self {
            analysis,
            migration_path,
        }
    }

    /// Creates a code generator with an explicit migration path.
    ///
    /// Useful for testing without filesystem dependency.
    #[cfg(test)]
    fn with_path(analysis: &'a TestAnalysis, path: &str) -> Self {
        Self {
            analysis,
            migration_path: path.to_owned(),
        }
    }

    /// Generates test function(s). For a concrete backend, emits
    /// a single `#[tokio::test]`. For `Multi`, emits one per
    /// backend, each cfg-gated.
    pub fn generate(&self) -> TokenStream {
        match &self.analysis.backend {
            Backend::Multi(type_param) => self.generate_multi(type_param),
            Backend::Concrete(concrete) => self.generate_single(concrete),
        }
    }

    /// Generates a doctest wrapper with a blocking Tokio runtime.
    ///
    /// Unlike `generate()`, this wraps the body in a manual Tokio
    /// runtime since doctests cannot use `#[tokio::test]`.
    /// Multi-backend is not supported for doctests.
    pub fn generate_doctest(&self) -> TokenStream {
        if !matches!(
            self.analysis.backend,
            Backend::Concrete(ConcreteBackend::Sqlite)
        ) {
            return syn::Error::new_spanned(
                &self.analysis.fn_name,
                "#[fabrique::doctest] only supports Sqlite",
            )
            .into_compile_error();
        }

        let body = &self.analysis.body;
        let param = &self.analysis.param_name;
        let path = &self.migration_path;

        quote! {
            fn main() {
                ::tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("Failed to create Tokio runtime")
                    .block_on(async {
                        let #param =
                            ::fabrique::__private::create_sqlite_pool(#path)
                                .await
                                .expect("Failed to create doctest pool");
                        let __result: Result<(), ::fabrique::Error> =
                            async #body .await;
                        __result.expect("Doctest failed");
                    });
            }
        }
    }

    /// Generates a single `#[tokio::test]` for a concrete backend.
    fn generate_single(&self, backend: &ConcreteBackend) -> TokenStream {
        let fn_name = &self.analysis.fn_name;
        let stmts = &self.analysis.body.stmts;
        let param = &self.analysis.param_name;
        let setup = pool_setup_tokens(backend, param, &self.migration_path);
        let cleanup = cleanup_tokens(backend, param);

        quote! {
            #[::tokio::test]
            async fn #fn_name() {
                #setup
                #(#stmts)*
                #cleanup
            }
        }
    }

    /// Generates three cfg-gated `#[tokio::test]` functions,
    /// one per backend. Each introduces a `type DB = ...;` alias
    /// so the body can reference the generic type parameter.
    fn generate_multi(&self, type_param: &Ident) -> TokenStream {
        let stmts = &self.analysis.body.stmts;
        let param = &self.analysis.param_name;
        let ws_root = workspace_root();

        let fns = CONCRETE_BACKENDS.iter().map(|backend| {
            let feature = backend.feature();
            let db_type = backend.sqlx_type();
            let suffix = feature;
            let fn_name = format_ident!("{}_{}", self.analysis.fn_name, suffix,);
            let path = ws_root
                .join("migrations")
                .join(backend.feature())
                .to_string_lossy()
                .into_owned();
            let setup = pool_setup_tokens(backend, param, &path);
            let cleanup = cleanup_tokens(backend, param);

            quote! {
                #[cfg(feature = #feature)]
                #[::tokio::test]
                async fn #fn_name() {
                    type #type_param = #db_type;
                    #setup
                    #(#stmts)*
                    #cleanup
                }
            }
        });

        quote! { #(#fns)* }
    }

    /// Returns the absolute migration path for the given backend.
    fn resolve_migration_path(backend: &ConcreteBackend) -> String {
        let subdir = backend.feature();
        workspace_root()
            .join("migrations")
            .join(subdir)
            .to_string_lossy()
            .into_owned()
    }
}

// ── Helpers ─────────────────────────────────────────────────────

/// Finds the workspace root by walking up from
/// `CARGO_MANIFEST_DIR`.
///
/// Looks for a `Cargo.toml` containing a `[workspace]` section.
/// Panics if no workspace root is found.
fn workspace_root() -> std::path::PathBuf {
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set");
    find_workspace_root(std::path::PathBuf::from(manifest_dir))
}

/// Walks up from `start` looking for a `Cargo.toml` containing
/// a `[workspace]` section. Panics if none is found.
fn find_workspace_root(mut path: std::path::PathBuf) -> std::path::PathBuf {
    loop {
        let cargo_toml = path.join("Cargo.toml");
        if cargo_toml.exists() {
            let content = std::fs::read_to_string(&cargo_toml).expect("failed to read Cargo.toml");
            if content.contains("[workspace]") {
                return path;
            }
        }
        if !path.pop() {
            panic!(
                "could not find workspace root \
                 (Cargo.toml with [workspace])"
            );
        }
    }
}

// ── Entry points ────────────────────────────────────────────────

/// Entry point for `#[fabrique::test]`.
pub fn expand_test(attr: TokenStream, item: TokenStream) -> Result<TokenStream, syn::Error> {
    if !attr.is_empty() {
        return Err(syn::Error::new_spanned(
            attr,
            "#[fabrique::test] does not accept arguments",
        ));
    }
    let input: ItemFn = syn::parse2(item)?;
    let analysis = TestAnalysis::try_from_item(&input)?;
    let codegen = TestCodegen::new(&analysis);
    Ok(codegen.generate())
}

/// Entry point for `#[fabrique::doctest]`.
pub fn expand_doctest(item: TokenStream) -> Result<TokenStream, syn::Error> {
    let input: ItemFn = syn::parse2(item)?;
    let analysis = TestAnalysis::try_from_item(&input)?;
    let codegen = TestCodegen::new(&analysis);
    Ok(codegen.generate_doctest())
}

// ── Tests ───────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use syn::parse_quote;

    #[test]
    fn test_analysis_parses_sqlite_backend() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: Pool<Sqlite>) {}
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();

        assert_eq!(analysis.fn_name, "my_test");
        assert_eq!(analysis.param_name, "pool");
        assert_eq!(analysis.backend, Backend::Concrete(ConcreteBackend::Sqlite));
    }

    #[test]
    fn test_analysis_parses_postgres_backend() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: Pool<Postgres>) {}
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();

        assert_eq!(
            analysis.backend,
            Backend::Concrete(ConcreteBackend::Postgres)
        );
    }

    #[test]
    fn test_analysis_parses_mysql_backend() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: Pool<MySql>) {}
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();

        assert_eq!(analysis.backend, Backend::Concrete(ConcreteBackend::MySql));
    }

    #[test]
    fn test_analysis_parses_qualified_path() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: Pool<sqlx::Sqlite>) {}
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();

        assert_eq!(analysis.backend, Backend::Concrete(ConcreteBackend::Sqlite));
    }

    #[test]
    fn test_analysis_rejects_missing_param() {
        let input: ItemFn = parse_quote! {
            async fn my_test() {}
        };
        let result = TestAnalysis::try_from_item(&input);

        assert!(result.is_err());
    }

    #[test]
    fn test_analysis_rejects_unsupported_backend() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: Pool<Mssql>) {}
        };
        let result = TestAnalysis::try_from_item(&input);

        assert!(result.is_err());
    }

    #[test]
    fn test_generate_sqlite_test() {
        let input: ItemFn = parse_quote! {
            async fn test_create(pool: Pool<Sqlite>) {
                let result = Product::all(&pool).await;
                assert!(result.is_ok());
            }
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();
        let codegen = TestCodegen::with_path(&analysis, "/ws/migrations/sqlite");

        let generated = codegen.generate();

        assert_eq!(
            generated.to_string(),
            quote! {
                #[::tokio::test]
                async fn test_create() {
                    let pool =
                        ::fabrique::__private::create_sqlite_pool(
                            "/ws/migrations/sqlite"
                        )
                            .await
                            .expect("Failed to create test pool");
                    let result = Product::all(&pool).await;
                    assert!(result.is_ok());
                }
            }
            .to_string()
        );
    }

    #[test]
    fn test_generate_postgres_test() {
        let input: ItemFn = parse_quote! {
            async fn test_create(pool: Pool<Postgres>) {
                let result = Product::all(&pool).await;
                assert!(result.is_ok());
            }
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();
        let codegen = TestCodegen::with_path(&analysis, "/ws/migrations/postgres");

        let generated = codegen.generate();

        assert_eq!(
            generated.to_string(),
            quote! {
                #[::tokio::test]
                async fn test_create() {
                    let (pool, __base_url, __db_name) =
                        ::fabrique::__private::create_postgres_pool(
                            "/ws/migrations/postgres"
                        )
                            .await
                            .expect("Failed to create test pool");
                    let result = Product::all(&pool).await;
                    assert!(result.is_ok());
                    drop(pool);
                    ::fabrique::__private::cleanup_test_db_postgres(
                        &__base_url,
                        &__db_name,
                    )
                    .await;
                }
            }
            .to_string()
        );
    }

    #[test]
    fn test_generate_mysql_test() {
        let input: ItemFn = parse_quote! {
            async fn test_create(pool: Pool<MySql>) {
                let result = Product::all(&pool).await;
                assert!(result.is_ok());
            }
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();
        let codegen = TestCodegen::with_path(&analysis, "/ws/migrations/mysql");

        let generated = codegen.generate();

        assert_eq!(
            generated.to_string(),
            quote! {
                #[::tokio::test]
                async fn test_create() {
                    let (pool, __base_url, __db_name) =
                        ::fabrique::__private::create_mysql_pool(
                            "/ws/migrations/mysql"
                        )
                            .await
                            .expect("Failed to create test pool");
                    let result = Product::all(&pool).await;
                    assert!(result.is_ok());
                    drop(pool);
                    ::fabrique::__private::cleanup_test_db_mysql(
                        &__base_url,
                        &__db_name,
                    )
                    .await;
                }
            }
            .to_string()
        );
    }

    #[test]
    fn test_analysis_parses_multi_backend() {
        let input: ItemFn = parse_quote! {
            async fn my_test<DB: Dialect>(pool: Pool<DB>) {}
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();

        assert_eq!(analysis.fn_name, "my_test");
        assert_eq!(analysis.param_name, "pool");
        assert!(matches!(&analysis.backend, Backend::Multi(id) if id == "DB"),);
    }

    #[test]
    fn test_analysis_parses_multi_custom_name() {
        let input: ItemFn = parse_quote! {
            async fn my_test<T: Dialect>(pool: Pool<T>) {}
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();

        assert!(matches!(&analysis.backend, Backend::Multi(id) if id == "T"),);
    }

    #[test]
    fn test_generate_multi_backend() {
        let input: ItemFn = parse_quote! {
            async fn test_create<DB: Dialect>(pool: Pool<DB>) {
                let result = Product::all(&pool).await;
                assert!(result.is_ok());
            }
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();
        let codegen = TestCodegen::new(&analysis);

        let output = codegen.generate().to_string();

        // Three cfg-gated functions are generated
        assert!(output.contains("fn test_create_sqlite"));
        assert!(output.contains("fn test_create_postgres"));
        assert!(output.contains("fn test_create_mysql"));
        assert!(output.contains("# [cfg (feature = \"sqlite\")]"));
        assert!(output.contains("# [cfg (feature = \"postgres\")]"));
        assert!(output.contains("# [cfg (feature = \"mysql\")]"));

        // Type aliases for the generic parameter
        assert!(output.contains("type DB = :: sqlx :: Sqlite"));
        assert!(output.contains("type DB = :: sqlx :: Postgres"));
        assert!(output.contains("type DB = :: sqlx :: MySql"));
    }

    #[test]
    fn test_doctest_rejects_multi_backend() {
        let input: ItemFn = parse_quote! {
            async fn main<DB: Dialect>(
                pool: Pool<DB>,
            ) -> Result<(), fabrique::Error> {
                Ok(())
            }
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();
        let codegen = TestCodegen::with_path(&analysis, "/ws/migrations/sqlite");

        let output = codegen.generate_doctest().to_string();
        assert!(output.contains("compile_error"));
    }

    #[test]
    fn test_doctest_rejects_non_sqlite_backend() {
        let input: ItemFn = parse_quote! {
            async fn main(
                pool: Pool<Postgres>,
            ) -> Result<(), fabrique::Error> {
                Ok(())
            }
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();
        let codegen = TestCodegen::with_path(&analysis, "/ws/migrations/postgres");

        let output = codegen.generate_doctest().to_string();
        assert!(output.contains("compile_error"));
    }

    #[test]
    fn test_analysis_rejects_non_ident_pattern() {
        let input: ItemFn = parse_quote! {
            async fn my_test((a, b): Pool<Sqlite>) {}
        };
        let err = TestAnalysis::try_from_item(&input).unwrap_err();
        assert_eq!(err.to_string(), "expected a simple identifier");
    }

    #[test]
    fn test_analysis_rejects_self_param() {
        let input: ItemFn = parse_quote! {
            async fn my_test(&self) {}
        };
        let err = TestAnalysis::try_from_item(&input).unwrap_err();
        assert_eq!(err.to_string(), "expected a typed parameter");
    }

    #[test]
    fn test_analysis_rejects_non_path_type() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: &Pool<Sqlite>) {}
        };
        let err = TestAnalysis::try_from_item(&input).unwrap_err();
        assert_eq!(err.to_string(), "expected Pool<Sqlite|Postgres|MySql>");
    }

    #[test]
    fn test_analysis_rejects_non_pool_type() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: NotPool<Sqlite>) {}
        };
        let err = TestAnalysis::try_from_item(&input).unwrap_err();
        assert_eq!(err.to_string(), "expected Pool type");
    }

    #[test]
    fn test_analysis_rejects_pool_without_angle_brackets() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: Pool) {}
        };
        let err = TestAnalysis::try_from_item(&input).unwrap_err();
        assert_eq!(
            err.to_string(),
            "expected Pool<\u{2026}> with angle brackets"
        );
    }

    #[test]
    fn test_analysis_rejects_non_path_type_argument() {
        let input: ItemFn = parse_quote! {
            async fn my_test(pool: Pool<&Sqlite>) {}
        };
        let err = TestAnalysis::try_from_item(&input).unwrap_err();
        assert_eq!(err.to_string(), "expected a path type argument");
    }

    #[test]
    fn test_expand_test_delegates_correctly() {
        let input: TokenStream = quote! {
            async fn my_test(pool: Pool<Sqlite>) {
                let result = Product::all(&pool).await;
                assert!(result.is_ok());
            }
        };
        let output = expand_test(TokenStream::new(), input).unwrap().to_string();

        assert!(output.contains("fn my_test"));
        assert!(output.contains("create_sqlite_pool"));
    }

    #[test]
    fn test_expand_test_rejects_attributes() {
        let attr: TokenStream = quote! { some_config };
        let input: TokenStream = quote! {
            async fn my_test(pool: Pool<Sqlite>) {}
        };
        let err = expand_test(attr, input).unwrap_err();
        assert_eq!(
            err.to_string(),
            "#[fabrique::test] does not accept arguments"
        );
    }

    #[test]
    fn test_expand_doctest_delegates_correctly() {
        let input: TokenStream = quote! {
            async fn main(
                pool: Pool<Sqlite>,
            ) -> Result<(), fabrique::Error> {
                Ok(())
            }
        };
        let output = expand_doctest(input).unwrap().to_string();

        assert!(output.contains("fn main"));
        assert!(output.contains("block_on"));
        assert!(output.contains("create_sqlite_pool"));
    }

    #[test]
    fn test_generate_doctest() {
        let input: ItemFn = parse_quote! {
            async fn main(
                pool: Pool<Sqlite>,
            ) -> Result<(), fabrique::Error> {
                let _user = User::factory().create(&pool).await?;
                Ok(())
            }
        };
        let analysis = TestAnalysis::try_from_item(&input).unwrap();
        let codegen = TestCodegen::with_path(&analysis, "/ws/migrations/sqlite");

        let generated = codegen.generate_doctest();

        assert_eq!(
            generated.to_string(),
            quote! {
                fn main() {
                    ::tokio::runtime::Builder::new_current_thread()
                        .enable_all()
                        .build()
                        .expect("Failed to create Tokio runtime")
                        .block_on(async {
                            let pool =
                                ::fabrique::__private::create_sqlite_pool(
                                    "/ws/migrations/sqlite"
                                )
                                    .await
                                    .expect("Failed to create doctest pool");
                            let __result: Result<(), ::fabrique::Error> =
                                async {
                                    let _user = User::factory()
                                        .create(&pool).await?;
                                    Ok(())
                                }.await;
                            __result.expect("Doctest failed");
                        });
                }
            }
            .to_string()
        );
    }

    #[test]
    fn test_find_workspace_root_from_subcrate() {
        let start = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let root = find_workspace_root(start);
        assert!(root.join("Cargo.toml").exists());
        let content = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
        assert!(content.contains("[workspace]"));
    }

    #[test]
    #[should_panic(expected = "could not find workspace root")]
    fn test_find_workspace_root_panics_without_workspace() {
        let dir = std::env::temp_dir().join("fabrique_test_no_workspace");
        std::fs::create_dir_all(&dir).unwrap();

        struct Cleanup(std::path::PathBuf);
        impl Drop for Cleanup {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.0);
            }
        }
        let _guard = Cleanup(dir.clone());

        find_workspace_root(dir);
    }
}