admixture-harness 0.1.0

Test harness with context lifecycle management and grouped execution
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
//! Test runner that executes all registered integration tests.

use crate::{ContextManager, TestDescriptor};
use std::collections::HashMap;
use tracing::{debug, error, info};

/// Result of running all tests.
#[derive(Debug)]
pub struct TestResults {
    pub total: usize,
    pub passed: usize,
    pub failed: usize,
    pub failures: Vec<TestFailure>,
}

/// Information about a failed test.
#[derive(Debug, Clone)]
pub struct TestFailure {
    pub name: String,
    pub file: String,
    pub line: u32,
    pub error: String,
}

impl TestFailure {
    /// Create a test failure for a context start failure.
    fn context_start_failed(test: &TestDescriptor, error: String) -> Self {
        Self {
            name: test.name.to_string(),
            file: test.file.to_string(),
            line: test.line,
            error: format!("Context startup failed: {}", error),
        }
    }

    /// Create a test failure for a hook failure.
    fn hook_failed(test: &TestDescriptor, hook_name: &str, error: String) -> Self {
        Self {
            name: test.name.to_string(),
            file: test.file.to_string(),
            line: test.line,
            error: format!("Hook '{}' failed: {}", hook_name, error),
        }
    }

    /// Create a test failure for a test failure.
    fn test_failed(test: &TestDescriptor, error: String) -> Self {
        Self {
            name: test.name.to_string(),
            file: test.file.to_string(),
            line: test.line,
            error,
        }
    }
}

impl TestResults {
    /// Check if all tests passed.
    pub fn all_passed(&self) -> bool {
        self.failed == 0
    }

    /// Print a summary of test results.
    pub fn print_summary(&self) {
        println!("\n{}", "=".repeat(80));
        println!("📊 Test Results Summary");
        println!("{}", "=".repeat(80));

        if self.failed == 0 {
            println!("   ✅ All tests passed!");
        } else {
            println!("   ⚠️  Some tests failed");
        }

        println!();
        println!("   Total:  {}", self.total);
        println!("   ✅ Passed: {}", self.passed);

        if !self.failures.is_empty() {
            println!("   ❌ Failed: {}", self.failed);
            println!("\n{}", "-".repeat(80));
            println!("❌ Failed Tests:");
            println!("{}", "-".repeat(80));
            for failure in &self.failures {
                println!("\n   Test: {}", failure.name);
                println!("   Location: {}:{}", failure.file, failure.line);
                println!("   Error: {}", failure.error);
            }
        }

        println!("{}", "=".repeat(80));
    }
}

/// Collect all registered integration tests.
pub fn collect_tests() -> Vec<&'static TestDescriptor> {
    inventory::iter::<TestDescriptor>().collect()
}

/// Run all registered integration tests, grouped by context type.
///
/// Tests sharing the same context type will reuse the same context instance.
/// This function initializes basic tracing for output.
#[tracing::instrument(name = "test_run", skip_all, fields(total_tests, context_types))]
pub async fn run_all_tests() -> TestResults {
    // Initialize basic tracing if not already initialized
    let _ = tracing_subscriber::fmt()
        .with_target(false)
        .with_test_writer()
        .try_init();

    let tests = collect_tests();

    tracing::Span::current().record("total_tests", tests.len());
    info!("Starting integration test run");

    // Group tests by context type
    let mut grouped_tests: HashMap<&str, Vec<&TestDescriptor>> = HashMap::new();
    for test in tests.iter() {
        grouped_tests
            .entry(test.context_type)
            .or_default()
            .push(test);
    }

    tracing::Span::current().record("context_types", grouped_tests.len());
    info!("Grouped tests by context type");

    run_all_tests_impl(tests, grouped_tests).await
}

/// Internal implementation of test runner.
///
/// This is exposed as a public API so that external tools (like admixture-tui)
/// can run tests with custom tracing layers.
pub async fn run_all_tests_impl(
    tests: Vec<&'static TestDescriptor>,
    grouped_tests: HashMap<&'static str, Vec<&'static TestDescriptor>>,
) -> TestResults {
    info!("Starting integration test run");

    // Run all context groups in parallel
    let futures: Vec<_> = grouped_tests
        .into_values()
        .map(|group| {
            let group_slice: &'static [&'static TestDescriptor] = Box::leak(group.into_boxed_slice());
            async move {
                // Call the type-erased entry point for this context type
                // Internally calls run_context_group<ConcreteType>
                (group_slice[0].run_group)(group_slice).await
            }
        })
        .collect();

    let group_results = futures::future::join_all(futures).await;

    // Aggregate results
    let mut passed = 0;
    let mut failed = 0;
    let mut failures = Vec::new();

    for group_result in group_results {
        passed += group_result.passed;
        failed += group_result.failed;
        failures.extend(group_result.failures);
    }

    let results = TestResults {
        total: tests.len(),
        passed,
        failed,
        failures,
    };

    info!(
        total = results.total,
        passed = results.passed,
        failed = results.failed,
        "Test run completed"
    );

    results.print_summary();

    results
}

/// Result from running a context group.
///
/// This is public so that it can be used in GroupRunnerFn.
pub struct ContextGroupResult {
    pub passed: usize,
    pub failed: usize,
    pub failures: Vec<TestFailure>,
}

/// Run all tests for a single context type with concrete type C.
///
/// This is the generic execution layer - all tests in the group share the same
/// context type C, so no type erasure or downcasting is needed.
#[tracing::instrument(
    name = "context_group",
    skip_all,
    fields(
        context_type = %context_type,
        test_count = tests.len(),
        status = tracing::field::Empty,
    )
)]
pub async fn run_context_group<C: Send + 'static>(
    context_type: &str,
    tests: &[(crate::TestFn<C>, &'static TestDescriptor)],
    manager: &dyn ContextManager<C>,
    hooks: crate::Hooks<C>,
) -> ContextGroupResult {
    info!(
        context_type = context_type,
        test_count = tests.len(),
        "CONTEXT_GROUP_START"
    );

    let mut passed = 0;
    let mut failed = 0;
    let mut failures = Vec::new();

    // Start the context once for all tests - concrete type C!
    tracing::Span::current().record("status", "starting context");
    let ctx = match manager.start().await {
        Ok(ctx) => ctx,
        Err(e) => {
            tracing::Span::current().record("status", "❌ failed to start");
            let error_msg = e.to_string();
            error!(error = %e, "Failed to start context");

            // Mark all tests in this group as failed
            for &(_, descriptor) in tests {
                failures.push(TestFailure::context_start_failed(descriptor, error_msg.clone()));
            }

            return ContextGroupResult {
                passed: 0,
                failed: tests.len(),
                failures,
            };
        }
    };

    tracing::Span::current().record("status", "✅ context ready");

    // Run before_all hook - direct call, no downcast!
    if let Some(before_all_fn) = hooks.before_all
        && let Err(e) = before_all_fn(&ctx).await {
        // before_all failed - fail all tests and stop
        error!(
            "before_all hook failed, skipping all tests in context {}",
            context_type
        );
        tracing::Span::current().record("status", "❌ before_all failed");

        for &(_, descriptor) in tests {
            failures.push(TestFailure::hook_failed(
                descriptor,
                "before_all",
                e.to_string(),
            ));
        }

        // Best-effort context stop
        if let Err(stop_err) = manager.stop(ctx).await {
            error!(error = %stop_err, "Failed to stop context after before_all failure");
        }

        return ContextGroupResult {
            passed: 0,
            failed: tests.len(),
            failures,
        };
    }

    // Run all tests with the shared context
    for &(test_fn, descriptor) in tests {
        // Run before_each hook - direct call, no downcast!
        if let Some(before_each_fn) = hooks.before_each
            && let Err(e) = before_each_fn(&ctx).await {
            failed += 1;
            failures.push(TestFailure::hook_failed(
                descriptor,
                "before_each",
                e.to_string(),
            ));

            // Run after_each even though test didn't run
            if let Some(after_each_fn) = hooks.after_each {
                let _ = after_each_fn(&ctx).await;
            }

            continue; // Skip to next test
        }

        // Run the test - direct call, no downcast!
        let test_result = run_test(descriptor, test_fn, &ctx).await;

        // Run after_each hook (always runs) - direct call, no downcast!
        if let Some(after_each_fn) = hooks.after_each
            && let Err(e) = after_each_fn(&ctx).await {
            // after_each failed - mark test as failed
            failed += 1;
            failures.push(TestFailure::hook_failed(
                descriptor,
                "after_each",
                e.to_string(),
            ));
            continue;
        }

        // Record test result
        match test_result {
            Ok(()) => {
                passed += 1;
            }
            Err(e) => {
                failed += 1;
                failures.push(TestFailure::test_failed(descriptor, e.to_string()));
            }
        }
    }

    // Run after_all hook (best-effort, doesn't fail tests) - direct call, no downcast!
    if let Some(after_all_fn) = hooks.after_all
        && let Err(e) = after_all_fn(&ctx).await {
        tracing::warn!("after_all hook failed (non-fatal): {}", e);
    }

    // Stop the context after all tests complete - concrete type C!
    tracing::Span::current().record("status", "🛑 stopping");
    if let Err(e) = manager.stop(ctx).await {
        error!(error = %e, "Failed to stop context");
        tracing::Span::current().record("status", "⚠️ completed with stop error");
    } else {
        tracing::Span::current().record("status", "✅ completed");
    }

    info!("CONTEXT_GROUP_END");

    ContextGroupResult {
        passed,
        failed,
        failures,
    }
}

/// Run a single test with concrete context type - no downcast needed!
#[tracing::instrument(
    name = "test",
    skip_all,
    fields(
        name = %descriptor.name,
        context_type = %descriptor.context_type,
        file = %descriptor.file,
        line = descriptor.line,
        result = tracing::field::Empty,
    )
)]
async fn run_test<C>(
    descriptor: &TestDescriptor,
    test_fn: crate::TestFn<C>,
    ctx: &C,
) -> Result<(), Box<dyn std::error::Error + Send>> {
    debug!("Running test");

    match test_fn(ctx).await {
        Ok(()) => {
            tracing::Span::current().record("result", "✅ passed");
            info!(name = descriptor.name, result = "✅ passed", "TEST_PASSED");
            Ok(())
        }
        Err(e) => {
            tracing::Span::current().record("result", "❌ failed");
            error!(name = descriptor.name, error = %e, "TEST_FAILED");
            Err(e)
        }
    }
}

/// Macro to generate a test runner function.
///
/// Use this in your test module to create a single test that runs all
/// `#[admixture_test]` tests. Automatically detects if TUI mode is enabled
/// via the ADMIXTURE_TUI environment variable.
///
/// # Example
///
/// ```ignore
/// use admixture_harness::test_runner;
///
/// test_runner!();
/// ```
#[macro_export]
macro_rules! test_runner {
    () => {
        #[tokio::test]
        async fn __run_all_admixture_tests() {
            let results = $crate::runner::run_all_tests().await;
            assert!(results.all_passed(), "{} test(s) failed", results.failed);
        }
    };
}