protest 1.1.0

An ergonomic, powerful, and feature-rich property testing library with minimal boilerplate.
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
//! Async property testing examples
//!
//! This example demonstrates how to use Protest for testing asynchronous code,
//! including async properties, error handling, and integration with async runtimes.

use protest::{
    AsyncProperty, PropertyError, PropertyTestBuilder, TestConfig, check_async,
    check_async_with_config, range,
};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::time::sleep;

// Example 1: Basic async property
async fn example_1_basic_async() {
    println!("=== Example 1: Basic Async Property ===");

    struct AsyncTimeoutProperty;
    impl AsyncProperty<u64> for AsyncTimeoutProperty {
        type Output = ();

        async fn test(&self, timeout_ms: u64) -> Result<Self::Output, PropertyError> {
            let start = Instant::now();
            sleep(Duration::from_millis(timeout_ms)).await;
            let elapsed = start.elapsed();

            // Property: actual sleep time should be close to requested time
            let expected = Duration::from_millis(timeout_ms);
            let tolerance = Duration::from_millis(10); // 10ms tolerance

            if elapsed >= expected && elapsed <= expected + tolerance {
                Ok(())
            } else {
                Err(PropertyError::property_failed(format!(
                    "Sleep time {} ms not close to expected {} ms",
                    elapsed.as_millis(),
                    expected.as_millis()
                )))
            }
        }
    }

    // Test with small timeout values to keep the example fast
    let generator = range(1u64, 20u64);

    match check_async(generator, AsyncTimeoutProperty).await {
        Ok(success) => {
            println!(
                "✓ Async timeout property passed! ({} iterations)",
                success.iterations
            );
        }
        Err(failure) => {
            println!("✗ Property failed: {}", failure.error);
            println!("  Timeout value: {} ms", failure.original_input);
        }
    }
}

// Example 2: Async property with external service simulation
async fn example_2_external_service() {
    println!("\n=== Example 2: External Service Simulation ===");

    // Simulate an external HTTP service
    async fn fetch_user_data(user_id: u32) -> Result<String, String> {
        // Simulate network delay
        sleep(Duration::from_millis(5)).await;

        // Simulate service behavior
        match user_id {
            0 => Err("Invalid user ID".to_string()),
            1..=1000 => Ok(format!("User data for ID {}", user_id)),
            _ => Err("User not found".to_string()),
        }
    }

    struct UserServiceProperty;
    impl AsyncProperty<u32> for UserServiceProperty {
        type Output = ();

        async fn test(&self, user_id: u32) -> Result<Self::Output, PropertyError> {
            match fetch_user_data(user_id).await {
                Ok(data) => {
                    // Property: returned data should contain the user ID
                    if data.contains(&user_id.to_string()) {
                        Ok(())
                    } else {
                        Err(PropertyError::property_failed(format!(
                            "User data '{}' doesn't contain ID {}",
                            data, user_id
                        )))
                    }
                }
                Err(error) => {
                    // Property: errors should only occur for invalid IDs
                    if user_id == 0 || user_id > 1000 {
                        Ok(()) // Expected error
                    } else {
                        Err(PropertyError::property_failed(format!(
                            "Unexpected error for valid ID {}: {}",
                            user_id, error
                        )))
                    }
                }
            }
        }
    }

    let config = TestConfig {
        iterations: 30,
        seed: Some(789),
        ..TestConfig::default()
    };

    match check_async_with_config(range(0u32, 1200u32), UserServiceProperty, config).await {
        Ok(success) => {
            println!(
                "✓ User service property passed! ({} iterations)",
                success.iterations
            );
        }
        Err(failure) => {
            println!("✗ Property failed: {}", failure.error);
            println!("  User ID: {}", failure.original_input);
        }
    }
}

// Example 3: Async property with shared state
async fn example_3_shared_state() {
    println!("\n=== Example 3: Shared State Management ===");

    #[derive(Clone)]
    struct Counter {
        value: Arc<Mutex<i32>>,
    }

    impl Counter {
        fn new() -> Self {
            Self {
                value: Arc::new(Mutex::new(0)),
            }
        }

        async fn increment(&self, amount: i32) -> i32 {
            // Simulate async work
            sleep(Duration::from_millis(1)).await;

            let mut value = self.value.lock().unwrap();
            *value += amount;
            *value
        }

        fn get(&self) -> i32 {
            *self.value.lock().unwrap()
        }
    }

    struct CounterProperty {
        counter: Counter,
    }

    impl AsyncProperty<i32> for CounterProperty {
        type Output = ();

        async fn test(&self, increment: i32) -> Result<Self::Output, PropertyError> {
            let initial = self.counter.get();
            let result = self.counter.increment(increment).await;

            // Property: result should equal initial + increment
            if result == initial + increment {
                Ok(())
            } else {
                Err(PropertyError::property_failed(format!(
                    "Counter increment failed: {} + {} != {}",
                    initial, increment, result
                )))
            }
        }
    }

    let counter = Counter::new();
    let property = CounterProperty {
        counter: counter.clone(),
    };

    match check_async(range(-10, 10), property).await {
        Ok(success) => {
            println!(
                "✓ Counter property passed! ({} iterations)",
                success.iterations
            );
            println!("  Final counter value: {}", counter.get());
        }
        Err(failure) => {
            println!("✗ Property failed: {}", failure.error);
            println!("  Increment value: {}", failure.original_input);
            println!("  Final counter value: {}", counter.get());
        }
    }
}

// Example 4: Async property with timeout handling
async fn example_4_timeout_handling() {
    println!("\n=== Example 4: Timeout Handling ===");

    async fn slow_computation(n: u32) -> Result<u32, &'static str> {
        // Simulate computation that gets slower with larger inputs
        let delay_ms = n / 10; // 0.1ms per unit
        sleep(Duration::from_millis(delay_ms as u64)).await;

        if n > 1000 {
            Err("Input too large")
        } else {
            Ok(n * 2)
        }
    }

    struct TimeoutProperty;
    impl AsyncProperty<u32> for TimeoutProperty {
        type Output = ();

        async fn test(&self, input: u32) -> Result<Self::Output, PropertyError> {
            // Use tokio::time::timeout to enforce a timeout
            let timeout_duration = Duration::from_millis(50);

            match tokio::time::timeout(timeout_duration, slow_computation(input)).await {
                Ok(Ok(result)) => {
                    // Property: result should be double the input
                    if result == input * 2 {
                        Ok(())
                    } else {
                        Err(PropertyError::property_failed(format!(
                            "Computation result {} != {} * 2",
                            result, input
                        )))
                    }
                }
                Ok(Err(error)) => {
                    // Expected error for large inputs
                    if input > 1000 {
                        Ok(())
                    } else {
                        Err(PropertyError::property_failed(format!(
                            "Unexpected error for input {}: {}",
                            input, error
                        )))
                    }
                }
                Err(_) => {
                    // Timeout occurred
                    Err(PropertyError::property_failed(format!(
                        "Computation timed out for input {}",
                        input
                    )))
                }
            }
        }
    }

    let config = TestConfig {
        iterations: 25,
        max_shrink_iterations: 50,
        shrink_timeout: Duration::from_secs(2),
        ..TestConfig::default()
    };

    match check_async_with_config(range(1u32, 800u32), TimeoutProperty, config).await {
        Ok(success) => {
            println!(
                "✓ Timeout property passed! ({} iterations)",
                success.iterations
            );
        }
        Err(failure) => {
            println!("✗ Property failed: {}", failure.error);
            println!("  Input: {}", failure.original_input);
            if let Some(shrunk) = failure.shrunk_input {
                println!("  Shrunk to: {}", shrunk);
            }
        }
    }
}

// Example 5: Async property with PropertyTestBuilder
async fn example_5_builder_pattern() {
    println!("\n=== Example 5: Async Builder Pattern ===");

    // Simulate a database operation
    async fn database_query(query_size: usize) -> Result<Vec<String>, String> {
        // Simulate query processing time based on size
        sleep(Duration::from_millis(query_size as u64 / 100)).await;

        if query_size == 0 {
            return Err("Empty query".to_string());
        }

        if query_size > 1000 {
            return Err("Query too large".to_string());
        }

        // Return mock results
        Ok((0..query_size.min(10))
            .map(|i| format!("Result {}", i))
            .collect())
    }

    struct DatabaseProperty;
    impl AsyncProperty<usize> for DatabaseProperty {
        type Output = ();

        async fn test(&self, query_size: usize) -> Result<Self::Output, PropertyError> {
            match database_query(query_size).await {
                Ok(results) => {
                    // Property: non-empty queries should return results
                    if query_size > 0 && results.is_empty() {
                        Err(PropertyError::property_failed(format!(
                            "Query size {} returned no results",
                            query_size
                        )))
                    } else {
                        Ok(())
                    }
                }
                Err(error) => {
                    // Property: errors should only occur for invalid query sizes
                    if query_size == 0 || query_size > 1000 {
                        Ok(()) // Expected error
                    } else {
                        Err(PropertyError::property_failed(format!(
                            "Unexpected error for query size {}: {}",
                            query_size, error
                        )))
                    }
                }
            }
        }
    }

    let result = PropertyTestBuilder::new()
        .iterations(40)
        .seed(456)
        .max_shrink_iterations(30)
        .shrink_timeout(Duration::from_secs(3))
        .enable_statistics()
        .run_async(range(0usize, 1200usize), DatabaseProperty)
        .await;

    match result {
        Ok(success) => {
            println!(
                "✓ Database property passed! ({} iterations)",
                success.iterations
            );
            if let Some(stats) = success.stats {
                println!("  Total queries tested: {}", stats.total_generated);
                // Note: test_duration field not available
                // println!("  Test duration: {:?}", success.test_duration);
            }
        }
        Err(failure) => {
            println!("✗ Property failed: {}", failure.error);
            println!("  Query size: {}", failure.original_input);
            // Note: test_duration field not available
            // println!("  Test duration: {:?}", failure.test_duration);
        }
    }
}

// Example 6: Concurrent async properties
async fn example_6_concurrent_properties() {
    println!("\n=== Example 6: Concurrent Async Properties ===");

    struct FastProperty;
    impl AsyncProperty<i32> for FastProperty {
        type Output = ();

        async fn test(&self, input: i32) -> Result<Self::Output, PropertyError> {
            sleep(Duration::from_millis(1)).await;

            if input < 0 {
                Err(PropertyError::property_failed("Negative input"))
            } else {
                Ok(())
            }
        }
    }

    struct SlowProperty;
    impl AsyncProperty<i32> for SlowProperty {
        type Output = ();

        async fn test(&self, input: i32) -> Result<Self::Output, PropertyError> {
            sleep(Duration::from_millis(5)).await;

            if input > 100 {
                Err(PropertyError::property_failed("Input too large"))
            } else {
                Ok(())
            }
        }
    }

    let config = TestConfig {
        iterations: 15,
        ..TestConfig::default()
    };

    // Run both properties concurrently
    let start = Instant::now();
    let (result1, result2) = tokio::join!(
        check_async_with_config(range(0, 50), FastProperty, config.clone()),
        check_async_with_config(range(0, 50), SlowProperty, config)
    );
    let duration = start.elapsed();

    println!("  Concurrent execution completed in {:?}", duration);

    match (result1, result2) {
        (Ok(success1), Ok(success2)) => {
            println!("✓ Both properties passed!");
            println!("  Fast property: {} iterations", success1.iterations);
            println!("  Slow property: {} iterations", success2.iterations);
        }
        (Err(failure), Ok(_)) => {
            println!("✗ Fast property failed: {}", failure.error);
        }
        (Ok(_), Err(failure)) => {
            println!("✗ Slow property failed: {}", failure.error);
        }
        (Err(failure1), Err(failure2)) => {
            println!("✗ Both properties failed:");
            println!("  Fast: {}", failure1.error);
            println!("  Slow: {}", failure2.error);
        }
    }
}

#[tokio::main]
async fn main() {
    println!("Protest Library - Async Examples");
    println!("================================");

    example_1_basic_async().await;
    example_2_external_service().await;
    example_3_shared_state().await;
    example_4_timeout_handling().await;
    example_5_builder_pattern().await;
    example_6_concurrent_properties().await;

    println!("\n=== Summary ===");
    println!("These async examples demonstrate:");
    println!("• Basic async property testing");
    println!("• Testing external service interactions");
    println!("• Managing shared state in async tests");
    println!("• Handling timeouts and cancellation");
    println!("• Using PropertyTestBuilder with async properties");
    println!("• Running concurrent async property tests");
    println!("\nAsync support in Protest allows you to test:");
    println!("• Network operations and HTTP clients");
    println!("• Database interactions");
    println!("• File I/O operations");
    println!("• Timer and scheduling logic");
    println!("• Any async/await based code");
}