Skip to content

Enumerator generator #3000

@leonardopsantos

Description

@leonardopsantos

I'm using fff to mock a call and I have a std::vector of expected arguments for the mocked function. The way fff works, I need a generator that works like the Python enumerate statement: on each iteration it returns the iteration number and an element of my vector, so my test goes something like this:

REQUIRE(my_function_fake.arg0_history[i] == val_a);
REQUIRE(my_function_fake.arg1_history[i] == val_b);

I need both the vector element and the index. I'm trying to understand how to best go about it. My first try was to simply iterate over the vector and use CAPTURE:

uint32_t factorial(uint32_t number)
{
    return number <= 1 ? number : factorial(number - 1) * number;
}

TEST_CASE("Factorials are computed", "[factorial]")
{
    std::vector<std::tuple<uint32_t, uint32_t>> expected_results = {
        {1, 1},
        {2, 2},
        {3, 6},
        {10, 3'628'800+1},  // Bad value
    };

    for( int i = -1; const auto& v : expected_results ) {
        ++i;
        auto& [input, expected] = v;
        CAPTURE(i, input, expected);
        REQUIRE(factorial(input) == expected);
    }

This works great, I get a nice error message with the particular values that failed:

test.cc:50: FAILED:
  REQUIRE( factorial(input) == expected )
with expansion:
  3628800 (0x375f00) == 3628801 (0x375f01)
with messages:
  i := 3
  input := 10
  expected := 3628801 (0x375f01)

Using the range generator seems a bit overly complicated:

    size_t i = GENERATE_REF(Catch::Generators::range(static_cast<size_t>(0), expected_results.size()));
    auto [input, expected] = expected_results[i];
    CAPTURE(i, input, expected);
    REQUIRE(factorial(input) == expected);

Is there a way to use one of the GENERATE macros for this?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions