Skip to main content

luxid_orm/
factory.rs

1//! Model factories.
2//!
3//! A factory says what a *typical* row looks like; a test says only what it
4//! cares about. That is the whole point — a test that spells out every column
5//! is a test that breaks when an unrelated column is added.
6//!
7//! ```ignore
8//! UserFactory::new().create().await?;                    // one typical user
9//! UserFactory::new().count(3).create().await?;           // three of them
10//! UserFactory::new()
11//!     .state(|user| user.email = Set("ada@example.com".into()))
12//!     .create_one()
13//!     .await?;                                           // one, with an override
14//! ```
15
16use luxid_core::error::Result;
17use sea_orm::{ActiveModelBehavior, ActiveModelTrait, EntityTrait, IntoActiveModel};
18
19use crate::hooks::Hooks;
20use crate::model::insert;
21
22/// The typical shape of a row.
23///
24/// `#[luxid::factory]`-generated types implement this; `new()` gives the
25/// builder.
26pub trait Factory: Sized {
27    type Active: ActiveModelTrait + ActiveModelBehavior + Send;
28
29    /// A row with every required column filled in.
30    fn definition() -> Self::Active;
31
32    /// Start building.
33    fn new() -> FactoryBuilder<Self> {
34        FactoryBuilder::new()
35    }
36}
37
38type ModelOf<F> = <<<F as Factory>::Active as ActiveModelTrait>::Entity as EntityTrait>::Model;
39type Mutation<F> = Box<dyn Fn(&mut <F as Factory>::Active) + Send>;
40
41/// A pending set of rows.
42pub struct FactoryBuilder<F: Factory> {
43    count: usize,
44    /// Applied in order, so a later override wins.
45    states: Vec<Mutation<F>>,
46}
47
48impl<F: Factory> Default for FactoryBuilder<F> {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl<F: Factory> FactoryBuilder<F> {
55    pub fn new() -> Self {
56        Self {
57            count: 1,
58            states: Vec::new(),
59        }
60    }
61
62    /// How many rows to build.
63    #[must_use]
64    pub fn count(mut self, count: usize) -> Self {
65        self.count = count;
66        self
67    }
68
69    /// Override part of the definition.
70    ///
71    /// The closure receives each row in turn, so a `count(3)` with a state that
72    /// varies by call produces three different rows.
73    #[must_use]
74    pub fn state(mut self, state: impl Fn(&mut F::Active) + Send + 'static) -> Self {
75        self.states.push(Box::new(state));
76        self
77    }
78
79    /// Build the active models without touching the database.
80    pub fn make(&self) -> Vec<F::Active> {
81        (0..self.count)
82            .map(|_| {
83                let mut active = F::definition();
84
85                for state in &self.states {
86                    state(&mut active);
87                }
88
89                active
90            })
91            .collect()
92    }
93
94    /// Insert the rows, running the model's hooks.
95    pub async fn create(&self) -> Result<Vec<ModelOf<F>>>
96    where
97        ModelOf<F>: IntoActiveModel<F::Active> + Hooks<Active = F::Active>,
98    {
99        let mut created = Vec::with_capacity(self.count);
100
101        // Sequentially, because rows often depend on the ids of earlier ones
102        // and because a factory is not a throughput problem.
103        for active in self.make() {
104            created.push(insert(active).await?);
105        }
106
107        Ok(created)
108    }
109
110    /// Insert exactly one row and return it, regardless of `count`.
111    pub async fn create_one(&self) -> Result<ModelOf<F>>
112    where
113        ModelOf<F>: IntoActiveModel<F::Active> + Hooks<Active = F::Active>,
114    {
115        let mut active = F::definition();
116
117        for state in &self.states {
118            state(&mut active);
119        }
120
121        insert(active).await
122    }
123}