RFC-036: std.test Test Framework and the yaoxiang test Command
Summary
This RFC introduces the standard std.test testing framework module and the yaoxiang test CLI subcommand for YaoXiang. Test files are ordinary .yx files, and their overall pass/fail status is determined by the subprocess exit code. A file may contain multiple test functions: assertion failures are represented as Err values (value semantics), and the suite collects per-test verdicts (§7). The std.test module is implemented purely in YaoXiang and is the first dogfooding library. yaoxiang test is a CLI tool, not a compiler feature, and requires no changes to the parser, IR, bytecode, or executor.
Motivation
Why is a testing framework needed?
YaoXiang's current test coverage relies on Rust-side #[test] attributes and tests/ integration tests. This means:
- Unit tests for the standard library (std.math / std.list / std.dict / std.convert / std.io) cannot be written in YaoXiang
- Unit-test coverage for each standard-library module is blocked by the lack of usable testing infrastructure
- Regression tests for language features, such as the RFC-032 spawn semantic changes, have no automated mechanism
Key Constraints
- 17-keyword iron law: No new keywords or syntactic constructs may be introduced
- Zero compiler changes: The parser, IR, bytecode, and executor must remain untouched
- Dogfooding first: The test library is written in YaoXiang and is the first dogfooding library
Architecture
┌──────────────────────────────────────────────────────────────┐
│ yaoxiang test │
│ │
│ CLI 层: yaoxiang test [--filter --fail-fast --json ...] │
│ │ │
│ 发现层: 读取 yaoxiang.toml → [tool.test] patterns │
│ 默认: tests/**/*.yx │
│ │ │
│ 执行层: 对每个文件: yaoxiang run <file> │
│ 检查 exit code → 串行执行 │
│ │ │
│ 报告层: PASS/FAIL → 汇总 │
│ 支持 --json / --verbose / --fail-fast │
│ │
│ 断言层: std.test (纯 YaoXiang,自举) │
│ 底层: std.assert.assert │
│ 诊断: f"Expected {expected}, got {actual}" │
└──────────────────────────────────────────────────────────────┘Core Principles
- The testing framework is not a compiler feature but a CLI tool —
yaoxiang runcan already "run tests";yaoxiang testmerely runs all files for you and provides a report - Zero compiler changes — No
@testannotation scanning, bytecode metadata section, or executor-specific entry point is introduced - Dogfooding — The
std.testmodule is implemented purely in YaoXiang, with its underlying capabilities provided bystd.assert/std.result - Test files are ordinary
.yxfiles — Each file runs in a subprocess, and its exit code determines the overall pass/fail result - An assertion failure is a value, not a process event — A test function returns
Result, and an assertion failure is expressed asErr; the suite collects per-test verdicts individually (§7). Process-level abort is reserved for runtime guards and is not used for test assertions
Detailed Design
1. CLI Design
yaoxiang test [OPTIONS] [PATHS]
Arguments:
[PATHS]... 指定测试文件或目录(默认: 从 yaoxiang.toml 读取,否则 tests/)
Options:
--filter <NAME> 只跑文件名包含 <NAME> 的测试
--fail-fast 遇到第一个失败就停止
--verbose, -v 显示每个测试的详细 stdout/stderr
--list 只列出测试文件,不跑
--no-progress 不显示进度输出(表头与 PASS 行);FAIL 明细与汇总保留(CI 场景)
--json 输出 JSON 格式结果(CI 集成用)
--parallel 并行执行(每核一个 worker;与 [tool.test].parallel 取或)Output Formats
Default output (per-test verdicts come from in-file suite collection; see §7):
Running 3 test files...
tests/math_test.yx ........................ PASS (0.002s)
tests/list_test.yx ........................ FAIL (0.003s)
`-- [FAIL] push_grows_len: Expected 3, got 2
`-- [ ok ] pop_returns_last
Results: 2 files passed, 1 file failed, 0 skipped (0.006s)
Categories: 2 behavior, 0 compile-error, 0 runtime-errorJSON output (--json):
{
"summary": {
"total": 3,
"passed": 2,
"failed": 1,
"skipped": 0,
"by_kind": { "behavior": 3, "compile-error": 0, "runtime-error": 0, "invalid": 0 },
"time_secs": 0.006
},
"files": [
{ "file": "tests/math_test.yx", "kind": "behavior", "passed": true, "time_secs": 0.002 },
{
"file": "tests/list_test.yx",
"kind": "behavior",
"passed": false,
"time_secs": 0.003,
"exit_code": 1,
"stderr": "error [E1024]: one is not two",
"tests": [
{ "name": "push_grows_len", "passed": false, "error": "Expected 3, got 2" },
{ "name": "pop_returns_last", "passed": true }
]
}
]
}- Failed files additionally carry
exit_codeandstderr(child-process diagnostics after ANSI stripping, for CI evidence); when--verboseand--jsonare combined, all files carrystdout/stderr --no-progresssuppresses only progress output (the header and PASS lines)—FAIL details and the summary are always emitted, and failures can never be silent;--listoutputs one test-file path per line without executing anything- Each file carries a
kind(behavior / compile-error / runtime-error / invalid, §8.2), and the summary carriesby_kindexecution counts (four fixed keys, excluding skipped); the human-readable summary also includes aCategories:distribution line - Under
--parallel, human-readable progress lines are streamed in completion order (entire blocks do not interleave), while JSONfilesare sorted byfilepath to ensure stable output (friendly to CI diffs) - The per-test
testsarray within each file comes from the suite collection described in §7 and takes effect as the value-semantics model is implemented - The official CI (
.github/workflows/ci.ymltest job) consumes the output in this form: the Cargo side runs--test integration(CLI integration) and--test yx_runner(dual-root corpus guard), after whichyaoxiang test --json --parallelperforms layered test runs—the default mode (language corpus) and the explicitsrc/std/tests(library layer) each produce a report. The summary table (total / passed / failed / skipped / time_secs and by_kind) is written to the job summary; failed files printkind/exit_code/stderras evidence; and any suite with a nonzero exit causes the job to fail
2. yaoxiang.toml Configuration
The configuration is placed under [tool.test], following RFC-015's third-party extension convention for [tool.*]:
[project]
name = "my-project"
[tool.test]
patterns = ["tests/**/*.yx"]
exclude = ["tests/fixtures/**"] # Matches are removed from the discovered set (also excluded by --list)
parallel = true # Run in parallel (ORed with the --parallel flag)- The default is
patterns = ["tests/**/*.yx"]—users can begin with zero configuration excludehas the same form aspatterns(literal paths orroot/**…, all matched by path prefix); an excluded file is not a test, and fixtures that require runtime behavior verification should be run directly withyaoxiang run- Single-file mode (
yaoxiang test foo.yx) runs directly and does not read configuration—when explicit paths are provided, neither theexcludenorparallelconfiguration keys apply (flags excepted) - The project may eventually be split into a separate repository (the
[tool.test]location remains unchanged)
3. std.test Module (Pure YaoXiang)
// std/test.yx — Pure YaoXiang test assertion library (standard value-semantics form, delivered 2026-09-03)
// First dogfooding library: YaoXiang's test library is written in YaoXiang.
use std.result
assert_eq: (a: Any, b: Any) -> Result(Void, String) = (a, b) => {
if a == b { return result.ok(void) }
return result.err(f"Expected {b}, got {a}")
}
assert_ne: (a: Any, b: Any) -> Result(Void, String) = (a, b) => {
if a != b { return result.ok(void) }
return result.err(f"Expected not equal to {b}, got {a}")
}
assert_true: (cond: Bool) -> Result(Void, String) = (cond) => {
if cond { return result.ok(void) }
return result.err(f"Expected true, got {cond}")
}
// assert_not shares its implementation with assert_false; see §8.1 for assert_err / assert_err_code- Assertion functions use value semantics: they return
Result(Void, String), express failures asErr(diagnostic information), and do not abort the process. The §7 suite uses this to collect per-test verdicts. The process-level abort semantics ofstd.assert.assertremain available for runtime guards and are not part of the test-assertion path. The Ok payload isVoid(the unit type specified by type-system.md;()is an empty Tuple, and the two are not mixed—this was finalized on 2026-09-03) - Seven-function family (delivered 2026-09-03; the transitional abort version was removed): value-based
assert_eq/assert_ne/assert_true/assert_false+assert_not(which shares its implementation withassert_falseand is reserved for a future!assertform) +assert_err(§8.1)assert_err_code(§8.1 error-code assertion)assert_approx_eq(a: Float, b: Float, eps: Float)(Phase 3, delivered 2026-09-07): determines whether|a - b| <= eps. The caller must explicitly provideeps—tolerance is part of the test contract, and there is no hidden default. Declaring a negativeepsyieldsErrimmediately, and NaN always yieldsErr
assert_eq/assert_neuse Any-annotated parameters—==/!=and f-string interpolation work correctly on Any and do not depend on the generics system. Note that parameters must be explicitly annotated: parameters without annotations fail the native generic&Result(T, E)call check (as demonstrated by the R1 probe)assert_false/assert_notexpress negation ascond == false(the unarynotsyntax has not yet been implemented and may be migrated later; the unary!assertform has the same dependency; see §8.1)- Block body + explicit
returnform: the then-arm type of an if expression is discarded during checking, and the two-arm Result if expression is a checking blind spot, so the implementation avoids it std.testdoes not depend on any native code and is implemented purely in YaoXiang
4. Standard Library Loading Mechanism (Key Design)
Phase 1: Embedded in the binary
std/test.yx (and all future standard-library modules written in YaoXiang) is embedded in the binary at build time:
// build.rs or a build script, generated automatically
pub const STD_YX_FILES: &[(&str, &str)] = &[
("std/test.yx", r#"..."#), // Source code text
// More in the future
];The module system (RFC-029, fully implemented on 2026-08-02) provides the integration point: the Registry holds both native and source modules, while the orchestrator handles multi-file orchestration. The resolution order for use std.test is:
- First, look for a Rust native module (the existing mechanism, such as
std.assert) - If no match is found, look in the embedded
STD_YX_FILES; on a match, inject a virtual path (such as<std>/test.yx) as the seed module into the orchestrator and pass it through the normal frontend pipeline (parse → typecheck → IR) - If no match is found, use filesystem discovery (user modules)
A use std.assert inside an embedded source module is resolved normally by the resolver to the native registry. Native and source modules coexist in the Registry, making cross-kind dependencies work naturally. Embedded modules are compiled on demand: they enter the pipeline only when imported.
Advantages:
use std.testworks even in single-file mode- The standard-library version is strictly bound to the binary, preventing version mismatches
- Users do not need to configure a standard-library path
Future: Filesystem-based standard library
Once YaoXiang's project mode matures, the standard library will move to a filesystem-based form. See the update to RFC-014.
5. Discovery and Execution
Prerequisite (review decision from 2026-08-02): The CLI run command must be connected to the orchestrator. The current CLI run path uses the single-file pipeline (run_file_with_diagnostics) and cannot resolve user-module imports; the subprocess model of yaoxiang test inherits the CLI's capabilities, and test files importing project modules are a core use case. Phase 1 therefore first delegates the CLI Run source branch to run_project (the orchestrator, with recursive directory discovery); on-demand discovery along use is layered on later as a pure performance optimization. A single file without imports behaves equivalently through the orchestrator, and the bytecode branch remains unchanged.
Discovery phase:
- If
[PATHS]are specified, use those paths directly - Otherwise, read
[tool.test].patternsfromyaoxiang.toml - If there is no configuration, use
tests/**/*.yxby default - Apply
--filterfiltering (the filename contains the filter) - The discovery scope is also the test layering (§9): the default patterns cover only the language-availability corpus; the library-test layer, such as
src/std/tests/, is discovered through an explicit path or package configuration and is not mixed into the default scan - A project directory is not a loose collection of tests: when recursive discovery encounters a directory containing
yaoxiang.toml, that directory is a project (the manifest is the project identity marker and the basis for determining its Bin role). Discovery includes only its conventional entry point,main.yx; it does not recurse into the project or collect the other.yxfiles in the same directory (those are project modules imported throughuse). The rationale is that module files have nomainby definition and would necessarily report a "missing main binding" when run independently, while placing non-test.yxfiles (fixtures or library modules) undertests/is a valid layout—discovery must not rely on the invalid assumption that every.yxfile undertests/**is an independently runnable test. If a project directory has no entry point, no files are discovered (a project is not a loose collection of tests), and this is not treated as an error boundary - Every
.yxfile that does not belong to a project directory is treated as a test target—this is the definition of the default rule. If a non-test helper.yxfile must be placed elsewhere, put it in a project directory or exclude it through[tool.test].exclude(the existing Phase 3 mechanism)
Execution phase:
- Dispatch each file according to its header directives (the directive grammar is described in §8.2 and parsed by
src/util/test_markers.rs, shared with yx_runner):- Behavior test:
yaoxiang run <file>subprocess. Runtime errors include the source location and stack frames by default—debug_mapis generated by default, and stack traces outputfile:line:col. A// mode:declaration selects the subprocess--runtimemode - Compile-time rejection: a single
yaoxiang check <file>step - Runtime failure: a two-step
check(must pass) plusrun(must fail)
- Behavior test:
- Files with
// skip: <reason>are not executed and are counted as skipped in the report - Verdicts are compared against the expected codes according to the §8.2 decision matrix; a directive parse failure is not executed and fails immediately (construction-time rejection)
- Capture stdout/stderr for the report
- Serial execution is the default;
--parallel(or[tool.test].parallel) starts a worker pool sized by the number of available cores. Each file remains an independent subprocess—skip/invalid entries are handled first in discovery order, execution results are streamed in completion order, and JSON output is sorted by path (Phase 3, delivered 2026-09-07) - With
--fail-fast, stop scheduling new files immediately after the first FAIL; in parallel mode, in-flight files finish and are counted
6. Test Isolation
Test isolation is naturally provided by process-level boundaries:
- Each test file runs in an independent subprocess
- Each subprocess has an independent Heap, Frame, and NativeContext
- A panic in one test file does not affect other test files
- No additional independent Heap context mechanism is needed
- Parallel execution (Phase 3) does not expand the isolation boundary: subprocesses share the working directory (CWD), so parallel tests must not use files at the same path within the CWD—file-I/O tests should use distinct filenames and clean them up when finished
7. Suites and Multiple Tests (Value-Semantics Model)
A test file may contain multiple tests. The in-file organization is as follows (implemented on 2026-09-03):
// tests/list_test.yx
use std.list
use std.result
use std.test
push_grows_len: () -> Result(Void, String) = () => {
xs = [1]
extended = list.push(xs, 2)
test.assert_eq(list.len(extended), 2)
}
pop_returns_last: () -> Result(Void, String) = () => {
mut xs = [1, 2]
last = list.pop(xs)
test.assert_eq(last, 2)
}
main: () -> Void = {
test.suite([
("push_grows_len", () => push_grows_len()),
("pop_returns_last", () => pop_returns_last()),
])
}- Each test is a zero-argument function returning
Result(Void, String). Assertion failures are expressed asErr(§3's value-semantics assertion family) and do not interrupt the process—subsequent tests continue to run test.suiteinvokes and collects each test in turn: if a test does not return Ok, its name and diagnostic are recorded; Ok results remain silent. After all tests have run, if any result is Err, the suite aborts viastd.assert.assertwith failure details (N of M test(s) failedplus one[FAIL] name: diagnosticentry per failure), and the file exits with a nonzero code (§5's decision rules remain unchanged). This abort is a runtime guard in the test binary, not part of the assertion path; when all tests return Ok, it exits silently with code 0- Top-level test functions are registered as closures (
("name", () => test_fn())): using a top-level function name directly as a value is not yet supported (an IR-layer limitation,E3006), but a closure that invokes the global function is unaffected - The runner sees only the file and performs no function-level scanning: per-test verdicts come entirely from collection within the suite, leaving the file's internal structure transparent to the runner and preserving the zero-compiler-change principle
- Explicitly not used: an in-process catch boundary (the 17-keyword iron law) or runner-driven invocation of individual function entry points (limited to internal scenarios such as the §8.2 compile-failure cases)
- The API shape was finalized on 2026-09-03:
suite(tests: List((String, () -> Result(Void, String)))) -> Void; duplicate names are not detected (names are used only for reporting), and--filterfilters by filename without being aware of test names inside a suite
8. Negative Tests (Expected Failures): A Three-Layer Design
Negative tests are assigned to layers according to where the failure occurs.
8.1 Value-Level Negatives (General-Purpose, User-Facing)
The operation under test returns a Result, and the test expresses the expected failure through ordinary assertions:
r = range.iter(invalid_range)
test.assert_err(r)
e = result.unwrap_err(r)
test.assert_eq(result.code(e), "E6009")
// Or use a single wrapper (the code exists only on the std Error carrier, with E fixed to Error):
test.assert_err_code(r, "E6009")assert_not/assert_err/assert_err_codewere delivered with the value-semantics family on 2026-09-03 (§3). The unary!assertform will be provided once thenotsyntax is implemented, subject to the same constraint asassert_false'scond == false- Error-code assertions depend on the
Errorvalue carrying a machine-readablecodefield, which has been implemented asError = { code, message }(nativeerror_new(code, message)). The carrier is obtained withresult.unwrap_err(r), followed by theresult.code(e)/result.message(e)accessors. The design-stage estimates for the nameerror_new_with_code, code-constant exports, and directerr.codefield access were not adopted—the language has no Struct field access, and code constants are not exported - As Result conversion advances, fallible operations progressively return
Result, and file-level negative markers in the corpus are migrated to in-file assertions
8.2 File-Level Negative Directives (For Language Designers Only)
Compilation is all-or-nothing for an entire file, so it is impossible to express "this line should not compile" within the file. Runtime failures likewise require file-level expression, such as a suite containing a test that must fail. The file header declares expectations through structured directives, and the runner dispatches its verdict by expected category (dispatch model finalized on 2026-09-03; directive grammar finalized and implemented on 2026-09-06).
The header directive grammar (// key: value, within the first 16 lines, with strict token matching) is:
// expect: compile-error E1002 [E1003 ...] Compile-time rejection test
// expect: runtime-error E6003 [...] Runtime failure test
// skip: <reason> Skip execution; count as skipped
// mode: embedded|standard|full Subprocess --runtime mode (consumed only by the run step)- No
expect:directive means a behavior test.expect:is the sole declaration of an expectation—on 2026-09-06, it was decided to abandon the[test:error]Boolean marker and Chinese预期:prose code extraction. A Boolean marker and an expectation line are two loosely coupled facts that will inevitably drift if maintained only through discipline. The strict English token grammar lets the runner parse mechanically (the kind and codes are all fixed tokens, and any extra token after a code causes a parse failure). A parse failure means no execution and an immediate FAIL, so there is no silent degradation path for a malformed directive (construction-time rejection) - Compile-error class: a single
checkstep—it must fail and its output must contain all[EXXXX]codes. If compilation succeeds, the result is FAIL (the expected error was not reported); if compilation is rejected but the code does not match, the result is also FAIL. Syntax errors (the E1xxx parse phase) and semantic errors (E2xxx and later) do not receive separate categories—the expected code itself pins down the phase - Runtime-error class: a two-step verdict—
checkmust succeed (no compile-time fault), whilerunmust fail and its output must contain all[EXXXX]codes. Failure at compile time results in FAIL. This is the critical verdict in the opposite direction from the compile-error class and prevents a "compilation unexpectedly passed, runtime happened to fail" case from escaping detection - This is structurally consistent with the industry: Rust compiletest
//~ ERROR, Go// ERROR "regexp", GCCdg-error, and Clangexpected-errorall declare expectations in fixture comments and use a harness for bidirectional comparison. They use line-level anchoring because multi-diagnostic compilers need to distinguish multiple expectations in one file. This compiler stops at the first error and produces one diagnostic per file, so file-level expectations are structurally consistent with the compiler's current reality; line-anchored forms may be added to the grammar after error recovery is implemented (Cranelift filetests' combination of file-header directives and function-level expectations uses the same hybrid model) - Known rendering debt: parse-time diagnostics currently use Debug formatting (
code: "E0012"rather than[E0012]), and the code scanner accepts both forms; strict formatting will be restored once diagnostic rendering is unified - This mechanism serves only this repository's corpus and is not part of the user-facing testing framework. The dual-runner decision convention was consolidated on 2026-09-03: yx_runner (
cargo test) andyaoxiang testshare thesrc/util/test_markers.rsheader-directive parser, and the directory convention in 06-compile-errors was abolished. The reporting layer provides category counts: the human-readable summary includes aCategories:line, the JSON summary includesby_kind(behavior / compile-error / runtime-error / invalid, with skipped counted separately), and each file includes akind
8.3 Runtime Hard Failures (Folded into Result Conversion)
There is no separate mechanism—operations that may fail return Result in accordance with the language direction, and tests consistently use §8.1. Process-level aborts, such as assertion violations or runtime argument mismatches, gradually converge to values as Result conversion advances, and the testing framework provides no dedicated semantics for them. Note that the "runtime-error class" marker decision in §8.2 is the runner's file-level verification channel for operations that cannot yet be converted to Result. This does not contradict the direction of this section: the latter is the end state, while the former is a migration-period channel.
9. Test System Layering: Language Corpus and Library Tests (Finalized 2026-09-03)
Tests are divided into two layers by the object under test, each with its own ownership and maintainers. The marker system (§8.2) and assertion library (§3) are shared by both layers.
Layer 1: Language-Availability Corpus (tests/yaoxiang/)
- The object under test is the language itself—the parser, type system, modules, concurrency, ownership, compile-time rejection, and runtime semantics. The directory is organized by language-specification chapter
- The standard library is used in the corpus only as an assertion tool (
std.assert/std.test) and is never tested—the behavior of a library's API is not part of language availability - Within the corpus, §8 divides tests into behavior tests, compile-time rejection tests, and runtime failure tests
Two forms of Layer 1: single-file corpus entries (one .yx file is an independently runnable program) and project fixtures (one directory per fixture, containing yaoxiang.toml, an entry-point main.yx, and module files, such as tests/yaoxiang-multifile/; see the multi-file corpus location for the project-level contract). A project's module files are not test targets—default discovery includes only its entry point (§5 item 6), while the project semantics of the complete fixture are evaluated by a dedicated runner (cargo test --test yx_multifile_runner).
Layer 2: Library Tests (Ship with the Library)
- The object under test is the library's public API contract, such as
list.pushbehavior orresult.codesemantics - Tests are written inside the library's own package: the std package is
src/std/, and its YaoXiang-level tests belong insrc/std/tests/(in the same location as the implementation; the directory coexists with Rust unit tests, and the file types do not overlap). The tests forstd.testitself also live there (using std.test to test std.test, closing the dogfooding loop) - Future user packages follow the same convention: tests live with the package and are discovered through the package's
[tool.test]configuration (previewing the test layout described in RFC-014's package management) - The library-test layer is not included in the default patterns (the default
tests/**/*.yxcovers only the language layer). It is discovered through an explicit path (yaoxiang test src/std/tests) or package configuration, and CI runs the layers separately
Migration note: Migrated on 2026-09-06—the 19 files originally under tests/yaoxiang/07-std/ were reviewed individually and determined to be library tests in their entirety (the objects under test were all std-module API contracts; features such as ? propagation, automatic borrowing, and generic instantiation served as carriers rather than objects under test). They were moved in their entirety to src/std/tests/, and the 07-std directory was removed. yx_runner switched to dual-root discovery (tests/yaoxiang/ + src/std/tests/), the default patterns exclude the library layer, and integration tests lock in this contract. The language corpus has since contained zero std-API tests.
Relationship to Existing Systems
| Item | Relationship |
|---|---|
Rust #[test] | Unchanged; internal compiler tests continue to use Rust |
Existing .yx integration tests (tests/yaoxiang/) | Discovered and executed by yaoxiang test |
std.assert.assert(cond) | Retained for runtime guards; std.test's value-semantics assertion family is based on std.result (§3, §7) |
| Module system (RFC-029) | Embedded source modules are integrated through Registry/orchestrator; CLI run connecting to the orchestrator is a prerequisite |
Corpus refactoring (io.println → assert.assert) | Fully consistent with the direction of yaoxiang test |
@ annotations | Not used; no @test is introduced |
Implementation Strategy
Phase 1: Core Functionality
Scope of changes:
src/util/diagnostic/mod.rs/src/main.rs— Delegate the CLIRunsource branch torun_project(prerequisite for multi-file execution)src/main.rs— Add theTestsubcommandsrc/std/test.yx— Add the pure YaoXiang modulebuild.rs— Embedstd/*.yxin the binary- orchestrator / Registry — Support loading
.yxmodules from embedded sources through virtual paths - RFC-015 configuration parsing — The
[tool.test]section - Subprocess execution and reporting
Deliverables:
yaoxiang testis fundamentally usablestd.testprovides four assertion functions- Default discovery of
tests/**/*.yx - Serial execution and the default output format
Phase 2: Refinement
- The
--filter/--fail-fast/--verboseoptions --jsonoutput (CI integration)- The
--listoption - The
--no-progressoption
Phase 3: Advanced Features (Delivered 2026-09-07)
--parallelparallel execution (worker pool with one independent subprocess per file; the[tool.test].parallelconfiguration key has the same effect)- The
[tool.test].excludeconfiguration (prefix-based exclusion, also applied by--list) assert_approx_eq(Float assertion with an expliciteps, §3)
Risks and Mitigations
| Risk | Probability | Mitigation |
|---|---|---|
f"..." interpolation fails on Any | None | Verified on 2026-08-02 (both Int and String work correctly) |
yaoxiang.toml configuration parsing is not currently supported by the CLI | Low | A simple extension that does not affect core functionality |
| Connecting CLI run to the orchestrator introduces a behavioral regression | Low | Single-file paths without imports are equivalent; integration tests cover the orchestrator |
Embedding .yx source files in the binary increases binary size | Low | The .yx source files are extremely small and the increase is negligible |
| Test-loop duration grows as the corpus expands | High | The main cost is compiling every file in full (185 files measured at 11.3s), not subprocess startup; --parallel only mitigates the process side, and compile costs require test-loop cache slicing |
Open Questions
- [x] Can the
use std.assertreference instd/test.yxbe resolved correctly? — Resolved on 2026-08-02. After the module system (RFC-029) was implemented, native and source modules coexist in the Registry, the resolver handles both uniformly, and cross-kind dependencies work naturally - [x] Does the generic
to_stringused byf"..."in test output introduce new type constraints? — Resolved on 2026-08-02. Empirical testing showed that==/!=and f-string interpolation both work on parameters with no specific type annotation (Any) (verified with Int and String), introducing no new constraints - [x] Is the
?generic parameter feasible? — Resolved on 2026-08-02: the?type syntax does not currently exist (and is silently swallowed, with a separate issue tracking it). Phase 1 assertion functions use parameters with no specific type annotation and do not depend on the generics system
Design Decision Log
| Decision | Determination | Date | Rationale |
|---|---|---|---|
| Test marking method | Do not use an @test annotation; test files are ordinary .yx files | 2026-07-26 | Zero compiler changes; subprocesses provide isolation |
| Assertion approach | The std.test module consists purely of YaoXiang functions | 2026-07-26 | Dogfooding; no native code |
| Test execution model | Subprocess yaoxiang run <file> + exit code | 2026-07-26 | Process-level isolation, zero compiler changes |
| Standard library loading | Currently embedded in the binary; filesystem-based in the future | 2026-07-26 | Version binding; works in single-file mode |
| Assertion parameter type | Parameters with no specific type annotation (Any), independent of the generics system | 2026-08-02 | ? type syntax does not exist; Any was empirically shown to be comparable and interpolatable |
| Multi-file execution | CLI run delegates to run_project (orchestrator) as a prerequisite | 2026-08-02 | The subprocess model inherits CLI capabilities; on-demand discovery along use degrades to a pure performance optimization |
| Report source location | Runtime errors include it by default | 2026-09-07 | debug_map is generated by default and stack traces output file:line:col; frame ownership when passing through an embedded module such as std.test is not guaranteed and belongs to RFC-034 |
| Negative test layering | General-purpose value-level negatives / structured runner markers for compile failures (internal only) / hard failures folded into Result conversion | 2026-09-02 | The value model was finalized; this replaces the implicit [test:error] convention |
| Multiple tests within a file | Standard value-semantics model: test functions return Result, and the suite collects per-test verdicts | 2026-09-02 | No catch and no direct function invocation (direct invocation is limited to internal scenarios) |
| Error code | Error gains a machine-readable code field | 2026-09-02 | Supports error-code assertions; compile-time codes are compared by the runner |
| Assertion library shape | A seven-function value-semantics family with a Result(Void, String) contract; the transitional abort version was removed | 2026-09-03 | Void is the specified unit type (() is an empty Tuple and is not mixed with it); nested Any is rigid, and parameters without annotations fail native generic checks—parameters must be explicitly annotated (as demonstrated by the R1 probe) |
| Test system layering | Language corpus (tests/yaoxiang/) and library tests (ship with the library, std → src/std/tests/) form two layers; std is only an assertion tool in the corpus | 2026-09-03 | The object under test determines ownership and maintainers; library-test package layout previews RFC-014 |
| Discovery semantics: project directories ≠ loose test sets | When recursive discovery encounters a directory containing yaoxiang.toml, it includes only that project's conventional entry point, main.yx; the other .yx files in the same directory are project modules and are not independent test targets. A .yx file belonging to no project directory is treated as a test target (the remaining loose end is covered in §5 item 7) | 2026-10-16 | Determining "this is a test" originally relied solely on extension matching (collect_yx_recursive in util/test_runner.rs), which does not hold: placing non-test .yx files (fixtures or library modules) under tests/ is a valid layout. The same rule has already forced two escapes (the library-test layer was moved out of tests/, and the project-fixture layer was bypassed through explicit CI paths). Per D3, the rule should be changed rather than bypassed again. Industry practice points in the same direction (Cargo treats only top-level .rs files in tests/ as integration-test targets, while pytest collects by the test_*.py naming convention). Red then green: yaoxiang test with no path arguments changed from 321 passed / 10 failed → 321 passed / 0 failed, while tests/yaoxiang (the CI criterion) remained at 311/0 |
| Negative-marker dispatch | Dispatch by expected category: the compile-error class requires check to fail, while the runtime-error class requires check to pass and run to fail; the report provides category counts | 2026-09-03 (implemented 2026-09-06) | Mixing categories would allow a "compilation unexpectedly passed, runtime happened to fail" case to escape detection; the expected code pins down the phase, and syntax errors do not receive a separate category |
| Header directive grammar | Expectations are declared through English structured directives (// expect: / // skip: / // mode:, with a strict token grammar and immediate FAIL on parse failure); the [test:error] Boolean marker and Chinese 预期: prose code extraction are abandoned | 2026-09-06 | Expectations are properties of fixture content, and in-fixture declarations are structurally consistent with the industry (compiletest / Go / GCC / Clang). A central list inevitably rots; coupling a Boolean marker and an expectation line through discipline is a defect surface. The structured grammar lets the runner decide mechanically without human intervention |
| Parallel execution model | --parallel starts one worker per core (each file still runs in an independent subprocess); skip/invalid entries are handled first in discovery order, execution results are streamed in completion order, and JSON is sorted by path; --fail-fast stops scheduling (in-flight files finish and are counted); the CWD remains shared and the isolation boundary is not expanded | 2026-09-07 | Under the subprocess model, parallel execution means OS thread scheduling with spawn and requires no YaoXiang-level concurrency. The main cost is compiling every file in full (see the risk table); parallelism only mitigates the process side—test-loop cache slicing is the primary mitigation |
References
- RFC-014: Package Management System Design — Standard-library directory structure
- RFC-015: Configuration System — The
[tool.test]configuration section - RFC-030: assert Assertion Mechanism — Lower-level dependency
- Rust
#[test]mechanism — Reference design
