chicago_tdd_tools/
lib.rs

1//! Chicago TDD Tools
2//!
3//! A comprehensive testing framework for Chicago TDD (Classicist Test-Driven Development)
4//! methodology in Rust. Provides fixtures, builders, helpers, and advanced testing
5//! capabilities including property-based testing and mutation testing.
6//!
7//! ## Features
8//!
9//! - **Test Fixtures**: Reusable test fixtures with state management and test isolation
10//! - **Builders**: Fluent builders for test data and workflows
11//! - **Assertion Helpers**: Comprehensive assertion utilities
12//! - **Macros**: AAA pattern enforcement and test helpers
13//! - **Property-Based Testing**: QuickCheck-style random test generation
14//! - **Mutation Testing**: Test quality validation through mutations
15//! - **Coverage Analysis**: Test coverage reporting and analysis
16//!
17//! ## Chicago TDD Principles
18//!
19//! This framework enforces Chicago TDD principles:
20//!
21//! 1. **State-Based Testing**: Tests verify outputs and state, not implementation
22//! 2. **Real Collaborators**: Uses actual dependencies, not mocks
23//! 3. **Behavior Verification**: Tests verify what code does, not how
24//! 4. **AAA Pattern**: All tests follow Arrange-Act-Assert structure
25//!
26//! ## Usage
27//!
28//! ```rust
29//! use chicago_tdd_tools::prelude::*;
30//!
31//! # #[tokio::test]
32//! # async fn test_example() {
33//!     // Arrange: Create fixture
34//!     let fixture = TestFixture::new().unwrap_or_else(|e| panic!("Failed to create fixture: {}", e));
35//!
36//!     // Act: Execute test
37//!     let counter = fixture.test_counter();
38//!
39//!     // Assert: Verify state
40//!     assert!(counter >= 0);
41//! # }
42//! ```
43//!
44//! ## Module Organization
45//!
46//! Modules are organized into capability groups for better discoverability and maintainability:
47//!
48//! ### Core Testing Infrastructure (`core`)
49//! - `fixture`: Test fixtures and setup utilities
50//! - `async_fixture`: Async test fixtures with async traits (requires `async` feature)
51//! - `builders`: Fluent builders for test data
52//! - `assertions`: Assertion helpers and utilities
53//! - `macros`: Test macros for AAA pattern enforcement and assertions
54//! - `state`: Type-level AAA enforcement
55//! - `poka_yoke`: Error prevention through type-level safety (prevents invalid states)
56//! - `const_assert`: Compile-time assertions
57//! - `alert`: Alert helpers for visual problem indicators (with optional `log` crate integration)
58//!
59//! ### Advanced Testing Techniques (`testing`)
60//! - `property`: Property-based testing framework
61//! - `mutation`: Mutation testing framework
62//! - `snapshot`: Snapshot testing (requires `snapshot-testing` feature)
63//! - `concurrency`: Concurrency testing (requires `concurrency-testing` feature)
64//! - `cli`: CLI testing (requires `cli-testing` feature)
65//! - `generator`: Test code generation
66//!
67//! ### Quality & Validation (`validation`)
68//! - `coverage`: Test coverage analysis
69//! - `guards`: Guard constraint enforcement (`MAX_RUN_LEN` ≤ 8, `MAX_BATCH_SIZE`)
70//! - `jtbd`: Jobs To Be Done validation framework (validates code accomplishes intended purpose)
71//! - `performance`: RDTSC benchmarking and tick measurement
72//!
73//! ### Telemetry & Observability (`observability`)
74//! - `otel`: OTEL span/metric validation (requires `otel` feature)
75//! - `weaver`: Weaver live validation integration (requires `weaver` feature)
76//!
77//! ### Integration Testing (`integration`)
78//! - `testcontainers`: Docker container support (requires `testcontainers` feature)
79//!
80//! ## Backward Compatibility
81//!
82//! All modules are re-exported at the crate root for backward compatibility.
83//! Existing code using `chicago_tdd_tools::fixture::*` continues to work.
84//! New code is encouraged to use capability group paths: `chicago_tdd_tools::core::fixture::*`
85//!
86//! ## Macros
87//!
88//! The crate provides several macros to reduce boilerplate and enforce Chicago TDD principles:
89//!
90//! ## Procedural Macros
91//!
92//! - `#[tdd_test]`: Procedural macro for zero-boilerplate tests with AAA validation
93//!   - Import: `use chicago_tdd_tools::tdd_test;` (re-exported) or `use chicago_tdd_tools_proc_macros::tdd_test;`
94//! - `#[fixture]`: Procedural macro for automatic fixture setup/teardown
95//!   - Import: `use chicago_tdd_tools::fixture;` (re-exported) or `use chicago_tdd_tools_proc_macros::fixture;`
96//! - `#[derive(TestBuilder)]`: Derive macro for fluent builder generation
97//!
98//! ## Declarative Macros
99//!
100//! **Root Cause Fix**: All macros below are exported with `#[macro_export]`, making them
101//! available at the crate root **without import**. Importing them with `use` causes
102//! "unused import" errors. Use macros directly (e.g., `assert_ok!(result)`) without importing.
103//!
104//! **Exception**: In nested modules, you may need to use the full path (e.g., `chicago_tdd_tools::assert_ok!()`)
105//! or create a macro wrapper. See `tests/testcontainers/tests.rs` for an example.
106//!
107//! - `test!`: Enforce AAA pattern for synchronous tests
108//! - `async_test!`: Enforce AAA pattern for async tests
109//! - `fixture_test!`: Async test with automatic fixture setup/teardown
110//! - `performance_test!`: Performance test with tick budget validation
111//! - `assert_ok!`: Assert Result is Ok with detailed error messages
112//! - `assert_err!`: Assert Result is Err with detailed error messages
113//! - `assert_fail!`: Assert function call fails, returning error value for further assertions
114//! - `assert_within_tick_budget!`: Validate performance constraints (≤8 ticks)
115//! - `assert_in_range!`: Assert value is within range with detailed messages
116//! - `assert_eq_msg!`: Assert equality with custom message
117//! - `assert_guard_constraint!`: Validate guard constraints
118//! - `alert_critical!`: Emit critical alert (🚨) - must stop immediately
119//! - `alert_warning!`: Emit warning alert (âš ī¸) - should stop
120//! - `alert_info!`: Emit info alert (â„šī¸) - informational
121//! - `alert_success!`: Emit success alert (✅) - operation completed
122//! - `alert_debug!`: Emit debug alert (🔍) - detailed diagnostics
123//! - `alert!`: Emit custom alert with user-defined severity
124
125#![deny(clippy::unwrap_used)]
126#![deny(warnings)] // Poka-Yoke: Prevent warnings at compile time - compiler enforces correctness
127#![warn(missing_docs)]
128// Poka-Yoke: pub use is necessary for procedural macro re-exports
129#![allow(clippy::pub_use, reason = "Procedural macros must be re-exported via pub use")]
130// Test code - panic is appropriate for test failures
131#![cfg_attr(test, allow(clippy::panic))]
132
133// Note: When using the `logging` feature (enabled by default), users should initialize
134// the AlertLogger at the start of their application:
135//   use chicago_tdd_tools::alert::AlertLogger;
136//   let _ = AlertLogger::init_default();
137// This enables standard log macros (log::error!, log::warn!, etc.) to use the alert format.
138// Alert macros (alert_critical!, alert_warning!, etc.) also use log::* when logging is enabled.
139
140// Re-export procedural macros
141// Both #[tdd_test] and #[fixture] are re-exported at crate root for convenience
142// Users can import from chicago_tdd_tools: use chicago_tdd_tools::{tdd_test, fixture};
143// Or directly from chicago_tdd_tools_proc_macros: use chicago_tdd_tools_proc_macros::{tdd_test, fixture};
144pub use chicago_tdd_tools_proc_macros::fixture;
145pub use chicago_tdd_tools_proc_macros::tdd_test;
146
147// Re-export TestBuilder derive macro (users will use #[derive(TestBuilder)])
148pub use chicago_tdd_tools_proc_macros::TestBuilder;
149
150// Capability groups - organized by functionality
151//
152// **Kaizen improvement**: Module declaration pattern to prevent dead code.
153// All modules MUST be declared here (or in parent module's mod.rs).
154// Files not declared as modules are dead code and will be removed.
155// Pattern: Use `pub mod` for new modules, `pub use` for re-exports.
156// **Waste elimination**: Work reports and internal documentation don't belong in docs/.
157// Only user-facing documentation should be in docs/ (guides, API refs, architecture).
158pub mod core;
159pub mod integration;
160pub mod observability;
161pub mod operator_registry;
162pub mod sector_stacks;
163pub mod swarm;
164pub mod testing;
165pub mod validation;
166
167// Macros are exported via core::macros module
168// src/macros.rs re-exports from core::macros for backward compatibility
169// Note: #[macro_use] is not needed here - macros are exported via #[macro_export] in macro definitions
170pub mod macros;
171
172// Re-export new "go the extra mile" types
173pub use core::assertions::{AssertionBuilder, ValidatedAssertion};
174pub use core::builders::{GenericTestDataBuilder, ValidatedTestDataBuilder};
175pub use operator_registry::{
176    global_registry, GuardType, OperatorDescriptor, OperatorProperties, OperatorRegistry,
177};
178pub use sector_stacks::{academic, claims, OperationReceipt, OperationStatus, SectorOperation};
179pub use swarm::{
180    ComposedOperation, OperationChain, SwarmCoordinator, SwarmMember, TaskReceipt, TaskRequest,
181    TaskStatus,
182};
183pub use validation::coverage::{CoveragePercentage, CoveredCount, TotalCount};
184pub use validation::jtbd::ScenarioIndex;
185pub use validation::performance::ValidatedTickBudget;
186
187// Backward compatibility: Re-export modules at crate root for existing code
188// New code should use capability group paths: core::fixture, validation::guards, etc.
189pub use core::{alert, assertions, builders, const_assert, fail_fast, fixture, invariants, state};
190// Note: async_fixture is separate because it's feature-gated (requires `async` feature)
191#[cfg(feature = "async")]
192pub use core::async_fixture;
193#[cfg(feature = "testcontainers")]
194pub use integration::testcontainers;
195// Note: testcontainers::poka_yoke is NOT re-exported via glob to avoid conflicts with otel::poka_yoke
196#[cfg(feature = "otel")]
197pub use observability::otel;
198// Note: otel::poka_yoke is NOT re-exported via glob to avoid conflicts with testcontainers::poka_yoke
199#[cfg(feature = "weaver")]
200pub use observability::weaver::types::WeaverLiveCheck;
201#[cfg(feature = "weaver")]
202pub use observability::weaver::{WeaverValidationError, WeaverValidationResult};
203// Unified observability API (new)
204#[cfg(any(feature = "otel", feature = "weaver"))]
205pub use observability::{ObservabilityError, ObservabilityResult, ObservabilityTest};
206#[cfg(feature = "cli-testing")]
207pub use testing::cli;
208#[cfg(feature = "concurrency-testing")]
209pub use testing::concurrency;
210#[cfg(feature = "snapshot-testing")]
211pub use testing::snapshot;
212pub use testing::{generator, mutation, property};
213pub use validation::{coverage, guards, jtbd, performance};
214
215/// Prelude module - import everything you need with `use chicago_tdd_tools::prelude::*;`
216///
217/// **Usage**:
218/// ```rust,ignore
219/// use chicago_tdd_tools::prelude::*;
220///
221/// test!(my_test, {
222///     // All macros and types available
223/// });
224/// ```
225///
226/// **What's included**:
227/// - All core modules (fixture, builders, assertions, macros)
228/// - All validation modules (coverage, guards, jtbd, performance)
229/// - Feature-gated modules (when features enabled): property, mutation, snapshot, concurrency, cli
230pub mod prelude {
231    // Re-export core modules explicitly to avoid poka_yoke conflicts
232    pub use crate::core::{
233        alert, assertions, async_fixture, builders, const_assert, contract, fail_fast, fixture,
234        invariants, receipt, state, test_utils, type_level, verification_pipeline,
235    };
236    // poka_yoke is accessed via core::poka_yoke::* to avoid conflicts with otel/testcontainers poka_yoke
237    pub use crate::validation::*;
238
239    // Macros are automatically exported via #[macro_export] in macro definitions
240    // They can be used directly: test!, assert_ok!, etc.
241    // Or explicitly: use chicago_tdd_tools::{test, assert_ok};
242
243    #[cfg(feature = "property-testing")]
244    pub use crate::testing::property::*;
245
246    #[cfg(feature = "mutation-testing")]
247    pub use crate::testing::mutation::*;
248
249    #[cfg(feature = "snapshot-testing")]
250    pub use crate::testing::snapshot::*;
251
252    #[cfg(feature = "concurrency-testing")]
253    pub use crate::testing::concurrency::*;
254
255    #[cfg(feature = "cli-testing")]
256    pub use crate::testing::cli::*;
257
258    #[cfg(feature = "otel")]
259    pub use crate::observability::otel::{
260        MetricValidator, OtelValidationError, OtelValidationResult, SpanValidator,
261    };
262    // Note: otel::poka_yoke is NOT re-exported via glob to avoid conflicts with testcontainers::poka_yoke
263
264    #[cfg(feature = "weaver")]
265    pub use crate::observability::weaver::{WeaverValidationError, WeaverValidationResult};
266
267    // Unified observability API (new)
268    #[cfg(any(feature = "otel", feature = "weaver"))]
269    pub use crate::observability::{ObservabilityError, ObservabilityResult, ObservabilityTest};
270
271    #[cfg(feature = "testcontainers")]
272    pub use crate::integration::testcontainers::{
273        ContainerClient, ExecResult, GenericContainer, TestcontainersError, TestcontainersResult,
274    };
275    // Note: testcontainers::poka_yoke is NOT re-exported via glob to avoid conflicts
276
277    // Hyper-advanced Îŧ-kernel verification substrate (Track 1-6)
278    // Track 1: Test Contracts as First-Class Types (already in core::*)
279    // Track 2: Ī„-Aware Test Harness (already in validation::*)
280    // Track 3: Effect-Typed Tests
281    pub use crate::testing::effects::*;
282    // Track 4: Type-Directed State Machine Testing
283    pub use crate::testing::state_machine::*;
284    // Track 5: Proof-Carrying Test Receipts (already in core::*)
285    // Track 6: Swarm-Native Test Orchestrator
286    pub use crate::swarm::test_orchestrator::*;
287}