Skip to content

Latest commit

 

History

History
225 lines (176 loc) · 8.21 KB

ARCHITECTURE.md

File metadata and controls

225 lines (176 loc) · 8.21 KB

Architecture

Overview

testfold is a unified test runner that orchestrates multiple test frameworks (Jest, Playwright) with parallel execution and detailed failure reporting.

Layer Structure

┌─────────────────────────────────────────────────────┐
│                     CLI Layer                        │
│              src/cli/index.ts, args.ts               │
├─────────────────────────────────────────────────────┤
│                    Core Layer                        │
│     TestRunner → Orchestrator → Executor            │
├─────────────────────────────────────────────────────┤
│          Parsers              │      Reporters       │
│   JestParser, PlaywrightParser │ Console, JSON, MD   │
├─────────────────────────────────────────────────────┤
│                   Utils Layer                        │
│          ANSI, Files, Sanitize                       │
├─────────────────────────────────────────────────────┤
│                  Config Layer                        │
│           Schema, Loader, Types                      │
└─────────────────────────────────────────────────────┘

Component Descriptions

Config Layer (src/config/)

  • types.ts - TypeScript interfaces for configuration
  • schema.ts - Zod schemas for validation
  • loader.ts - Loads and validates config from file or object

Core Layer (src/core/)

  • runner.ts - TestRunner class, main entry point. Creates reporters (built-in + custom from file paths)
  • orchestrator.ts - Coordinates suite execution (parallel/sequential), guard-aware hooks, filter flag passing, and --file coverage: a requested file that selected no test in any selected suite fails the run with exit code 2
  • executor.ts - Spawns child processes with detached: true, captures output. SIGKILL escalation on timeout, workers→maxWorkers mapping, progress streaming via onOutput callback

Parsers (src/parsers/)

  • types.ts - Parser and ParseResult interfaces
  • jest.ts - Parses Jest JSON reporter output, crash detection from logs
  • playwright.ts - Parses Playwright JSON reporter output, crash detection from logs (missing/empty/corrupted JSON)
  • custom.ts - Lazy-loading custom parser from file path

Reporters (src/reporters/)

  • types.ts - Reporter interface
  • console.ts - Colored terminal output with summary table, artifact inventory, and test hierarchy display
  • json.ts - Generates summary.json with failedTests[], errors[], per-suite testResults[]
  • markdown.ts - Individual failure reports in Markdown with test hierarchy
  • timing.ts - Generates timing.json with tests sorted by duration
  • timing-text.ts - Per-suite .txt files with top slowest tests and file grouping
  • text.ts - Plain text output for CI/tool integration (no ANSI, no markdown)
  • summary-log.ts - ANSI-free test-summary.log matching console summary format
  • custom.ts - Dynamic loading of custom reporters from file paths

Utils (src/utils/)

  • ansi.ts - Strip ANSI escape codes
  • sanitize.ts - Sanitize strings for filenames
  • files.ts - Directory cleanup, file writing
  • file-filters.ts - Matches --file filters against the test files each suite ran; used by the orchestrator to fail runs where a requested file selected no test

CLI (src/cli/)

  • index.ts - Entry point, parses args, runs tests
  • args.ts - Argument parsing with minimist

Data Flow

1. Config Loading
   config file → loader.ts → schema validation → ValidatedConfig

2. Test Execution
   ValidatedConfig → TestRunner → Orchestrator

   Orchestrator:
   ├── For each suite (parallel or sequential):
   │   └── Executor.execute(suite.command)
   │       ├── Spawn process
   │       ├── Capture stdout/stderr
   │       └── Write log file
   │
   └── For each completed suite:
       └── Parser.parse(resultFile, logFile)
           └── ParseResult { passed, failed, failures[] }

3. Reporting
   ParseResult[] → AggregatedResults

   For each Reporter:
   ├── onStart(suites)
   ├── onSuiteComplete(suite, result)
   └── onComplete(aggregated)

Key Interfaces

Config

interface Config {
  artifactsDir: string;
  testsDir?: string;
  suites: Suite[];
  parallel?: boolean;
  failFast?: boolean;
  reporters?: ReporterType[];
  hooks?: Hooks;
}

interface Suite {
  name: string;
  type: 'jest' | 'playwright' | 'custom';
  command: string;
  resultFile: string;
  timeout?: number;
  workers?: number;
  env?: Record<string, string>;
  environments?: Record<string, EnvironmentConfig>;
}

Parser

interface Parser {
  parse(jsonPath: string, logPath: string): Promise<ParseResult>;
}

interface ParseResult {
  passed: number;
  failed: number;
  skipped: number;
  duration: number;
  success: boolean;
  failures: FailureDetail[];
}

Reporter

interface Reporter {
  onStart(suites: Suite[]): void;
  onSuiteComplete(suite: Suite, result: SuiteResult): void;
  onComplete(results: AggregatedResults): Promise<void> | void;
}

Extension Points

Custom Parsers

Implement Parser interface:

class CustomParser implements Parser {
  async parse(jsonPath: string, logPath: string): Promise<ParseResult> {
    // Parse custom format
  }
}

Custom Reporters

Implement Reporter interface:

class SlackReporter implements Reporter {
  onStart(suites: Suite[]) { /* notify */ }
  onSuiteComplete(suite: Suite, result: SuiteResult) { /* notify */ }
  async onComplete(results: AggregatedResults) { /* send summary */ }
}

Hooks

interface GuardResult {
  ok: boolean;
  error?: string;
}

hooks: {
  beforeAll: async () => { /* global setup */ },
  afterAll: async (results) => { /* global cleanup */ },
  beforeSuite: async (suite) => { /* suite setup, return GuardResult to gate */ },
  afterSuite: async (suite, result) => { /* suite cleanup, return GuardResult to gate */ }
}

beforeSuite/afterSuite can return GuardResult. If { ok: false }, the suite is marked failed regardless of test results.

Artifact Management

When running specific suites (testfold unit), only artifacts for those suites are cleaned before execution. Artifacts from other suites are preserved:

test-results/
  unit.json        # Cleaned (unit suite running)
  unit.log         # Cleaned
  integration.json # Preserved (not running)
  integration.log  # Preserved
  failures/
    unit/          # Cleaned
    integration/   # Preserved

This allows incremental test runs without losing results from previous suite executions.

Error Handling

  • Config validation errors throw immediately with detailed messages
  • Suite execution errors are captured and reported, don't stop other suites
  • Parser errors result in success: false with error in failures
  • Successful suites require a zero process exit, a valid successful parser result, and executed passing tests. Process interruption, enforced timeout and Playwright global errors prevent success even when parsed assertion failures are zero.
  • Completion diagnostics preserve partial assertion counts. Aggregate success requires every suite to succeed and its semantic exit code to be zero; consumers must not infer success from assertion counts alone.
  • Invalid custom categories or file metadata fail before downstream filter/reporter consumption. Incomplete process results leave file inventories unknown, so partial output cannot establish an unmatched-file failure.
  • File system errors logged but don't crash the runner