Native Testing Framework
Flame features an integrated, zero-cost testing runner driven by PascalCase annotations. Run tests with flame test.
Built-in Testing Annotations
Section titled “Built-in Testing Annotations”| Annotation | Description |
|---|---|
@Test |
Marks a function as an executable test case. |
@Setup |
Runs before each individual test in the file. |
@Cleanup |
Runs after each individual test in the file. |
@BeforeAll |
Runs once before the entire test suite starts. |
@AfterAll |
Runs once after all tests in the file complete. |
@Parameterized |
Executes the test across a matrix of input arguments. |
Example Test Suite
Section titled “Example Test Suite”@Setupfn init_test_env() { print("Setting up test sandbox...")}
@Test(timeout: 3000)fn test_math_operations() { let result = 10 * 5 assertEq(result, 50, "Multiplication should equal 50")}
@Parameterized([ [2, 3, 5], [10, 15, 25], [-5, 5, 0]])fn test_addition(a: Int, b: Int, expected: Int) { assertEq(a + b, expected)}
@Cleanupfn tear_down() { print("Test finished.")}Built-in Test Assertions & Mock Helpers
Section titled “Built-in Test Assertions & Mock Helpers”Flame includes built-in test assertion primitives. All assertion functions accept an optional diagnostic message parameter declared using Flame’s Optional Type syntax (String? = nil):
assert(condition: Bool, message: String? = nil)assertTrue(condition: Bool, message: String? = nil)assertFalse(condition: Bool, message: String? = nil)assertEq<T>(actual: T, expected: T, message: String? = nil)assertNe<T>(actual: T, unexpected: T, message: String? = nil)mockData(schema: String) -> FormulamockApi(url: String, body: String = "{\"status\": \"ok\"}", status: Int = 200) -> FormulamockFunction<T>(name: String, return_value: T)
Optional Assertion Messages
Section titled “Optional Assertion Messages”Because the message parameter is declared as an Optional Type (message: String? = nil), callers can omit the message for clean, concise assertions or supply a custom diagnostic string for detailed failure diagnostics:
@Testfn test_assertions() { let count = 100
// 1. Omitted message parameter assertEq(count, 100)
// 2. Custom descriptive message assertEq(count, 100, "Counter should initialize to 100")
// 3. Explicit nil message parameter assertEq(count, 100, nil)
// Boolean assertions assertTrue(count > 0, "Counter must be positive") assertFalse(count < 0)}@Testfn test_mocking() { let user = mockData("user") assertEq(user.id, 1001, "Mock user ID should be generated")
let api_res = mockApi("/v1/health") assertTrue(api_res.ok)}Negative Testing with @ExpectPanic
Section titled “Negative Testing with @ExpectPanic”When validating invariant enforcement, error-handling paths, or borrow checker rules, you write negative test cases that verify a routine properly panics or rejects invalid operations.
Decorate the test function with both @Test and @ExpectPanic:
@Test@ExpectPanicfn test_use_after_move() { let a = "heavy_payload" let b = a // Ownership moves to b
// Attempting to read a after move triggers a memory safety error println(a)}
@Test@ExpectPanicfn test_conflicting_mutable_borrows() { let mut x = 42 let r1 = &mut x let r2 = &mut x // Second mutable borrow triggers borrow checker error
r1 += 1 r2 += 1}Testing Libraries and Packages
Section titled “Testing Libraries and Packages”Flame makes testing standalone libraries (--lib) as ergonomic as testing full executables.
1. Creating a Library Package
Section titled “1. Creating a Library Package”fmp new my_crypto --libcd my_cryptoThe resulting library layout separates exported API definitions from unit and integration tests:
my_crypto/├── flame.toml # Package manifest declaring [package] name, version, edition├── src/│ └── lib.fm # Main library entry point exporting package public API└── tests/ └── test_crypto.fm # Unit and integration test suites2. Exporting Library Functions (src/lib.fm)
Section titled “2. Exporting Library Functions (src/lib.fm)”package my_crypto
export fn hash_bytes(input: String) -> String { // Return hash digest return "hash_" + input}
export struct KeyPair { public_key: String, private_key: String,}3. Writing Library Tests (tests/test_crypto.fm)
Section titled “3. Writing Library Tests (tests/test_crypto.fm)”In test files under tests/, simply import your package by name:
import my_crypto
@Testfn test_hash_computation() { let digest = hash_bytes("payload") assertEq(digest, "hash_payload", "Hash digest should match expected prefix")}
@Testfn test_keypair_creation() { let kp = KeyPair { public_key: "pub_123", private_key: "priv_456", } assertEq(kp.public_key, "pub_123") assertNe(kp.public_key, kp.private_key, "Keys must never collide")}4. Running Library Tests
Section titled “4. Running Library Tests”# Execute all tests inside the tests/ directoryfmp test
# Run a specific test suite directlyflame test tests/test_crypto.fmExplicit Test Failures & Invariants (panic)
Section titled “Explicit Test Failures & Invariants (panic)”When writing complex integration tests for robotics control loops or validating edge-case state transitions, standard equality assertions (assertEq) may not express custom branching failure logic clearly.
You can invoke the built-in panic(message: String) function directly within any @Test case to explicitly fail the test with an exact diagnostic message and line trace:
@Testfn test_logical_operators_and_safety_interlocks() { let isOnline = true let isFaulted = false
// Explicit invariant validation using panic if isOnline and isFaulted { panic("Expected safety interlock: system cannot be online while in a faulted state") }
if not (isOnline or isFaulted) { panic("Expected system to be responsive (online or faulted)") }
let motorSpeed: Int? = 1200 if motorSpeed == nil { panic("Motor telemetry dropped unexpectedly during active test cycle") }}Benchmarking Framework (@Benchmark)
Section titled “Benchmarking Framework (@Benchmark)”Flame provides a built-in, first-class performance benchmarking framework. Simply decorate functions with @Benchmark and execute them via flame bench.
@Benchmark(warmup: 10, iterations: 100, group: "crypto", name: "SHA-256 Hashing")fn benchmark_sha256() { let hash = crypto.sha256("benchmark-payload")}Configuration Parameters
Section titled “Configuration Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
warmup |
Int |
10 |
Unmeasured iterations to warm CPU caches and JIT paths. |
iterations |
Int |
100 |
Timed iterations measured for statistical profiling. |
group |
String |
"" |
Tag for generating comparative performance ranking tables. |
name |
String |
Function Name | Display name in benchmark reports. |
Running Benchmarks
Section titled “Running Benchmarks”# Run all benchmarks across tests/, benchmarks/, and src/flame bench
# Run a specific benchmark fileflame bench tests/crypto_bench.fmStatistical Metrics & Comparative Reports
Section titled “Statistical Metrics & Comparative Reports”Each benchmark generates:
- Total Time & Average Time / Op (with microsecond / nanosecond precision)
- Min & Max Latency
- Percentiles:
p50(median),p95,p99 - Throughput: Calculated
ops/sec - Memory Allocation: Total bytes and bytes per op (using OS page RSS tracking)
- Group Comparison Tables: Automatically ranks benchmarks sharing a
groupand computes the relative percentage improvement!
