postmortem 0.1.1

A validation library that accumulates all errors for comprehensive feedback
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
---
number: 13
title: Developer Experience
category: testing
priority: medium
status: draft
dependencies: [1, 2, 3, 4, 5]
created: 2025-11-26
---

# Specification 013: Developer Experience

**Category**: testing
**Priority**: medium
**Status**: draft
**Dependencies**: Specs 001-005 (Core through Array)

## Context

A validation library is only as good as its developer experience. This specification focuses on testing utilities, assertion macros, and documentation that make postmortem pleasant to use in real projects. Good test helpers reduce boilerplate and make validation tests readable and maintainable.

## Objective

Implement developer experience improvements:
1. Test assertion macros for validation results
2. Property-based test generators for formats
3. Comprehensive rustdoc documentation
4. Runnable examples for common use cases

## Requirements

### Functional Requirements

1. **Test Assertion Macros**
   - `assert_valid!(result)` - assert validation succeeded
   - `assert_invalid!(result)` - assert validation failed
   - `assert_error_at!(errors, path)` - assert error at specific path
   - `assert_error_at!(errors, path, code)` - assert error with specific code
   - `assert_error_count!(errors, n)` - assert exact error count

2. **Property Testing Generators** (feature: `proptest`)
   - `valid_email()` - generates valid email strings
   - `invalid_email()` - generates invalid email strings
   - `valid_url()` - generates valid URLs
   - `valid_uuid()` - generates valid UUIDs
   - `valid_date()` - generates ISO 8601 dates
   - `arbitrary_for_schema(schema)` - generate values matching schema

3. **Debug Output Helpers**
   - Pretty-print validation errors
   - Color-coded output in test failures
   - Path highlighting for error location

4. **Documentation**
   - Comprehensive rustdoc on all public items
   - Examples in doc comments
   - Module-level documentation with guides
   - README with quick start

### Non-Functional Requirements

- Test macros provide clear failure messages
- Property generators are efficient
- Documentation builds without warnings
- Examples are tested via doctest

## Acceptance Criteria

- [ ] `assert_valid!(result)` passes for valid results
- [ ] `assert_valid!(result)` shows errors on failure
- [ ] `assert_invalid!(result)` passes for invalid results
- [ ] `assert_error_at!(errors, "email")` finds error at path
- [ ] `assert_error_at!(errors, "email", "invalid_email")` checks code
- [ ] `assert_error_count!(errors, 2)` checks count
- [ ] `valid_email()` generates only valid emails
- [ ] `invalid_email()` generates only invalid emails
- [ ] All public items have rustdoc
- [ ] Examples compile and pass

## Technical Details

### Implementation Approach

```rust
// src/test_helpers.rs

/// Assert that validation result is successful
/// Note: Consider using stillwater's built-in `assert_success!` macro as well
#[macro_export]
macro_rules! assert_valid {
    ($result:expr) => {
        match &$result {
            $crate::Validation::Success(_) => {}
            $crate::Validation::Failure(errors) => {
                panic!(
                    "Expected valid result, got {} error(s):\n{}",
                    errors.len(),
                    $crate::test_helpers::format_errors(errors)
                );
            }
        }
    };
}

/// Assert that validation result failed
/// Note: Consider using stillwater's built-in `assert_failure!` macro as well
#[macro_export]
macro_rules! assert_invalid {
    ($result:expr) => {
        match &$result {
            $crate::Validation::Failure(_) => {}
            $crate::Validation::Success(v) => {
                panic!(
                    "Expected invalid result, got valid: {:?}",
                    v
                );
            }
        }
    };
    ($result:expr, $count:expr) => {
        match &$result {
            $crate::Validation::Failure(errors) => {
                assert_eq!(
                    errors.len(),
                    $count,
                    "Expected {} errors, got {}:\n{}",
                    $count,
                    errors.len(),
                    $crate::test_helpers::format_errors(errors)
                );
            }
            $crate::Validation::Success(v) => {
                panic!(
                    "Expected invalid result with {} errors, got valid: {:?}",
                    $count,
                    v
                );
            }
        }
    };
}

/// Assert error exists at specific path
#[macro_export]
macro_rules! assert_error_at {
    ($errors:expr, $path:expr) => {
        let path_str = $path.to_string();
        let found = $errors.iter().any(|e| e.path.to_string() == path_str);
        if !found {
            panic!(
                "Expected error at path '{}', but no error found there.\nActual errors:\n{}",
                path_str,
                $crate::test_helpers::format_errors($errors)
            );
        }
    };
    ($errors:expr, $path:expr, $code:expr) => {
        let path_str = $path.to_string();
        let code_str = $code.to_string();
        let found = $errors.iter().any(|e| {
            e.path.to_string() == path_str && e.code == code_str
        });
        if !found {
            panic!(
                "Expected error at path '{}' with code '{}', but not found.\nActual errors:\n{}",
                path_str,
                code_str,
                $crate::test_helpers::format_errors($errors)
            );
        }
    };
}

/// Assert exact error count
#[macro_export]
macro_rules! assert_error_count {
    ($errors:expr, $count:expr) => {
        assert_eq!(
            $errors.len(),
            $count,
            "Expected {} errors, got {}:\n{}",
            $count,
            $errors.len(),
            $crate::test_helpers::format_errors($errors)
        );
    };
}

pub mod test_helpers {
    use crate::SchemaErrors;

    /// Format errors for display in test failures
    pub fn format_errors(errors: &SchemaErrors) -> String {
        errors
            .iter()
            .enumerate()
            .map(|(i, e)| {
                format!(
                    "  {}. {} [{}]: {}",
                    i + 1,
                    e.path,
                    e.code,
                    e.message
                )
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Pretty-print errors with colors (for terminal)
    #[cfg(feature = "colored")]
    pub fn format_errors_colored(errors: &SchemaErrors) -> String {
        use colored::Colorize;

        errors
            .iter()
            .enumerate()
            .map(|(i, e)| {
                format!(
                    "  {}. {} [{}]: {}",
                    (i + 1).to_string().bold(),
                    e.path.to_string().yellow(),
                    e.code.red(),
                    e.message
                )
            })
            .collect::<Vec<_>>()
            .join("\n")
    }
}

// Property testing generators (feature-gated)
#[cfg(feature = "proptest")]
pub mod generators {
    use proptest::prelude::*;

    /// Generate valid email addresses
    pub fn valid_email() -> impl Strategy<Value = String> {
        (
            "[a-z]{1,10}",           // local part
            "[a-z]{1,10}",           // domain
            prop_oneof!["com", "org", "net", "io"],
        )
            .prop_map(|(local, domain, tld)| format!("{}@{}.{}", local, domain, tld))
    }

    /// Generate invalid email addresses
    pub fn invalid_email() -> impl Strategy<Value = String> {
        prop_oneof![
            // Missing @
            "[a-z]{5,10}".prop_map(|s| s),
            // Missing domain
            "[a-z]{5}@".prop_map(|s| s),
            // Double @
            "[a-z]{3}@@[a-z]{3}\\.[a-z]{3}".prop_map(|s| s),
            // Invalid characters
            "[a-z]{3}@[a-z]{3}\\.[a-z]{3} ".prop_map(|s| s),
        ]
    }

    /// Generate valid URLs
    pub fn valid_url() -> impl Strategy<Value = String> {
        (
            prop_oneof!["http", "https"],
            "[a-z]{1,10}",
            prop_oneof!["com", "org", "net", "io"],
            proptest::option::of("[a-z]{1,10}"),
        )
            .prop_map(|(scheme, domain, tld, path)| {
                match path {
                    Some(p) => format!("{}://{}.{}/{}", scheme, domain, tld, p),
                    None => format!("{}://{}.{}", scheme, domain, tld),
                }
            })
    }

    /// Generate valid UUIDs
    pub fn valid_uuid() -> impl Strategy<Value = String> {
        "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
    }

    /// Generate valid ISO 8601 dates
    pub fn valid_date() -> impl Strategy<Value = String> {
        (1970i32..2100, 1u32..13, 1u32..29)
            .prop_map(|(y, m, d)| format!("{:04}-{:02}-{:02}", y, m, d))
    }

    /// Generate valid ISO 8601 datetimes
    pub fn valid_datetime() -> impl Strategy<Value = String> {
        (valid_date(), 0u32..24, 0u32..60, 0u32..60)
            .prop_map(|(date, h, m, s)| {
                format!("{}T{:02}:{:02}:{:02}Z", date, h, m, s)
            })
    }

    /// Generate positive integers
    pub fn positive_integer() -> impl Strategy<Value = i64> {
        1i64..i64::MAX
    }

    /// Generate non-negative integers
    pub fn non_negative_integer() -> impl Strategy<Value = i64> {
        0i64..i64::MAX
    }

    /// Generate strings within length bounds
    pub fn string_with_length(min: usize, max: usize) -> impl Strategy<Value = String> {
        proptest::collection::vec(proptest::char::any(), min..=max)
            .prop_map(|chars| chars.into_iter().collect())
    }
}
```

### Documentation Structure

```rust
//! # postmortem
//!
//! Runtime schema validation with comprehensive error accumulation.
//!
//! ## Quick Start
//!
//! ```rust
//! use postmortem::{Schema, JsonPath, assert_valid, assert_invalid};
//! use serde_json::json;
//!
//! // Define a schema
//! let user_schema = Schema::object()
//!     .field("email", Schema::string().email())
//!     .field("age", Schema::integer().min(0).max(150));
//!
//! // Validate data
//! let result = user_schema.validate(&json!({
//!     "email": "user@example.com",
//!     "age": 25
//! }), &JsonPath::root());
//!
//! assert_valid!(result);
//! ```
//!
//! ## Key Features
//!
//! - **Error Accumulation**: Collects ALL validation errors, not just the first
//! - **Clear Paths**: Error locations like `users[0].email` for easy debugging
//! - **stillwater Integration**: Native `Validation` type for functional composition
//! - **Schema Interop**: Export to JSON Schema and OpenAPI formats
//!
//! ## Schema Types
//!
//! - [`Schema::string()`] - String validation with formats
//! - [`Schema::integer()`] - Integer validation with ranges
//! - [`Schema::object()`] - Object validation with fields
//! - [`Schema::array()`] - Array validation with items
//! - [`Schema::one_of()`] - Union types (exactly one match)
//! - [`Schema::any_of()`] - Union types (at least one match)
//!
//! ## Testing Utilities
//!
//! ```rust
//! use postmortem::{assert_valid, assert_invalid, assert_error_at};
//!
//! // Assert validation passes
//! assert_valid!(result);
//!
//! // Assert validation fails with specific errors
//! assert_invalid!(result);
//! assert_error_at!(errors, "email", "invalid_email");
//! ```
```

### Architecture Changes

- Create `src/test_helpers.rs` for test utilities
- Create `src/generators.rs` for property testing (feature-gated)
- Add comprehensive rustdoc to all modules

### Data Structures

- Macros for test assertions
- Strategy types for property testing

### APIs and Interfaces

```rust
// Test assertion macros
assert_valid!(result)
assert_invalid!(result)
assert_invalid!(result, count)
assert_error_at!(errors, path)
assert_error_at!(errors, path, code)
assert_error_count!(errors, count)

// Helper functions
test_helpers::format_errors(&errors) -> String
test_helpers::format_errors_colored(&errors) -> String

// Property generators (feature: proptest)
generators::valid_email() -> impl Strategy<Value = String>
generators::invalid_email() -> impl Strategy<Value = String>
generators::valid_url() -> impl Strategy<Value = String>
generators::valid_uuid() -> impl Strategy<Value = String>
generators::valid_date() -> impl Strategy<Value = String>
generators::valid_datetime() -> impl Strategy<Value = String>
generators::positive_integer() -> impl Strategy<Value = i64>
generators::string_with_length(min, max) -> impl Strategy<Value = String>
```

## Dependencies

- **Prerequisites**: Specs 001-005
- **Affected Components**: None (new utilities)
- **External Dependencies** (optional):
  - `proptest` for property testing
  - `colored` for colored output

## Testing Strategy

- **Unit Tests**:
  - Macro behavior with valid/invalid results
  - Error formatting output
  - Generator output validity

- **Property Tests**:
  - Generated emails are valid/invalid as expected
  - Generated URLs are valid
  - Generated dates are valid ISO 8601

- **Doc Tests**:
  - All examples in rustdoc compile and pass

## Documentation Requirements

- **Code Documentation**: Comprehensive rustdoc
- **User Documentation**: README with examples
- **Architecture Updates**: Module documentation

## Implementation Notes

- Macros should work in both sync and async tests
- Error formatting should be readable even with many errors
- Property generators should be composable
- Consider `#[track_caller]` for better panic locations

## Migration and Compatibility

No migration needed - new test utilities.

## Files to Create/Modify

```
src/test_helpers.rs
src/generators.rs
src/lib.rs (documentation)
examples/basic_validation.rs
examples/cross_field.rs
examples/api_validation.rs
examples/schema_registry.rs
```

## Example Usage

```rust
use postmortem::{Schema, JsonPath, assert_valid, assert_invalid, assert_error_at};
use serde_json::json;

#[test]
fn test_user_validation() {
    let schema = Schema::object()
        .field("email", Schema::string().email())
        .field("age", Schema::integer().min(0));

    // Valid user
    let result = schema.validate(&json!({
        "email": "test@example.com",
        "age": 25
    }), &JsonPath::root());
    assert_valid!(result);

    // Invalid user - multiple errors
    let result = schema.validate(&json!({
        "email": "not-an-email",
        "age": -5
    }), &JsonPath::root());

    assert_invalid!(result, 2);  // Expect 2 errors

    if let Validation::Failure(errors) = result {
        assert_error_at!(errors, "email", "invalid_email");
        assert_error_at!(errors, "age", "min_value");
    }
}

// Property-based testing
#[cfg(feature = "proptest")]
mod prop_tests {
    use super::*;
    use postmortem::generators::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn valid_emails_pass_validation(email in valid_email()) {
            let schema = Schema::string().email();
            let result = schema.validate(&json!(email), &JsonPath::root());
            assert_valid!(result);
        }

        #[test]
        fn invalid_emails_fail_validation(email in invalid_email()) {
            let schema = Schema::string().email();
            let result = schema.validate(&json!(email), &JsonPath::root());
            assert_invalid!(result);
        }
    }
}
```