Skip to content

Test Authoring Standards โ€‹

This document defines the mandatory test-authoring standards for the YaoXiang project. All contributors must comply with the following rules; violations will be required to be corrected during code review.


Table of Contents โ€‹


General Principles โ€‹

Scope โ€‹

This specification applies to all Rust test code in the YaoXiang project, including:

Test TypeLocationFramework
Unit testsrc/<module>/tests/#[test] + #[cfg(test)]
Integration testtests/#[test]
Benchmarkbenches/Criterion.rs
Documentation testAPI documentation commentscargo test --doc
Property testAny test locationproptest / quickcheck

Core Principles โ€‹

Principle 0: The authoritative source for tests is the specification, not the code. This is the most important principle in this document. Tests verify whether the code conforms to the specification, not whether it "passes with the current implementation." When a test finds that the code behavior differs from the specification, fix the code; never change the test to accommodate it.

The specification files are located at:

  • docs/src/reference/language-spec/ โ€” core language specifications
  • docs/rfc/accepted/ โ€” accepted RFC design documents

Every test file must declare the corresponding specification section at the top (see Rule 2.1). Any developer should be able to compare the tests against the specification and verify the correctness of the implementation. Conversely, if a piece of code has no corresponding specification, it should not exist, let alone be tested.

rust
// ๐ŸŸข Good โ€” the test directly references the specification and verifies that the code follows it
//! Literal tests โ€” based on Language Specification ยง2.6
//!
//! ยง2.6.1: Integers: Decimal, Octal(0o), Hex(0x), Binary(0b)
//! ยง2.6.2: Floating-point numbers (with decimal points and exponents)
//! ยง2.6.3: Strings (escape sequences \\nrt'"\\, \\x, \\u{})
//! RFC-012: F-String interpolation

#[test]
fn test_decimal_literal_parsing() {
    // Specification ยง2.6.1: Decimal ::= [0-9][0-9_]*
    let result = parse_literal("42").unwrap();
    assert_eq!(result, Literal::Int(42));
}

// ๐Ÿ”ด Bad โ€” the test accommodates the current implementation instead of verifying the specification
#[test]
fn test_literal_1() {
    // No idea which specification section this corresponds to
    // If parse_literal returns an incorrect value, this test will "pass with a green light"
    // Because it only verifies that the function does not panic
    let result = parse_literal("42");
    assert!(result.is_ok());
}

Scenario: You write a test and discover that the code behavior differs from the specification. You have two choices:

Wrong ApproachCorrect Approach
Change the test so it "passes"Change the code so it follows the specification
Add #[ignore] to the testFix the implementation immediately
Add a special conditional branch to accommodate the codeRemove the branch and let the test expose the problem directly

Remember: A red light means the code is wrong, not the test. (Unless the test itself has a bug, which is a separate issue.)

Principle 1: Tests are documentation. Any developer should be able to understand the behavior of the code under test by reading the tests, without additional comments or external documentation.

rust
// ๐ŸŸข Good โ€” the test name states what is tested and what is expected
#[test]
fn test_tokenize_empty_input_returns_eof() {
    let tokens = tokenize("").unwrap();
    assert_eq!(tokens.len(), 1);
    assert!(matches!(tokens[0].kind, TokenKind::Eof));
}

// ๐Ÿ”ด Bad โ€” no one knows what this tests
#[test]
fn test_tokenize_1() {
    let tokens = tokenize("").unwrap();
    assert!(tokens.len() > 0);
}

Principle 2: Zero tolerance for flaky tests. Tests must be repeatable in any environment. Tests that depend on random numbers, system time, or thread scheduling order must use fixed seeds or mocks instead.

Principle 3: One test verifies one thing. If the test name needs to connect multiple behaviors with "and," split it into multiple tests.

rust
// ๐ŸŸข Good โ€” each test verifies only one scenario
#[test]
fn test_parse_int_positive() { /* ... */ }
#[test]
fn test_parse_int_zero() { /* ... */ }

// ๐Ÿ”ด Bad โ€” one test contains too much unrelated content
#[test]
fn test_parser() {
    // Test tokenize, parse, typecheck, codegen...
}

Principle 4: Test behavior, not implementation. Refactoring the internal implementation should not cause tests to fail. If changing one line of implementation code causes 10 tests to fail, the tests are written incorrectly.

However, there is one critical distinction: the definition of "behavior" comes from the specification, not from the behavior of the current code. If the code changes its behaviorโ€”that is, adopts new behavior that does not conform to the specificationโ€”the tests must fail. If you cannot accomplish this, your test is a "test that accommodates the code"โ€”it allows bugs to take root.

Specification (language-spec.md / RFC)  โ”€โ”€definesโ”€โ”€โ–บ  Expected behavior  โ”€โ”€drivesโ”€โ”€โ–บ  Tests
                                           โ”‚
Current code  โ”€โ”€implementsโ”€โ”€โ–บ  Actual behavior  โ”€โ”€compared withโ”€โ”€โ–บ  Test results

If actual behavior โ‰  expected behavior:
  The test must fail (red light)  โ”€โ”€โ–บ  Fix the code  โ”€โ”€โ–บ  The test passes (green light)

If actual behavior = expected behavior (but the implementation is poor):
  The test passes  โ”€โ”€โ–บ  Refactor the implementation  โ”€โ”€โ–บ  The test still passes  โ† This is the meaning of Principle 4

Principle 5: Do not write fallback, compatibility, or mode-specific test code. The test environment is fully under your control. If you need #[cfg(not(ci))] to skip a test, the test has a fundamental design problem.

Definitions โ€‹

TermDefinition
Unit testTests the behavior of an individual function or module without relying on external systems
Integration testTests collaboration among multiple modules through the public API or a command-line entry point
BenchmarkMeasures code performance and detects performance regressions
Documentation testExecutable code examples embedded in documentation comments
Property testTests invariants using random inputs (properties)

Relationship to Commit Conventions โ€‹

All test-related commits must use the :white_check_mark: test: type. See the commit conventions.

:white_check_mark: test(parser): Add Pratt parser infix expression tests
:white_check_mark: test(codegen): Complete IR generation tests for switch statements

yx Corpus and Library Test Layers โ€‹

This specification governs Rust-side test code. Tests for the YaoXiang language itself (.yx corpora and library tests) are divided into two layers according to the object under test. The system design and adjudication contract are governed by RFC-036 (ยง7 suite collection / ยง8 three-layer negative testing / ยง9 test-system layering), while corpus-authoring details are governed by tests/yaoxiang/TEST_STANDARDS.md:

  • Language usability corpus (tests/yaoxiang/) โ€” the object under test is the language itself; std is used only as an assertion tool. Within the corpus, tests are classified into three categories according to the layer at which failure occurs: behavior tests / compile-time rejection tests / runtime failure tests
  • Library tests (distributed with the library) โ€” the object under test is the library's public API contract; std's yx-level tests are located in src/std/tests/, and tests for future user packages are discovered within each package via [tool.test]

The file header format for .yx tests, header directives (// expect: / // skip: / // mode:, RFC-036 ยง8.2), and assertion conventions are defined by TEST_STANDARDS.md. Result adjudication is implemented by src/util/test_markers.rs, shared by both runners (on the Rust side and subject to this specification).


Unit Test Standards โ€‹

File Organization โ€‹

Rule 1.1: A unit test's tests/ directory must be at the same level as the mod.rs of the module under test. tests/ directories must not aggregate upward or summarize across levels.

src/frontend/core/parser/
โ”œโ”€โ”€ mod.rs              # #[cfg(test)] mod tests; โ€” declares the sibling tests/
โ”œโ”€โ”€ ast.rs
โ”œโ”€โ”€ pratt/
โ”‚   โ”œโ”€โ”€ mod.rs          # #[cfg(test)] mod tests; โ€” declares pratt's own tests
โ”‚   โ””โ”€โ”€ tests/
โ”‚       โ”œโ”€โ”€ mod.rs
โ”‚       โ”œโ”€โ”€ led.rs
โ”‚       โ”œโ”€โ”€ nud.rs
โ”‚       โ””โ”€โ”€ precedence.rs
โ””โ”€โ”€ tests/              # parser module-level tests (excluding pratt submodule content)
    โ”œโ”€โ”€ mod.rs
    โ”œโ”€โ”€ ast.rs
    โ”œโ”€โ”€ expressions.rs
    โ”œโ”€โ”€ error_recovery.rs
    โ””โ”€โ”€ parser_state.rs

The key criterion is: wherever the tests/ directory is placed, that directory's mod.rs must declare it with #[cfg(test)] mod tests;.

Rule 1.1 Supplement: Upward aggregation is prohibited. Tests for a submodule must be placed in that submodule's own tests/ directory and must not be aggregated into the parent tests/ directory.

Module TypeTest LocationExample
Directory module (has mod.rs)tests/ under that directoryemitter/tests/, codes/tests/
Single-file module (only .rs)Parent's tests/session.rs โ†’ diagnostic/tests/session.rs
text
# โœ… Correct: each directory module has independent tests
src/util/diagnostic/
โ”œโ”€โ”€ codes/
โ”‚   โ”œโ”€โ”€ mod.rs              # #[cfg(test)] mod tests;
โ”‚   โ””โ”€โ”€ tests/              # โœ… codes' own tests
โ”‚       โ”œโ”€โ”€ mod.rs
โ”‚       โ””โ”€โ”€ codes.rs
โ”œโ”€โ”€ emitter/
โ”‚   โ”œโ”€โ”€ mod.rs              # #[cfg(test)] mod tests;
โ”‚   โ””โ”€โ”€ tests/              # โœ… emitter's own tests
โ”‚       โ”œโ”€โ”€ mod.rs
โ”‚       โ”œโ”€โ”€ text.rs
โ”‚       โ””โ”€โ”€ ansi.rs
โ””โ”€โ”€ tests/                  # โœ… diagnostic-level tests (single-file modules)
    โ”œโ”€โ”€ mod.rs
    โ”œโ”€โ”€ session.rs
    โ”œโ”€โ”€ suggest.rs
    โ””โ”€โ”€ collect.rs

# โŒ Wrong: aggregating emitter and codes tests into diagnostic/tests/
src/util/diagnostic/
โ””โ”€โ”€ tests/
    โ”œโ”€โ”€ mod.rs              # โŒ forced to declare mod emitter; mod codes;
    โ”œโ”€โ”€ emitter/            # โŒ should be in emitter/tests/
    โ””โ”€โ”€ codes/              # โŒ should be in codes/tests/

Test Placement Rules for Single-File Modules vs. Directory Modules โ€‹

Core distinction: the module's organizational form determines where its tests are placed.

Module TypeIdentificationTest LocationExample
Directory moduleHas a dedicated directory and mod.rstests/ under that directoryinference/tests/
Single-file moduleHas only a .rs file and no dedicated directoryParent module's tests/overload.rs โ†’ typecheck/tests/overload.rs

Detailed explanation:

src/frontend/core/typecheck/
โ”œโ”€โ”€ mod.rs                          # typecheck module's mod.rs
โ”œโ”€โ”€ checker.rs                      # Single-file module
โ”œโ”€โ”€ environment.rs                  # Single-file module
โ”œโ”€โ”€ overload.rs                     # Single-file module
โ”œโ”€โ”€ type_eval.rs                    # Single-file module
โ”œโ”€โ”€ dead_code.rs                    # Single-file module
โ”œโ”€โ”€ spawn_placement.rs              # Single-file module
โ”œโ”€โ”€ signature.rs                    # Single-file module
โ”œโ”€โ”€ types.rs                        # Single-file module
โ”‚
โ”œโ”€โ”€ tests/                          # โœ… typecheck test directory
โ”‚   โ”œโ”€โ”€ mod.rs                      # Declares tests for single-file modules
โ”‚   โ”œโ”€โ”€ checker.rs                  # Tests for checker.rs
โ”‚   โ”œโ”€โ”€ environment.rs              # Tests for environment.rs
โ”‚   โ”œโ”€โ”€ overload.rs                 # Tests for overload.rs (tests for a single-file module go here)
โ”‚   โ”œโ”€โ”€ type_eval.rs                # Tests for type_eval.rs
โ”‚   โ”œโ”€โ”€ dead_code.rs                # Tests for dead_code.rs
โ”‚   โ”œโ”€โ”€ spawn_placement.rs          # Tests for spawn_placement.rs
โ”‚   โ”œโ”€โ”€ signature.rs                # Tests for signature.rs
โ”‚   โ””โ”€โ”€ types.rs                    # Tests for types.rs
โ”‚
โ”œโ”€โ”€ inference/                      # Directory module (has mod.rs)
โ”‚   โ”œโ”€โ”€ mod.rs                      # #[cfg(test)] mod tests; โ€” declares sibling tests/
โ”‚   โ”œโ”€โ”€ expressions.rs
โ”‚   โ”œโ”€โ”€ statements.rs
โ”‚   โ”œโ”€โ”€ bounds.rs
โ”‚   โ”œโ”€โ”€ subtyping.rs
โ”‚   โ”œโ”€โ”€ generics.rs
โ”‚   โ”œโ”€โ”€ compatibility.rs
โ”‚   โ”œโ”€โ”€ scope.rs
โ”‚   โ”œโ”€โ”€ assignment.rs
โ”‚   โ””โ”€โ”€ tests/                      # โœ… inference test directory
โ”‚       โ”œโ”€โ”€ mod.rs
โ”‚       โ”œโ”€โ”€ expressions.rs          # Tests for expressions.rs
โ”‚       โ”œโ”€โ”€ statements.rs           # Tests for statements.rs
โ”‚       โ””โ”€โ”€ ...
โ”‚
โ””โ”€โ”€ traits/                         # Removed (logic merged into types/trait_data.rs)

Why are tests for single-file modules placed in the parent tests/ directory?

A single-file module such as overload.rs has no mod.rs of its own, so it cannot declare #[cfg(test)] mod tests;. Under Rust's module system, test files must be declared by a mod.rs to compile. Therefore, tests for a single-file module can only be declared by the parent module's mod.rs and placed in the parent tests/ directory.

Decision process:

When encountering a module, where should its tests go?
โ”‚
โ”œโ”€โ”€ Is the module a directory (with mod.rs)?
โ”‚   โ””โ”€โ”€ Yes โ†’ Create tests/ under that directory and declare it from that directory's mod.rs
โ”‚
โ”œโ”€โ”€ Is the module a single file (only .rs)?
โ”‚   โ””โ”€โ”€ Yes โ†’ Place the tests in the parent tests/ directory and declare them from the parent's mod.rs
โ”‚
โ””โ”€โ”€ Unsure?
    โ””โ”€โ”€ Check whether it has a dedicated directory and mod.rs

Common errors:

# โŒ Error 1: creating a dedicated tests/ directory for a single-file module
src/frontend/core/typecheck/
โ”œโ”€โ”€ overload.rs
โ””โ”€โ”€ overload/                       # โŒ Do not create a directory for a single-file module
    โ””โ”€โ”€ tests/
        โ””โ”€โ”€ overload.rs

# โŒ Error 2: declaring #[cfg(test)] mod tests; inside a single-file module
# overload.rs
#[cfg(test)]                        # โŒ A single-file module cannot declare this
mod tests;                          # Because there is no overload/tests/ directory

# โœ… Correct approach: place the tests in the parent tests/
src/frontend/core/typecheck/
โ”œโ”€โ”€ overload.rs                     # Source file
โ””โ”€โ”€ tests/
    โ””โ”€โ”€ overload.rs                 # Test file, declared by typecheck/mod.rs

โš ๏ธ Anti-patternโ€”do not do this:

# โŒ Wrong: concentrating submodule tests in the parent
src/frontend/core/types/
โ”œโ”€โ”€ mod.rs              # Should declare only base and computation
โ”œโ”€โ”€ base/
โ”‚   โ”œโ”€โ”€ mod.rs
โ”‚   โ””โ”€โ”€ var.rs
โ””โ”€โ”€ tests/              # โŒ Parent tests/ contains submodule tests
    โ”œโ”€โ”€ mod.rs          # โŒ Forced to declare mod base; mod computation;
    โ”œโ”€โ”€ base/           # โŒ This belongs in base/tests/
    โ”‚   โ””โ”€โ”€ var.rs
    โ””โ”€โ”€ computation/    # โŒ This belongs in computation/tests/
        โ””โ”€โ”€ ...
# โœ… Correct approach: each module's tests remain independent
src/frontend/core/types/
โ”œโ”€โ”€ mod.rs              # Declares only pub mod base; pub mod computation;
โ”œโ”€โ”€ base/
โ”‚   โ”œโ”€โ”€ mod.rs          # #[cfg(test)] mod tests; โ€” declares sibling tests/
โ”‚   โ”œโ”€โ”€ var.rs
โ”‚   โ””โ”€โ”€ tests/
โ”‚       โ”œโ”€โ”€ mod.rs
โ”‚       โ””โ”€โ”€ var.rs
โ””โ”€โ”€ computation/
    โ”œโ”€โ”€ mod.rs          # #[cfg(test)] mod tests; โ€” declares sibling tests/
    โ”œโ”€โ”€ operations.rs
    โ””โ”€โ”€ tests/
        โ”œโ”€โ”€ mod.rs
        โ””โ”€โ”€ operations.rs

Why is upward aggregation prohibited? Rust's module system requires #[cfg(test)] mod tests; to determine where test files are compiled at the declaration site. If types/mod.rs declares mod tests;, the contents of types/tests/ are private contents of the types moduleโ€”they should not cross into the territory of base or computation. Each module's tests should be an internal implementation detail of that module, not of its parent. This rule also applies during module refactoring: when you split types into base and computation, the tests should move with the split modules rather than remain in place. The test directory does not mirror the source structure; it follows module boundaries.

Rule 1.2: tests/mod.rs is responsible only for module declarations and re-exports; it must not contain test functions.

rust
//! Parser core tests โ€” mirrors src/frontend/core/parser/
//!
//! Tests for ast.rs, parser_state.rs, and expression/integration parsing.

mod ast;
mod error_recovery;
mod expressions;
mod integration;
mod parser_state;

Rule 1.3: Each test file corresponds to exactly one source file. Tests for multiple source modules must not be mixed into one file.

Rule 1.4: Test declarations must use the file form mod tests; (with a semicolon), pointing to the sibling tests/ directory. The inline form mod tests { ... }, which places test code directly in the source file, is prohibited.

rust
// โœ… Correct โ€” file-form declaration; test code lives in a separate file
// src/frontend/core/parser/mod.rs
#[cfg(test)]
mod tests;

// ๐Ÿ”ด Forbidden โ€” inline form; test code is embedded in the source file
// src/frontend/core/parser/mod.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_something() {
        // Test code should not appear in the source file
    }
}

Why is the inline form prohibited?

  1. Single responsibility for source files: source files contain only implementations, and test files contain only tests. Mixing them means scrolling to the bottom of a file to modify tests and skipping tests to modify the implementation.
  2. Clear module boundaries: the tests/ directory provides a physical boundary that makes it immediately apparent which modules have tests and which do not.
  3. Refactoring safety: when modules are split, the tests/ directory moves with them; inline tests must be manually extracted from the source files.
  4. Code review: source changes and test changes appear in separate files in the PR diff rather than being mixed together.

Module Declaration Standards โ€‹

Rule 2.1: Every test file must have a module-level documentation comment //! at the top, describing the specification sources covered by the test (language specification section number + RFC number). If a test does not reference any specification section, the code has no specification basisโ€”it should not exist.

rust
//! Literal tests โ€” based on Language Specification ยง2.6
//!
//! ยง2.6.1: Integers: Decimal, Octal(0o), Hex(0x), Binary(0b)
//! ยง2.6.2: Floating-point numbers (with decimal points and exponents)
//! ยง2.6.3: Strings (escape sequences \\nrt'"\\, \\x, \\u{})
//! RFC-012: F-String interpolation

Why must the specification be referenced? The expected values in tests come from the specification, not from the "current output of the code." If the code's output changes one day and the test is updated accordingly, the test protects nothing. Only specification-anchored tests can distinguish an intentional breaking change from an unintentional regression.

Rule 2.2: A test module's use imports must be precise down to the specific type or function. Glob imports such as use super::* are prohibited.

rust
// ๐ŸŸข Good โ€” precise imports
use crate::frontend::core::lexer::{tokenize, TokenKind};
use crate::frontend::core::parser::{ParserState, ParseError};

// ๐Ÿ”ด Bad โ€” no one knows what you are testing
use super::*;

Naming Standards โ€‹

Rule 3.1: Test function names must follow the format test_<what>_<scenario>, using lowercase words separated by underscores.

rust
#[test]
fn test_tokenize_empty_string() { /* ... */ }
#[test]
fn test_parse_int_overflow() { /* ... */ }
#[test]
fn test_typecheck_fn_return_mismatch() { /* ... */ }

Rule 3.2: Test function names must be self-explanatory. After reading the function name, one should know what is tested and what is expected. Numeric sequence names are prohibited.

rust
// ๐ŸŸข Good
fn test_skip_semicolon_success() { /* ... */ }
fn test_skip_semicolon_failure_when_identifier() { /* ... */ }

// ๐Ÿ”ด Bad โ€” no idea what is being tested
fn test_skip_1() { /* ... */ }
fn test_skip_2() { /* ... */ }

Rule 3.3: Helper functions do not need the test_ prefix; use a verb or noun that describes their purpose.

rust
fn parse_expr(source: &str) -> Expr { /* ... */ }
fn tokenize_single(source: &str) -> Token { /* ... */ }
fn setup_parser_with_tokens(tokens: &[Token]) -> ParserState { /* ... */ }

Test Structure Standards (Arrange-Act-Assert) โ€‹

Rule 4.1: Every test function must follow the three-part structure: Arrange โ†’ Act โ†’ Assert, with blank lines separating the three parts.

rust
#[test]
fn test_parse_binary_addition() {
    // Arrange
    let source = "1 + 2";

    // Act
    let expr = parse_expr(source);

    // Assert
    assert!(matches!(expr, Expr::Binary { op: BinOp::Add, .. }));
}

Rule 4.2: Simple tests (a single call + a single assertion) may omit the section comments, but must not exceed 5 lines of logical code. Tests longer than 5 lines must explicitly identify all three sections.

Helper Function Standards โ€‹

Rule 5.1: Setup logic that occurs three or more times must be extracted into a helper function.

rust
// ๐ŸŸข Good โ€” extract common setup
fn with_state<F>(source: &str, mut f: F)
where
    F: FnMut(&mut ParserState<'_>),
{
    let tokens = tokenize(source).unwrap();
    let mut state = ParserState::new(&tokens);
    f(&mut state);
}

#[test]
fn test_current_returns_first_token() {
    with_state("42", |state| {
        let tok = state.current();
        assert_eq!(&tok.unwrap().kind, &TokenKind::IntLiteral(42));
    });
}

Rule 5.2: An unwrap() / expect() in a helper function must print sufficient context when it panics. It is acceptable to call unwrap() directly inside a test function body (#[test] fn ...)โ€”Rust automatically prints the line number on failure; however, a failure inside a helper function points to the helper's definition and does not show the context of the call site.

rust
// ๐ŸŸข Good โ€” the helper prints the source content on failure
fn run_ok(source: &str) {
    run(source).unwrap_or_else(|e| panic!("Execution failed:\nSource:\n{}\nError:\n{:?}", source, e));
}

// ๐Ÿ”ด Bad โ€” on failure, you cannot tell which source file caused the problem
fn run_ok(source: &str) {
    run(source).unwrap();
}

Rule 5.3: Helper functions should be placed at the top of the test file, immediately after the use imports. If shared by multiple test modules, place them in tests/mod.rs and export them with pub(crate).

Assertion Style โ€‹

Rule 6.1: Enum variant matching should prefer assert!(matches!(...)); using if let + panic! is prohibited.

rust
// ๐ŸŸข Good
assert!(matches!(tokens[0].kind, TokenKind::IntLiteral(42)));

// ๐Ÿ”ด Bad
if let TokenKind::IntLiteral(v) = tokens[0].kind {
    assert_eq!(v, 42);
} else {
    panic!("Expected IntLiteral");
}

Rule 6.2: Use assert_eq! for exact-value comparisons and assert! for Boolean assertions. Using assert!(a == b) in place of assert_eq!(a, b) is prohibited.

Rule 6.3: Every assertion must include a custom error message unless the assertion itself fully describes the reason for failure.

rust
// ๐ŸŸข Good โ€” quickly locate the failure
assert!(
    state.infix_info().is_some(),
    "infix_info should handle '{op}'"
);

// ๐ŸŸข Good โ€” assert_eq! automatically prints the value diff, so no extra message is needed
assert_eq!(error_count, 0);

// ๐Ÿ”ด Bad โ€” on failure, you only know "assertion failed"
assert!(state.infix_info().is_some());

Rule 6.4: Assertions must use the order assert_eq!(actual, expected), with the actual value first and the expected value second.

Anti-Pattern Checklist โ€‹

The following prohibited patterns and their alternatives are listed below:

Anti-PatternProblemAlternative
#[cfg(test)] mod tests { ... } inline testsBloats source files, blurs module boundaries, makes refactoring difficultPlace test code in a separate tests/ directory and declare it with mod tests; (see Rule 1.4)
Tests accommodate incorrect code behaviorHide specification deviations and legitimize bugsCorrect the code against the specification and leave the tests unchanged
Test expectations are inferred from code outputTurn tests into a "recording of the current implementation"Derive expected values from the specification
Permanent #[ignore] markersHide rotting testsFix or remove them
println! debug outputPollutes test outputUse explicit assert! assertions
thread::sleepFlaky tests + slow executionUse synchronization mechanisms or mocks
Manipulating the real file system in testsSlow and non-reproducibleUse tempfile
Dependence on test execution orderFlaky testsSet up each test independently
A test function exceeds 30 lines of logicNo one can understand itSplit the test or use helper functions
An unwrap() in a helper function provides no contextDifficult to locateUse expect("why") or a custom panic message (see Rule 5.2)
The same setup is copy-pasted more than 3 timesHigh maintenance costExtract a helper function

Integration Test Standards โ€‹

Test Organization โ€‹

Rule 7.1: Integration tests are placed in the project root's tests/ directory. The entry file tests/integration.rs uses the #[path] attribute to include submodules.

rust
// tests/integration.rs
#[path = "integration/backends.rs"]
mod backends;
#[path = "integration/codegen.rs"]
mod codegen;
#[path = "integration/execution.rs"]
mod execution;

Rule 7.2: Every tests/integration/*.rs file corresponds to one test topic (compiler backend, code generation, executor, etc.), and topics must not be mixed.

Rule 7.3: Integration tests must exercise the project through its public API. Directly referencing internal crate:: modules in integration tests is prohibited. Use the public yaoxiang:: paths.

rust
// ๐ŸŸข Good โ€” through the public API
use yaoxiang::run;

// ๐Ÿ”ด Bad โ€” bypasses the public API boundary
use yaoxiang::middle::codegen::bytecode::BytecodeFile;

Test Data Management โ€‹

Rule 8.1: Integration tests should prefer inline source strings. Use an external fixture file only when the source exceeds 30 lines (stored in tests/fixtures/).

rust
#[test]
fn test_fibonacci() {
    run_ok(
        r#"
        // ๅ†…่”ๆบ็ ไปฅ Script ๆจกๅผ่ฟ่กŒ๏ผš้กถๅฑ‚่ฏญๅฅๅณ็จ‹ๅบไธปไฝ“๏ผˆSPEC syntax ยง3.11๏ผ‰ใ€‚
        // ๅธฆๅž‹ main ่‹ฅไธๆ˜พๅผ่ฐƒ็”จๅชๆ˜ฏๆƒฐๆ€ง lambdaโ€”โ€”ๅพช็Žฏไฝ“ๆฐธ่ฟœไธไผšๆ‰ง่กŒใ€‚
        main: () -> Void = {
            mut a = 0
            mut b = 1
            while a < 100 {
                mut next = a + b
                a = b
                b = next
            }
        }
        main()
        "#,
    );
}

Rule 8.2: Fixture files must end with the .yx extension, and their filenames must describe the test's intent.

E2E Coverage Principles โ€‹

Rule 9.1: The integration test for every language feature must cover three paths:

PathDescription
Happy pathValid input produces the expected output
Error pathInvalid input produces a clear error message (not a panic)
BoundaryBoundary values (empty input, maximum value, maximum nesting depth)

Rule 9.2: Integration tests must not depend on the network, system environment variables, or external services.

Rule 9.3: After the corpora (tests/yaoxiang/, src/std/tests/, tests/yaoxiang-multifile/) pass check with exit code 0, run must not report errors from the same families as compile-time errors: E0 lexical/syntax, E1 type, E2 semantic, E3 code generation, E4 generics, E5 modules. The authoritative source for family-to-category mappings is ErrorCategory in src/util/diagnostic/codes/mod.rs; run reporting only E6โ€“E8 (runtime / I/O / internal) does not constitute a violation.

The criteria are enforced by python scripts/ci/check-soundness.py. As of 2026-11-06, it has been enabled as a blocking gate: pre-commit runs it with --strict when the staging area contains corpus .yx files, and the CI Test job runs it on every push. Any divergence results in exit 1. --report-only is retained as a manual troubleshooting mode (always exits with 0) and is not used by any gate. After the gate was enabled, temporary exceptions may only be obtained through Part Five of the coding rules (// reason: + exemption count included in the gate report); do not revert the hook to report-only. The gate criteria (three known divergence categories reduced to zero + mutation self-verification + time budget) and measured figures are documented in the script's header comments.

The criteria surface consists of the three corpus locations listed above and is the same as the record set for the corpus differential baseline. The three E3 criteria surfaces (e3005-mono-max-depth, e3020-missing-main-binding, and e3022-entry-signature under tests/yaoxiang-multifile/) are checked in with // expect: compile-error E30XX: the corresponding implementation defects were fixed on 2026-11-06 (E3005: [mono] now propagates through the check chain; E3020 / E3022: entry-contract adjudication added to check), so their "success" form is a compilation failure. Writing them as compile-time rejections records the contract rather than a violation. There are two regression guards: if the check-side criterion is rolled back, the expect criterion in yx_multifile_runner turns red; simultaneously, the probe records any case where run still reports the same code as one divergence of "check passes โ‡’ run reports E0โ€“E5".


Benchmark Standards โ€‹

Criterion.rs Usage Standards โ€‹

Rule 10.1: Benchmarks must be placed uniformly in the benches/ directory, with benches/lib.rs as the entry file. Organize them into files by test topic.

benches/
โ”œโ”€โ”€ lib.rs              # Entry point; defines criterion_group/criterion_main
โ”œโ”€โ”€ lang_compare/
โ”‚   โ””โ”€โ”€ fibonacci.rs    # Cross-language comparison benchmark
โ”œโ”€โ”€ parser.rs           # Parser benchmark
โ””โ”€โ”€ codegen.rs          # Code generation benchmark

Rule 10.2: Every benchmark function must include a module documentation comment //! describing the test's purpose and measurement metric.

rust
//! YaoXiang interpreter performance benchmark
//!
//! Measurement metric: time per iteration (wall time)
//! Baseline: native Rust implementation

Preventing Compiler Optimization โ€‹

Rule 11.1: The output of every benchmark under test must be passed through criterion::black_box to prevent the compiler from eliminating it through optimization.

rust
use criterion::{black_box, Criterion};

fn bench_parse(c: &mut Criterion) {
    c.bench_function("parse_fib", |b| {
        b.iter(|| {
            let result = parse(black_box(FIB_SOURCE));
            black_box(result)
        })
    });
}

Rule 11.2: Benchmark input data must be const or use lazy_static; it must not be generated dynamically inside the iter closureโ€”otherwise, the measurement includes the time spent generating the data in addition to the logic under test.

Benchmark Grouping and Naming โ€‹

Rule 12.1: Benchmark names must follow the format <module-under-test>_<scenario>, using lowercase words separated by underscores. This is consistent with the unit test naming rules.

Rule 12.2: Related benchmarks must be logically grouped with criterion_group!. Cramming all benchmarks into one group is prohibited.

rust
criterion_group!(parser, bench_parse_expr, bench_parse_stmt);
criterion_group!(codegen, bench_codegen_module, bench_codegen_switch);
criterion_main!(parser, codegen);

Documentation Test Standards โ€‹

Use Cases โ€‹

Rule 13.1: Every pub function, type, and method must include at least one runnable code example in its documentation comments. The example is executed through cargo test --doc.

rust
/// Tokenizes a source string into a sequence of Tokens.
///
/// ```
/// use yaoxiang::frontend::core::lexer::tokenize;
///
/// let tokens = tokenize("42").unwrap();
/// assert_eq!(tokens.len(), 2); // IntLiteral + Eof
/// ```
pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
    // ...
}

Rule 13.2: Documentation test examples must compile and their assertions must succeed. Examples marked ignore are prohibited unless the example demonstrates a compile-time error.

rust
/// ```ignore
/// // Demonstrates a compile-time errorโ€”ignore is allowed
/// let x: int = "string";
/// ```

Coverage Requirements โ€‹

Rule 14.1: Documentation tests only need to cover the happy path of an API. Edge cases and error paths are covered by unit tests.

Rule 14.2: Example code in documentation tests must be conciseโ€”no more than 10 lines. If an example needs more context, the API design has a problem.


Property Test Standards โ€‹

Use Cases โ€‹

Rule 15.1: The following scenarios must use property tests (proptest or quickcheck) instead of hand-written cases with multiple boundary values:

ScenarioExample
Parser round-tripparse(pretty_print(ast)) == ast
Serialization/deserializationdeserialize(serialize(data)) == data
Mathematical-operation identitiesa + b == b + a
Compiler optimization preserves semanticseval(code) == eval(optimize(code))

Rule 15.2: Property tests use proptest as the primary property-testing framework (already declared in Cargo.toml under dev-dependencies).

rust
use proptest::prelude::*;

proptest! {
    #[test]
    fn test_roundtrip_serialize_deserialize(value: i64) {
        let serialized = serialize(&value);
        let deserialized: i64 = deserialize(&serialized).unwrap();
        prop_assert_eq!(deserialized, value);
    }
}

Property Definition Principles โ€‹

Rule 16.1: Every property test must have an explicit property declarationโ€”the comment must state the invariant being verified.

rust
// Property: any integer literal produces the same value after tokenize โ†’ tokens_to_string
proptest! {
    #[test]
    fn test_int_literal_roundtrip(n in any::<i64>()) {
        let source = n.to_string();
        let tokens = tokenize(&source).unwrap();
        // ...
    }
}

Rule 16.2: If a property test finds a failure, use proptest's regression mechanismโ€”add the failing input to the proptest-regressions/ directory. Do not replace it with a hand-written ordinary test.


Coverage Requirements โ€‹

Coverage Targets for New Code โ€‹

Rule 17.1: Coverage requirements for new code are:

Code TypeLine CoverageBranch Coverage
Core compiler modules (frontend/middle/backends)โ‰ฅ 85%โ‰ฅ 80%
Utility/helper modules (util)โ‰ฅ 75%โ‰ฅ 70%
Runtime modules (vm/runtime)โ‰ฅ 80%โ‰ฅ 75%
Standard library (std)โ‰ฅ 75%โ‰ฅ 70%
Error handling and diagnosticsโ‰ฅ 90%โ‰ฅ 85%

Rule 17.2: Error-handling paths (all Err branches) must have 100% coverage. Every user-visible error message must be verified by a test.

PR Review Checklist โ€‹

Rule 18.1: Before submitting a PR, the author must verify the following:

  • [ ] python scripts/dev/testsuite.py run fast passesโ€”the pre-submission self-check runs --lib (src/ unit tests) and four integration-side targets (integration / formatter_integration / yx_runner / yx_multifile_runner); the first stage of pre-commit runs this command, and the second runs cargo test --all --quiet to block the commit
  • [ ] cargo test --doc passesโ€”doctests are not covered by run fast and are handled by the CI test job
  • [ ] cargo bench shows no performance regressions (if hot-path changes are involved)
  • [ ] New code meets the coverage targets
  • [ ] Test names comply with the naming standards
  • [ ] Every test file declares the corresponding specification section (Rule 2.1)
  • [ ] Test expectations come from the specification, not from the "current output of the code"
  • [ ] There are no tests marked #[ignore] (unless accompanied by an explicit issue-number comment)
  • [ ] There are no unnecessary unwrap() calls (use expect or a custom panic message instead)
  • [ ] The commit message uses the :white_check_mark: test: type
  • [ ] No test expectation was changed because "the code behavior differs from the specification"โ€”change the code, not the tests
  • [ ] There are no inline tests (#[cfg(test)] mod tests { ... } must be replaced with mod tests; + separate files; see Rule 1.4)

Rule 18.2: A Reviewer must reject a PR that contains any of the following problems:

  • Only happy-path tests, with missing error paths
  • thread::sleep in tests or dependence on execution order
  • Copy-pasted test code repeated more than 3 times without extracting a helper function
  • Test names that do not comply with the naming standards
  • Tests permanently marked #[ignore]
  • Tests that accommodate incorrect code behavior (when the code differs from the specification, the test was changed instead of the code)
  • Tests that do not declare the corresponding specification section (see Rule 2.1)
  • Test expectations derived from code output rather than the specification (inferred tests are effectively no tests)
  • Inline tests (#[cfg(test)] mod tests { ... } instead of mod tests; + separate files; see Rule 1.4)
  • Tests that only verify "does not panic" without asserting concrete behavior
  • A failing test that exposed a code bug was deleted instead of fixing the code and then observing it turn green

Test Resource Profiles and Budget Channels โ€‹

Peak memory and execution time for tests are declared in place (cost: markers), without a central manifestโ€”the boundary approved by RFC-036 on 2026-09-06: a central manifest inevitably becomes stale. The only consumer is scripts/dev/testsuite.py: markers provides bidirectional guards, plan prints budget bin packing, and run fast|full executes tests by channel.

Rule 19.1: Every #[ignore] test must have a cost: marker. Unmarked tests are estimated at YX_TEST_DEFAULT_PEAK per thread (128 MiB by default) for bin packing. The marker must be in a comment block immediately above #[test], on a single line, with order-independent keys separated by spaces:

text
// cost: peak=<ๆ•ดๆ•ฐ><B|KiB|MiB|GiB>  time=<ๆ•ดๆ•ฐๆˆ–ๅฐๆ•ฐ>s  mode=shared|exclusive|manual  source=...
/// cost: ...   # The documentation-comment form is also accepted

Unknown keys, unknown units, unknown mode values, and unknown source forms are all hard errors (python scripts/dev/testsuite.py markers --check).

Rule 19.2: mode has three levels, whose semantics are fixed by the consumer:

LevelSemantics
sharedDefault level; executed concurrently according to budget bin packing
exclusiveRuns in an exclusive wave (not concurrently with other tests); the test body must call crate::util::test_support::exclusive_lock("<test name>"), with the argument matching the test name verbatim; a missing call or mismatched argument is a marker violation
manualPermanently #[ignore] and never executed implicitly; running the entire suite with cargo test -- --ignored is prohibited (it would execute this level and snapshot regeneration); tests must be run explicitly by name

Rule 19.3: source answers the question "where did this number come from?": measured@YYYY-MM-DD (measured) or extrapolated@<no-space rationale identifier> (extrapolated); a missing source for exclusive / manual is a hard error. New or modified markers must be measured; extrapolation is allowed only when measurement is impractical and must include the rationale. Calibration rounds must convert extrapolated values into measured values.

Rule 19.4: Channels and exit codes:

  • run fast: pre-submission self-check (the first stage of pre-commit); exclusive waves that do not fit are listed individually as "N skipped" rather than being silently skipped;
  • run full: pre-push and CI baseline; insufficient budget results in exit 2 and a list of the shortfall;
  • Marker violations or test failures result in exit 1; environment errors result in exit 3.

The channel baseline is reconciled among scripts/ci/check-test-channel.py, pre-commit, CI, and HOWTO.

Rule 19.5: The default timeout for waiting on an exclusive lock is 600 s, overridable through YX_TEST_LOCK_TIMEOUT (whole seconds); a timeout causes a panic (the message includes the lock path), with no silent skipping or fallback to defer. Lock files are placed under the shared target/test-budget/<test name>.lock path for cross-process mutual exclusion; the first lock collision prints blocked on <path>.


Appendix โ€‹

A. Test Command Quick Reference โ€‹

bash
# Run all tests
cargo test

# Run only unit tests
cargo test --lib

# Run only integration tests
cargo test --test integration

# Run only documentation tests
cargo test --doc

# Run a specific test (filtered by name)
cargo test test_parse_expr

# Run benchmarks
cargo bench

# Display test output (stdout is hidden by default)
cargo test -- --nocapture

# Run single-threaded (to diagnose concurrency issues)
cargo test -- --test-threads=1

# Generate a coverage report (requires cargo-llvm-cov)
cargo llvm-cov --html

B. Commit Message Template โ€‹

Test-related commits must follow this template:

:white_check_mark: test(<scope>): <short description>

<Optional: list of covered scenarios>

Example:

:white_check_mark: test(parser): Add Pratt parser infix operator tests

Covered scenarios:
- Arithmetic operator precedence (+, -, *, /, %)
- Comparison operator chaining (1 < x < 10)
- Logical operator short-circuiting
- Right-associative assignment operators

C. Checklist for Adding a Test File โ€‹

When creating a new test module, ensure that it contains the following files:

# Add tests under src/<module>/
src/<module>/tests/
โ”œโ”€โ”€ mod.rs          # Module declarations + shared helper functions
โ””โ”€โ”€ <subject>.rs    # Test file, named after the source file under test

# Add integration tests under tests/
tests/
โ”œโ”€โ”€ integration.rs   # Update: add the #[path] declaration
โ””โ”€โ”€ integration/
    โ””โ”€โ”€ <topic>.rs   # New test file

D. References โ€‹


๐Ÿ’ก Remember: Tests do not verify whether your code "can run"โ€”they verify whether your code conforms to the specification. When the specification changes, the tests change with it. If the code is wrong, fix the code, not the test. Code serves the specification, and tests safeguard the specification. The moment a test accommodates the code, you have lost all protection.