-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtesting_patterns.rs
More file actions
403 lines (337 loc) · 11.7 KB
/
testing_patterns.rs
File metadata and controls
403 lines (337 loc) · 11.7 KB
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
//! Testing Patterns Example
//!
//! Demonstrates testing strategies for code using Validation and Effect.
//! Shows how the "pure core, imperative shell" pattern makes testing easy.
//!
//! Patterns covered:
//! - Testing pure validation functions
//! - Testing effects with mock environments
//! - Testing effect composition
//! - Verifying side effects through the environment
use std::sync::{Arc, Mutex};
use stillwater::{from_fn, Effect, EffectExt, RunStandalone, Validation};
// ==================== Testing Pure Validations ====================
/// Pure validation functions are trivial to test - no mocks needed!
fn validate_age(age: i32) -> Validation<i32, Vec<String>> {
if (0..=150).contains(&age) {
Validation::success(age)
} else {
Validation::failure(vec![format!("Invalid age: {}", age)])
}
}
fn example_testing_validations() {
println!("\n=== Example 1: Testing Pure Validations ===");
println!("Pure validation functions are easy to test - just call them!");
// Test valid age
let result = validate_age(25);
assert!(matches!(result, Validation::Success(25)));
println!("✓ Valid age test passed");
// Test invalid age
let result = validate_age(-5);
match result {
Validation::Failure(errors) => {
assert_eq!(errors.len(), 1);
println!("✓ Invalid age test passed");
}
_ => panic!("Expected failure"),
}
// Test boundary conditions
let result = validate_age(0);
assert!(matches!(result, Validation::Success(0)));
let result = validate_age(150);
assert!(matches!(result, Validation::Success(150)));
let result = validate_age(151);
assert!(matches!(result, Validation::Failure(_)));
println!("✓ Boundary condition tests passed");
}
// ==================== Testing Effects with Mock Environment ====================
/// Example service trait for testing
///
/// In a real application, you would have:
/// - A trait like this defining the interface
/// - A production implementation (e.g., PostgresStorage with real DB queries)
/// - A mock implementation for testing (shown below)
///
/// This separation enables testing business logic without real infrastructure.
trait Storage {
fn get(&self, key: &str) -> Option<String>;
fn set(&self, key: &str, value: String);
}
/// Mock implementation (in-memory) for testing
#[derive(Clone)]
struct MockStorage {
data: Arc<Mutex<std::collections::HashMap<String, String>>>,
}
impl MockStorage {
fn new() -> Self {
Self {
data: Arc::new(Mutex::new(std::collections::HashMap::new())),
}
}
fn verify_contains(&self, key: &str, expected: &str) -> bool {
self.data
.lock()
.unwrap()
.get(key)
.map(|v| v == expected)
.unwrap_or(false)
}
}
impl Storage for MockStorage {
fn get(&self, key: &str) -> Option<String> {
self.data.lock().unwrap().get(key).cloned()
}
fn set(&self, key: &str, value: String) {
self.data.lock().unwrap().insert(key.to_string(), value);
}
}
/// Test environment using mock
#[derive(Clone)]
struct TestEnv {
storage: MockStorage,
}
impl TestEnv {
fn new() -> Self {
Self {
storage: MockStorage::new(),
}
}
}
impl AsRef<MockStorage> for TestEnv {
fn as_ref(&self) -> &MockStorage {
&self.storage
}
}
/// Function to test - uses Effect
fn save_user_preference<Env: AsRef<MockStorage> + Clone + Send + Sync + 'static>(
user_id: u64,
preference: String,
) -> impl Effect<Output = (), Error = String, Env = Env> {
from_fn(move |env: &Env| {
let storage: &MockStorage = env.as_ref();
let key = format!("user:{}:preference", user_id);
storage.set(&key, preference.clone());
Ok(())
})
}
fn load_user_preference<Env: AsRef<MockStorage> + Clone + Send + Sync + 'static>(
user_id: u64,
) -> impl Effect<Output = Option<String>, Error = String, Env = Env> {
from_fn(move |env: &Env| {
let storage: &MockStorage = env.as_ref();
let key = format!("user:{}:preference", user_id);
Ok(storage.get(&key))
})
}
async fn example_testing_effects() {
println!("\n=== Example 2: Testing Effects with Mock Environment ===");
println!("Effects are easy to test with mock environments!");
let env = TestEnv::new();
// Test saving
save_user_preference(42, "dark_mode".to_string())
.run(&env)
.await
.unwrap();
assert!(env
.storage
.verify_contains("user:42:preference", "dark_mode"));
println!("✓ Save effect test passed");
// Test loading
let result = load_user_preference(42).run(&env).await.unwrap();
assert_eq!(result, Some("dark_mode".to_string()));
println!("✓ Load effect test passed");
// Test loading non-existent
let result = load_user_preference(99).run(&env).await.unwrap();
assert_eq!(result, None);
println!("✓ Load non-existent test passed");
}
// ==================== Testing Effect Composition ====================
/// Combined operation that we want to test
fn update_and_verify<Env: AsRef<MockStorage> + Clone + Send + Sync + 'static>(
user_id: u64,
new_preference: String,
) -> impl Effect<Output = bool, Error = String, Env = Env> {
save_user_preference(user_id, new_preference.clone())
.and_then(move |_| load_user_preference(user_id))
.map(move |loaded| loaded == Some(new_preference.clone()))
}
async fn example_testing_composition() {
println!("\n=== Example 3: Testing Effect Composition ===");
println!("Composed effects can be tested end-to-end!");
let env = TestEnv::new();
let success = update_and_verify(10, "compact_view".to_string())
.run(&env)
.await
.unwrap();
assert!(success);
println!("✓ Composition test passed");
}
// ==================== Verifying Side Effects ====================
/// Service that tracks calls for verification
#[derive(Clone)]
struct SpyEmailService {
sent: Arc<Mutex<Vec<(String, String)>>>,
}
impl SpyEmailService {
fn new() -> Self {
Self {
sent: Arc::new(Mutex::new(Vec::new())),
}
}
fn send(&self, to: String, message: String) {
self.sent.lock().unwrap().push((to, message));
}
fn verify_sent(&self, to: &str, message: &str) -> bool {
self.sent
.lock()
.unwrap()
.iter()
.any(|(t, m)| t == to && m == message)
}
fn count_sent(&self) -> usize {
self.sent.lock().unwrap().len()
}
}
#[derive(Clone)]
struct EmailEnv {
email: SpyEmailService,
}
impl EmailEnv {
fn new() -> Self {
Self {
email: SpyEmailService::new(),
}
}
}
impl AsRef<SpyEmailService> for EmailEnv {
fn as_ref(&self) -> &SpyEmailService {
&self.email
}
}
fn send_welcome_email<Env: AsRef<SpyEmailService> + Clone + Send + Sync + 'static>(
email: String,
name: String,
) -> impl Effect<Output = (), Error = String, Env = Env> {
from_fn(move |env: &Env| {
let service: &SpyEmailService = env.as_ref();
let message = format!("Welcome, {}!", name);
service.send(email.clone(), message);
Ok(())
})
}
async fn example_testing_side_effects() {
println!("\n=== Example 4: Verifying Side Effects ===");
println!("Use spy/mock services to verify side effects!");
let env = EmailEnv::new();
send_welcome_email("[email protected]".to_string(), "Alice".to_string())
.run(&env)
.await
.unwrap();
assert!(env
.email
.verify_sent("[email protected]", "Welcome, Alice!"));
assert_eq!(env.email.count_sent(), 1);
println!("✓ Side effect verification passed");
}
// ==================== Testing Error Cases ====================
fn divide<Env: Clone + Send + Sync + 'static>(
a: i32,
b: i32,
) -> impl Effect<Output = i32, Error = String, Env = Env> {
from_fn(move |_env: &Env| {
if b == 0 {
Err("Division by zero".to_string())
} else {
Ok(a / b)
}
})
}
async fn example_testing_errors() {
println!("\n=== Example 5: Testing Error Cases ===");
// Test success case
let result = divide::<()>(10, 2).run_standalone().await;
assert_eq!(result, Ok(5));
println!("✓ Success case test passed");
// Test error case
let result = divide::<()>(10, 0).run_standalone().await;
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "Division by zero");
println!("✓ Error case test passed");
}
// ==================== Property-Based Testing ====================
fn example_property_based_testing() {
println!("\n=== Example 6: Property-Based Testing ===");
println!("Testing properties that should always hold:");
// Property: validation should be consistent
for age in -10..200 {
let result = validate_age(age);
let is_valid = (0..=150).contains(&age);
match result {
Validation::Success(_) => assert!(is_valid, "Age {} should be invalid", age),
Validation::Failure(_) => assert!(!is_valid, "Age {} should be valid", age),
}
}
println!("✓ Validation consistency property holds");
// Property: error accumulation should preserve all errors
fn multi_error_validation(n: i32) -> Validation<(), Vec<String>> {
let v1 = if n < 0 {
Validation::failure(vec!["negative".to_string()])
} else {
Validation::success(())
};
let v2 = if n % 2 != 0 {
Validation::failure(vec!["odd".to_string()])
} else {
Validation::success(())
};
Validation::<((), ()), Vec<String>>::all((v1, v2)).map(|_| ())
}
// Test that all errors are accumulated
let result = multi_error_validation(-3);
match result {
Validation::Failure(errors) => {
assert_eq!(errors.len(), 2);
assert!(errors.contains(&"negative".to_string()));
assert!(errors.contains(&"odd".to_string()));
}
_ => panic!("Expected failure with multiple errors"),
}
println!("✓ Error accumulation property holds");
}
// ==================== Test Organization Example ====================
fn example_test_organization() {
println!("\n=== Example 7: Test Organization ===");
println!("Organizing tests by behavior:");
println!("\n Unit Tests:");
println!(" - Test pure functions in isolation");
println!(" - Fast, no dependencies");
println!(" - Example: validate_age()");
println!("\n Integration Tests:");
println!(" - Test effect composition with mocks");
println!(" - Verify interactions between components");
println!(" - Example: update_and_verify()");
println!("\n Contract Tests:");
println!(" - Verify mock behavior matches real services");
println!(" - Run same tests against mock and real impl");
println!(" - Example: Storage trait tests");
println!("\n✓ All test organization patterns demonstrated");
}
// ==================== Main ====================
#[tokio::main]
async fn main() {
println!("Testing Patterns Examples");
println!("=========================");
println!();
println!("The pure core/imperative shell pattern makes testing easy:");
println!("- Pure functions: Just call them");
println!("- Effects: Inject mock environments");
println!("- Side effects: Use spy services");
example_testing_validations();
example_testing_effects().await;
example_testing_composition().await;
example_testing_side_effects().await;
example_testing_errors().await;
example_property_based_testing();
example_test_organization();
println!("\n=== All examples completed successfully! ===");
}