pleme_testing/
fixtures.rs1use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6pub trait Fixture: Sized {
8 type Output;
9
10 fn build(self) -> Self::Output;
12
13 fn build_with<F>(self, f: F) -> Self::Output
15 where
16 F: FnOnce(&mut Self::Output),
17 {
18 let mut output = self.build();
19 f(&mut output);
20 output
21 }
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct User {
27 pub id: String,
28 pub email: String,
29 pub name: String,
30}
31
32#[derive(Default)]
34pub struct UserFixture {
35 id: Option<String>,
36 email: Option<String>,
37 name: Option<String>,
38}
39
40impl UserFixture {
41 pub fn new() -> Self {
42 Self::default()
43 }
44
45 pub fn id(mut self, id: impl Into<String>) -> Self {
46 self.id = Some(id.into());
47 self
48 }
49
50 pub fn email(mut self, email: impl Into<String>) -> Self {
51 self.email = Some(email.into());
52 self
53 }
54
55 pub fn name(mut self, name: impl Into<String>) -> Self {
56 self.name = Some(name.into());
57 self
58 }
59}
60
61impl Fixture for UserFixture {
62 type Output = User;
63
64 fn build(self) -> User {
65 User {
66 id: self.id.unwrap_or_else(|| Uuid::new_v4().to_string()),
67 email: self.email.unwrap_or_else(|| "test@example.com".to_string()),
68 name: self.name.unwrap_or_else(|| "Test User".to_string()),
69 }
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76
77 #[test]
78 fn test_user_fixture() {
79 let user = UserFixture::default().build();
80 assert!(!user.id.is_empty());
81 assert_eq!(user.email, "test@example.com");
82 }
83
84 #[test]
85 fn test_user_fixture_custom() {
86 let user = UserFixture::new()
87 .email("custom@example.com")
88 .name("Custom User")
89 .build();
90 assert_eq!(user.email, "custom@example.com");
91 assert_eq!(user.name, "Custom User");
92 }
93}