Skip to content

Native Testing Framework

Flame features an integrated, zero-cost testing runner driven by PascalCase annotations. Run tests with flame test.


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.

@Setup
fn 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)
}
@Cleanup
fn tear_down() {
print("Test finished.")
}

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) -> Formula
  • mockApi(url: String, body: String = "{\"status\": \"ok\"}", status: Int = 200) -> Formula
  • mockFunction<T>(name: String, return_value: T)

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:

@Test
fn 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)
}
@Test
fn 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)
}

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
@ExpectPanic
fn 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
@ExpectPanic
fn 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
}

Flame makes testing standalone libraries (--lib) as ergonomic as testing full executables.

Terminal window
fmp new my_crypto --lib
cd my_crypto

The 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 suites

2. 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
@Test
fn test_hash_computation() {
let digest = hash_bytes("payload")
assertEq(digest, "hash_payload", "Hash digest should match expected prefix")
}
@Test
fn 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")
}
Terminal window
# Execute all tests inside the tests/ directory
fmp test
# Run a specific test suite directly
flame test tests/test_crypto.fm

Explicit 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:

@Test
fn 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")
}
}

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")
}
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.
Terminal window
# Run all benchmarks across tests/, benchmarks/, and src/
flame bench
# Run a specific benchmark file
flame bench tests/crypto_bench.fm

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 group and computes the relative percentage improvement!