Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Write a Rust macro that implements "Table Driven Tests" syntax.

  1. User

    Write a Rust macro that implements "Table Driven Tests" syntax.

  2. GLM Assistant

    The user wants a Rust macro that implements "Table Driven Tests" syntax.

    1. Understanding the Goal: Table-driven tests are a common pattern in Go and are becoming increasingly popular in Rust (often using libraries like rstest or manual implementations). The idea is to define a structure (the "table") containing test cases (input and expected output) and then iterate over them in a single test function.

    2. Desired Syntax: What should the macro usage look like? It should be ergonomic. Something like:

    my_test! {
        name_of_test_group;
        // Case 1
        input1: 1, input2: 2 => expected: 3;
        // Case 2
        input1: 10, input2: 5 => expected: 5;
    }
    

    Or perhaps a more struct-like definition? Let's look at existing popular implementations (like the standard pattern or crates). Standard pattern:

    #[test]
    fn test_add() {
        let cases = vec![
            (1, 2, 3),
            (10, 5, 15),
        ];
        for (a, b, expected) in cases {
            assert_eq!(add(a, b), expected);
        }
    }
    

    The macro should probably generate the #[test] function and the iteration logic.

    Let's try a syntax that allows naming cases for better error reporting. This is crucial. If a test fails, you want to know which row failed.

    Drafting a Syntax Idea:

    table_test! {
        test_fn_name: test_addition;
        input: (a: i32, b: i32);
        expected: result: i32;
        cases: [
            "simple add": (1, 2) => 3,
            "negative add": (-1, -1) => -2,
        ]
    }
    

    This is a bit verbose.

    A simpler syntax often used in simple macro tutorials:

    test_table! {
        my_test_function {
            (1, 2) => 3;
            (5, 5) => 10;
        }
    }
    

    This lacks case names. Named cases are better.

    Let's try to design a macro that looks like this:

    test_cases! {
        fn test_add(a: i32, b: i32) -> i32 { a + b }
    
        "positive": (1, 2) => 3,
        "negative": (-1, -1) => -2,
    }
    

    Wait, usually the function under test is defined elsewhere.

    Better approach:

    make_tests! {
        fn test_add(a, b) { add(a, b) } // The body of the test loop
    
        case "simple": (1, 2) => 3
        case "complex": (10, 20) => 30
    }
    

    Let's aim for something that feels "Rust-like" and generates standard #[test]s or a single #[test] that iterates.

    Approach A: Generate one test function with a loop. Pros: Fast compilation. Cons: Harder to run a single specific case (though #[ignore] logic or filtering helps).

    Approach B: Generate a separate #[test] function for each row. Pros: cargo test case_name works out of the box. Cons: Can slow down compile times if there are thousands of tests.

    Approach B is usually preferred for "Syntax Sugar" macros unless the case count is huge. Let's go with Approach B because it integrates better with the standard test harness.

    3. Designing the Macro (Approach B)

    Input:

    1. The test function name prefix.
    2. The arguments pattern.
    3. The expected result.
    4. The list of cases.

    Let's look at a syntax used by some crates (conceptually):

    parameterized! {
        "simple": (1, 2) => 3,
        "complex": (10, 20) => 30,
    }
    

    But the macro needs to know what code to run.

    Let's try this structure:

    table_driven! {
        // Function name
        test_add;
    
        // Arguments definition
        args: (a: i32, b: i32);
    
        // Expected
        expected: i32;
    
        // The logic
        run: add(a, b);
    
        // Cases
        cases: {
            "case1": (1, 2) -> 3;
            "case2": (10, 20) -> 30;
        }
    }
    

    That's a lot of boilerplate.

    Let's try to infer things. How about:

    test_table! {
        test_add; // Function name
        add(a, b); // Expression to test (using variables defined below)
        (a: i32, b: i32) -> (expected: i32); // Signature
        [
            "pos": (1, 2) => (3);
            "neg": (-1, -2) => (-3);
        ]
    }
    

    Actually, let's look at the standard macro_rules! pattern for this. It's a bit tricky because of recursive parsing.

    Let's go for a syntax that generates one test function iterating over a vector of cases. It's easier to implement robustly in macro_rules! and often what people mean when they say "Table Driven" (Go style). It keeps the output clean.

    Revised Syntax Goal:

    table_test! {
        // Test function name
        test_addition;
    
        // The structure of a row
        struct { a: i32, b: i32, expected: i32 }
    
        // The test logic
        assert_eq!(add(row.a, row.b), row.expected);
    
        // The data
        [
            { a: 1, b: 2, expected: 3 },
            { a: -1, b: 1, expected: 0 },
        ]
    }
    

    This is verbose.

    Let's try the case => expected syntax. It's the most intuitive for math/logic functions.

    Macro Syntax:

    test! {
        name: test_my_func;
        call: my_func(input);
        cases: {
            "simple case": 1 => 2;
            "another case": 3 => 6;
        }
    }
    

    Let's try to implement a macro that allows this:

    test_table! {
        // Name of the generated test function
        test_adder;
    
        // The function call/expression to test
        // $actual should match $expected
        add($a, $b) => $expected;
    
        // The table of arguments and results
        [
            "basic": (1, 2) => 3;
            "negatives": (-1, -1) => -2;
        ]
    }
    

    This looks good. How do we implement this in macro_rules!?

    Step 1: Structure

    macro_rules! test_table {
        (
            $test_name:ident; // test_adder
            $func:ident ( $($arg:ident),* ) => $expected:ident; // add(a, b) => expected
            [
                $($case_name:literal : ( $($val:expr),* ) => $exp:expr );* $(;)?
            ]
        ) => {
            #[test]
            fn $test_name() {
                $(
                    // Generate code for each case?
                    // No, if we do a loop, we need a struct.
                    // If we generate separate functions, we do it here.
                )*
            }
        }
    }
    

    Decision Point: Loop vs Individual Functions. If I generate individual functions, I can run cargo test case_name. If I generate a loop, I can print "Case 'case_name' failed".

    Let's go with the Loop approach (Go style) because it's usually what people mean by "Table Driven Tests" in a single macro, and it avoids creating hundreds of functions which can bloat the test binary.

    Implementation Plan (Loop Approach):

    1. Define a struct TestCase.
    2. Create a Vec of TestCase.
    3. Iterate and assert.

    Refining the Syntax: To make it generic, the macro needs to know the variable names inside the test body.

    Let's try a syntax similar to rstest or simple lambda passing.

    table_test! {
        // 1. Test Name
        test_addition,
    
        // 2. The function to run (closure syntax helps binding)
        |a, b| add(a, b),
    
        // 3. The table (name, inputs, expected)
        [
            ("simple", 1, 2, 3),
            ("negative", -1, -1, -2),
        ]
    }
    

    This is hard to read without labels.

    Let's stick to a Key-Value syntax for the table rows.

    test_table! {
        // 1. Name of test
        test_add,
    
        // 2. Code to run
        // Need to capture inputs
        // Let's say we define a struct `Row` implicitly
        add(row.a, row.b) == row.expected;
    
        // 3. The rows
        [
            { name: "simple", a: 1, b: 2, expected: 3 },
            { name: "negative", a: -1, b: -1, expected: -2 },
        ]
    }
    

    This is verbose but very clear.

    Alternative: The "Simple" Approach (Tuple based)

    test_table! {
        fn test_add(a: i32, b: i32) {
            let result = add(a, b);
            assert_eq!(result, expected); // Where does expected come from?
        }
    
        cases: [
            "simple": (1, 2, 3),
            ...
        ]
    }
    

    This is tricky because expected needs to be unpacked from the tuple.

    Let's provide a solution that generates a loop and uses a struct for the row. This is robust.

    Proposed Macro Syntax:

    table_test! {
        // The name of the test function
        test_addition;
    
        // The arguments to be extracted from the table
        args: (a: i32, b: i32, expected: i32);
    
        // The body of the test
        // The macro provides 'args'
        assert_eq!(add(a, b), expected);
    
        // The table data
        table: {
            "positive": (1, 2, 3);
            "negative": (-1, -1, -2);
        }
    }
    

    Wait, if I define args: (a: i32, b: i32, expected: i32), I can just iterate over a tuple. Tuple matching (a, b, expected) inside the loop.

    Let's refine the exact implementation code.

    macro_rules! table_test {
        (
            $test_name:ident;
            ( $( $arg:ident : $arg_ty:ty ),* );
            $body:block;
            [ $( $case_name:literal : ( $( $val:expr ),* ) ),* $(,)? ]
        ) => {
            #[test]
            fn $test_name() {
                let cases = [
                    $(
                        ($case_name, ( $( $val ),* ))
                    ),*
                ];
    
                for (name, ( $( $arg ),* )) in cases {
                    // We need to handle the body logic here.
                    // If the body uses `assert!`, panics are swallowed?
                    // No, `#[test]` catches panics.
                    // But we want to know *which* case failed.
                    
                    // Using `std::panic::catch_unwind` is possible but complex for a simple macro example.
                    // Standard approach: just run the code.
                    // If it panics, the test stops.
                    // To make it robust:
                    if let Err(e) = std::panic::catch_unwind(|| { $body }) {
                         panic!("Test case '{}' failed: {:?}", name, e);
                    }
                    // Actually, simpler: Just run the code. If it panics, line numbers might be obscure.
                    // Better: Encapsulate in a helper closure?
                }
            }
        }
    }
    

    The issue with catch_unwind is that the closure must be UnwindSafe and RefUnwindSafe, which forces types to be simple or wrapped in AssertUnwindSafe. This makes the macro annoying to use.

    Better Approach for the Loop: Just print the name before running, or rely on standard panic messages. Or, use assert_eq! inside the loop which provides context.

    Let's go with the Multiple Test Functions approach. It's actually simpler to implement correctly in macro_rules! without fighting the borrow checker or unwind safety, and it's much better for the user (can run individual cases).

    Macro Design (Multi-function): Input:

    1. A base name for the test.
    2. The expression to test (optional, can just be a body).
    3. List of cases.
    test_table! {
        test_add;
        |a, b| add(a, b);
        [
            "simple" => (1, 2) == 3,
            "complex" => (10, 20) == 30
        ]
    }
    

    This implies (1, 2) are inputs, 3 is output. The macro calls the closure.

    Let's try a very explicit "Rusty" macro structure.

    make_tests!{
        // Name of the test group
        test_math_ops;
    
        // Function body (args are pattern matched)
        |a, b| {
            add(a, b)
        }
    
        // Cases: "name" => (inputs) -> expected
        "add positives": (1, 2) -> 3,
        "add negatives": (-1, -1) -> -2,
    }
    

    Implementation Details: Recursive macro rules to handle the comma-separated list of cases. For each case, generate #[test] fn test_math_ops_add_positives() { ... }.

    Let's write the macro:

    macro_rules! table_test {
        // Base case: empty list
        (@cases $test_name:ident, $body:expr, []) => {};
    
        // Recursive case: one case
        (@cases $test_name:ident, $body:expr, [ $name:ident : ( $($args:expr),* ) => $expected:expr $(, $($rest:tt)*)? ]) => {
            #[test]
            fn $name() {
                let result = $body($($args),*);
                assert_eq!(result, $expected);
            }
            table_test!(@cases $test_name, $body, [ $($($rest)*)? ]);
        };
    
        // Entry point
        (
            $test_name:ident;
            $closure:expr;
            [ $( $case_name:ident : ( $($args:expr),* ) => $expected:expr ),* $(,)? ]
        ) => {
            $(
                // This expansion logic is tricky if we want to loop *inside* macro rules
                // because standard repetition only works if we define the function N times.
            )*
        }
    }
    

    Wait, standard repetition $()* works fine for generating top-level items (functions).

    Revised Macro Structure (Generating multiple functions):

    macro_rules! table_driven {
        (
            // The base name (unused if we name every case, but maybe used as prefix?)
            // Let's say every case needs a unique identifier.
            
            // The function logic to test.
            // We need to know the inputs to pass them.
            // A closure is the easiest way: |a, b| my_func(a, b)
            logic: $logic:expr;
    
            // The test cases
            cases: {
                $( $name:ident : ( $($args:expr),* ) => $expected:expr );* $(;)?
            }
        ) => {
            $(
                #[test]
                fn $name() {
                    assert_eq!($logic($($args),*), $expected);
                }
            )*
        }
    }
    

    Usage:

    table_driven! {
        logic: |a, b| add(a, b);
        cases: {
            test_add_simple: (1, 2) => 3;
            test_add_neg: (-1, -1) => -2;
        }
    }
    

    Critique: Using ident for test names limits naming (no spaces, no strings). Using ident is better for creating valid function names. This approach is very clean.

    What if we want a single loop test (Go style)? Many Rust users prefer the single test with a loop because it doesn't pollute the namespace with dozens of functions and compiles faster.

    Let's provide the Loop Style implementation. It is often more practical for large datasets.

    Macro Syntax for Loop Style:

    test_table! {
        // Name of the test function
        test_addition;
        
        // The arguments pattern
        args: (a: i32, b: i32, expected: i32);
        
        // The assertions body
        // variables 'a', 'b', 'expected' are available
        assert_eq!(add(a, b), expected);
        
        // The table
        rows: [
            ("simple", 1, 2, 3),
            ("negative", -1, -1, -2),
        ]
    }
    

    Implementation of Loop Style:

    macro_rules! test_table {
        (
            $test_name:ident; 
            ( $( $arg:ident : $arg_ty:ty ),+ );
            $body:block;
            [ $( $case_name:literal : ( $( $val:expr ),+ ) ),+ $(,)? ]
        ) => {
            #[test]
            fn $test_name() {
                let cases = [ 
                    $(
                        ($case_name, ($( $val ),+))
                    ),+
                ];
    
                for (name, ($( $arg ),+)) in cases {
                    // We execute the body.
                    // We want nice error messages if it fails.
                    // Using assert! macros inside $body handles the logic,
                    // but we can't easily inject the 'name' into the assert message
                    // unless we wrap it.
                    
                    // Let's just allow the user to write the assert in the body.
                    // To provide context on failure, we can wrap in a helper?
                    // No, simple is best. 
                    // User can do: assert_eq!(..., "... failed on case {}", name);
                    $body
                }
            }
        }
    }
    

    There is a scoping issue. If $body uses assert_eq!, it works. If we want to inject name into the panic automatically, it's harder without a closure.

    Let's go with a design that matches the cargo test behavior more natively: Multiple Function Generation. It's "The Rust Way" (1 test = 1 function). It allows granular running (cargo test case_1).

    Let's polish the Multiple Function syntax.

    test_table! {
        // Macro attribute (optional): test function prefix
        fn test_add;
        
        // Function to call (expression)
        call: add(a, b); 
        
        // The inputs/expected structure
        // args: (a, b), expected: res
        
        // Cases
        "case1": (1, 2) => 3;
        "case2": (10, 20) => 30;
    }
    

    I will implement a macro that generates separate #[test] functions. This is generally preferred in the Rust ecosystem for discoverability.

    Implementation Steps:

    1. Define the macro structure.
    2. Capture the logic expression.
    3. Iterate over the cases.
    4. Generate a function for each case.

    Wait, one complexity: Passing arguments to the logic expression. If the logic is add(a, b), how does the macro know a and b correspond to the values in the tuple (1, 2)? By order.

    Code Structure:

    macro_rules! table_test {
        (
            // The name of the test group (will be prefix)
            name: $group_name:ident;
    
            // The function body/closure logic
            // Arguments are passed positionally
            func: $func_body:expr;
    
            // Cases: "name" => (inputs) -> expected
            cases: {
                $( $test_name:ident : ( $($args:expr),* ) => $expected:expr );* $(;)?
            }
        ) => {
            $(
                #[test]
                fn $test_name() {
                    // Call the logic
                    let result = $func_body( $($args),* );
                    assert_eq!(result, $expected);
                }
            )*
        }
    }
    

    Refining for flexibility: Often we want to test a function that returns Result or panics. For a basic "Table Driven" macro request, assert_eq on return values is the standard interpretation.

    Let's add a twist: allow the user to provide the assertion logic, not just ==. Or keep it simple: actual == expected.

    Let's stick to the simplest, most useful version: Argument Tuple -> Expected Output.

    But, users often want string descriptions. ident doesn't allow spaces. We can use concat_idents! but that's unstable/complex. Let's stick to valid Rust identifiers for the test names.

    What if the user wants the "Go style" loop? The Go style (iterate vector) is better if there are 100 cases. The Function style is better if there are 10. I will provide the Function Generation version as it's more "macro-like" and integrates with cargo test filters better.

    However, the prompt asks for "Table Driven Tests" syntax. The Go style is synonymous with "Table Driven". The function generation is synonymous with "Parameterized Tests". I will provide the Loop (Go Style) implementation because it keeps the source code DRY (Don't Repeat Yourself) regarding the assertion logic, and allows structs for cases.

    The Plan: I will write a macro that creates a single test function containing a loop over a vector of test cases. It will print the case name on failure.

    Syntax:

    test_table! {
        // Test function name
        test_addition;
        
        // Argument destructuring from the tuple
        (a, b, expected);
        
        // Body of the test
        assert_eq!(add(a, b), expected);
        
        // Table of tuples
        [
            ("case 1", 1, 2, 3),
            ("case 2", 10, 20, 30),
        ]
    }
    

    Wait, type safety? If I pass ("s", 1, 2), Rust will infer types. It's fine.

    Handling Failures in Loop Style: If assert_eq! panics, the test stops. To make it robust:

    for (name, args) in cases {
       if let Err(e) = std::panic::catch_unwind(|| {
           // run body
       }) {
           panic!("Case {} failed: {:?}", name, e);
       }
    }
    

    This requires UnwindSafe. I'll stick to standard execution. If a case fails, the whole test fails immediately (standard behavior). The user can inspect the specific failure via the panic message or debugger. I will include the case name in the panic message if possible, or just let the assert! message handle it.

    Actually, the best way to include the name is: assert!(condition, "Failed on case: {}", name); The macro can wrap the body to inject this, but that's invasive.

    Let's refine the macro to be generic over the input and output types using a standard struct.

    Final Design: A macro table_test! that takes:

    1. Function name.
    2. A block of code (the test logic).
    3. A list of cases in name: input => expected format.

    Actually, name: input => expected is hard because input might be multiple args. Let's do: name: (inputs) => expected.

    And since generating functions is so much cleaner for CI (failures are isolated in some frameworks, easier to run specific ones), I'll actually provide the Function Generation version but with a helper syntax that allows string names, converting them to idents (or just requiring idents).

    Let's compromise: I will provide the Loop version. It is the canonical "Table Driven" implementation (creating a table struct/vector). It works for any number of cases and doesn't explode the binary size.

    Syntax:

    table_test! {
        fn test_addition; // Function name
        struct Args { a: i32, b: i32, expected: i32 }; // Struct definition
        run |args| { assert_eq!(add(args.a, args.b), args.expected); }; // Closure
        
        vec![
            Args { a: 1, b: 2, expected: 3 },
            Args { a: -1, b: -1, expected: -2 },
        ]
    }
    

    This is too verbose.

    Simplest Usable Syntax:

    test_table! {
        test_addition; // Name
        
        // Arguments available in scope: a, b, expected
        assert_eq!(add(a, b), expected);
        
        // Cases: identifier, a, b, expected
        [
            "simple": 1, 2, 3;
            "negatives": -1, -1, -2;
        ]
    }
    

    This requires the macro to know variable names a, b, expected.

    Let's write the macro_rules! for this.

    macro_rules! table_test {
        (
            $test_name:ident;
            $( $arg:ident ),* ; // Argument names for the pattern
            $body:block;
            [ $( $case_name:literal : $( $val:expr ),* ; )* ]
        ) => {
            #[test]
            fn $test_name() {
                let cases = [
                    $(
                        ($case_name, ($( $val ),*))
                    ),*
                ];
    
                for (name, ($( $arg ),*)) in cases {
                    println!("Running case: {}", name); // Helpful for logging
                    $body
                }
            }
        }
    }
    

    There is a small issue with trailing commas/semicolons in the syntax. I will make it robust.

    Alternative: The rstest crate is the industry standard for this. But the user asks to write a macro. I should provide a self-contained example.

    The Implementation: I will implement a macro that generates separate test functions. Why? Because it avoids the UnwindSafe / panic handling mess of the loop version and allows cargo test substring to work perfectly.

    The "Multiple Functions" Design: It mimics the #[test] attribute but adds parameters.

    parameterized_test! {
        // Macro name
        test_addition;
    
        // Parameters
        (a: i32, b: i32, expected: i32);
    
        // Body
        assert_eq!(add(a, b), expected);
    
        // Cases
        [
            "simple": (1, 2, 3);
            "neg": (-1, -1, -2);
        ]
    }
    

    Generates: fn test_addition_simple() { ... } fn test_addition_neg() { ... }

    The challenge: converting string literals "simple" to identifiers test_addition_simple. This requires paste crate logic usually, or concat_idents (which is unstable/limited). Or, just force the user to provide identifiers (idempotent).

    If I force identifiers:

    cases: [
        simple: (1, 2, 3);
        neg: (-1, -1, -2);
    ]
    

    Generates fn test_addition_simple(). This is robust and uses stable Rust.

    Final Choice: I will implement the Loop version (Go style). It is the most distinct "Table Driven" syntax compared to standard unit tests. The "Parameterized" approach (generating functions) is better described as "Parameterized Tests", while "Table Driven" implies a table structure.

    Refining the Loop Version Code: To handle the error reporting nicely (so you know which case failed), I will wrap the body execution. However, wrapping requires AssertUnwindSafe. I'll include that in the expansion so the user doesn't have to.

    macro_rules! table_test {
        (
            // Name of the test function
            name: $name:ident;
            
            // Arguments pattern (tuple)
            args: ( $( $arg:ident : $ty:ty ),* );
            
            // The test body logic
            // Users use the variable names defined above
            body: $body:block;
            
            // The table of cases
            cases: [
                $( $case_name:literal : ( $( $val:expr ),* ) ),* $(,)?
            ]
        ) => {
            #[test]
            fn $name() {
                // Define the cases vector
                let cases = vec![
                    $(
                        ($case_name, ($( $val ),*))
                    ),*
                ];
    
                for (case_name, ($( $arg ),*)) in cases {
                    // Wrap in a closure to handle unwinding and provide better error context
                    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        $body
                    }));
                    
                    if let Err(e) = result {
                        panic!("Test case '{}' failed with panic: {:?}", case_name, e);
                    }
                }
            }
        }
    }
    

    Wait, if I use catch_unwind, println! inside the test won't show up unless it passes or I capture it. This complicates things. Standard Rust tests capture stdout anyway. Let's keep it simple. No catch_unwind. Just a standard loop. However, standard loops stop at the first failure. That's usually desired.

    Let's verify the tuple destructuring syntax in macros. for (case_name, (a, b)) in cases works if cases is Vec<(&str, (i32, i32))>.

    Final Implementation Plan:

    1. Define macro_rules! table_test.
    2. Accept:
      • name (ident)
      • args (list of ident : ty)
      • body (block)
      • cases (list of literal : ( expr* ))
    3. Generate a #[test] function.
    4. Inside, create a vector of tuples (name, (args...)).
    5. Iterate and execute body.

    Example Usage:

    table_test! {
        name: test_add;
        args: (a: i32, b: i32, expected: i32);
        body: { assert_eq!(add(a, b), expected); }
        cases: [
            "positive": (1, 2, 3),
            "negative": (-1, -1, -2),
        ]
    }
    

    I'll present this with a clear explanation. I will also add a version that doesn't enforce types on the args definition to make it less verbose, relying on type inference.

    Simpler Syntax (Type Inference):

    table_test! {
        test_add;
        (a, b, expected); // No types
        assert_eq!(add(a, b), expected);
        [
            "simple": (1, 2, 3);
            "neg": (-1, -1, -2);
        ]
    }
    

    This is much nicer. The macro expansion just needs to make sure the variable names match.

    The Solution: I will provide the macro definition and an example of how to use it.

    macro_rules! table_test {
        (
            $test_name:ident;
            ( $( $arg:ident ),* );
            $body:block;
            [ $( $case_name:literal : ( $( $val:expr ),* ) ),* $(,)? ]
        ) => {
            #[test]
            fn $test_name() {
                let cases = [ 
                    $(
                        ($case_name, ($( $val ),*))
                    ),*
                ];
    
                for (name, ($( $arg ),*)) in cases {
                     // Optional: Print case name for verbose logs?
                     // eprintln!("Running case: {}", name); 
                     
                     // We execute the body.
                     // If it panics, the test fails.
                     // To provide context, we can wrap the panic, 
                     // but simple is better for a demo.
                     $body
                }
            }
        }
    }
    

    There is a conflict with the comma in the array syntax. [ ("a": 1), ("b": 2) ] vs [ "a": (1); "b": (2) ]. Standard arrays use commas. I will use commas for the cases list, and the values are inside parens.

    Structure: "case_name": (val1, val2, val3)

    One detail: Rust arrays [T; N] require all elements to have the same type. Since vals might be different types per row (if not careful), but usually in table tests the types match row to row. The tuple types must match.

    I will refine the macro_rules! to handle the comma separation correctly.

    One nice addition: concat_idents is unstable. If the user wants to run a single case, they can't with the loop approach. I'll mention this limitation or suggest the catch_unwind approach if they want all cases to run even if one fails. But strict "Table Driven" usually implies "Run until failure".

    I will stick to the clean, concise syntax.

    One specific syntax error in my thought process: [ $( $case_name:literal : ( $( $val:expr ),* ) ),* ] If I have ("case1", (1, 2)), ("case2", (3, 4)), I need to ensure the inner tuple matches the outer tuple structure. Yes, (1, 2) is an expression.

    Let's write the final code. Here is a robust implementation of a Table Driven Test macro in Rust.

    This macro simplifies the pattern of defining a list of input cases and expected outputs, iterating over them, and asserting the logic holds for all of them.

    The Macro

    #[macro_export]
    macro_rules! table_test {
        (
            // 1. The name of the test function to generate
            name: $test_name:ident;
    
            // 2. The argument pattern: (input1, input2, ..., expected)
            // We use 'tt' (token tree) to allow flexibility in types
            args: ($($arg_names:ident),+);
    
            // 3. The block of code to execute for each row
            body: $test_body:block;
    
            // 4. The table of cases: "case name" => (inputs..., expected)
            cases: [
                $( $case_name:literal : ( $($values:expr),+ ) ),* $(,)?
            ]
        ) => {
            #[test]
            fn $test_name() {
                // Define a struct to hold each row of data
                struct Case<$($arg_names),+> {
                    name: &'static str,
                    $($arg_names: $arg_names),+
                }
    
                // Create the vector of cases
                let cases = [
                    $(
                        Case {
                            name: $case_name,
                            $($arg_names: $values),+
                        }
                    ),*
                ];
    
                // Iterate and run
                for case in cases {
                    // Destructure args for easier usage in body
                    let ($($arg_names),+) = (case.$($arg_names),+);
                    
                    // We use a helper closure to scope the test body
                    // This allows us to handle panics gracefully if desired, 
                    // or simply keep the namespace clean.
                    let run_test = || {
                        $test_body
                    };
    
                    // Run the test
                    run_test();
                }
            }
        };
    }
    

    How to use it

    Here is an example testing a simple add function and a subtract function. Note how the args defined in the macro map to the variables used in the body.

    fn add(a: i32, b: i32) -> i32 {
        a + b
    }
    
    fn subtract(a: i32, b: i32) -> i32 {
        a - b
    }
    
    fn main() {
        // This is just to allow the example to run in a single file.
        // In a real project, you would place the tests in a #[cfg(test)] module.
    }
    
    // Unit tests module
    #[cfg(test)]
    mod tests {
        // Necessary if the macro is in another crate/module
        // use crate::table_test; 
    
        use super::*;
    
        #[test]
        fn test_add_manually() {
            assert_eq!(add(2, 2), 4);
        }
    
        // --- USAGE OF THE MACRO ---
    
        table_test! {
            name: test_addition;              // The test function name
    
            // Define the column names for the table.
            // The last one is conventionally the expected value.
            args: (a, b, expected);           
    
            // The logic to test. You must use the names defined in 'args'.
            body: {
                assert_eq!(add(a, b), expected);
            }
    
            // The data table
            cases: [
                "positive numbers": (1, 2, 3),
                "negative numbers": (-1, -2, -3),
                "zero":             (0, 0, 0),
            ]
        }
    
        table_test! {
            name: test_subtraction;
    
            args: (a, b, expected);
    
            body: {
                assert_eq!(subtract(a, b), expected);
            }
    
            cases: [
                "basic sub": (10, 5, 5),
                "underflow": (5, 10, -5),
            ]
        }
    }
    

    Why this design?

    1. Readability: The cases block looks exactly like a data structure, making it easy to add new test scenarios without copying assert! boilerplate.
    2. Type Safety: By mapping args to specific identifiers (a, b, expected), the compiler will throw an error if you provide the wrong types in the cases array or if the body uses a variable name that doesn't exist in args.
    3. Flexibility: The body block allows for complex logic (setup, multiple assertions, etc.) rather than just a simple 1-to-1 function call.

    Advanced: Handling Panics

    The simple version above stops at the first failure. If you want to emulate tools like rstest or Go's t.Run, where failures are reported but the loop continues, you would typically need to catch panics.

    Here is a slightly modified body execution block you can swap in to make it continue running even if an assertion fails (printing the error instead of halting):

    // Replace the 'run_test' logic in the macro above with this:
    let result = std::panic::catch_unwind(|| {
        $test_body
    });
    
    if result.is_err() {
        eprintln!("FAILED CASE: '{}' panicked", case.name);
        // Optional: resume_unwind to fail the whole test immediately, 
        // or accumulate errors to fail at the end.
    }