← Back to context

Comment by shagie

25 days ago

In functions that you write, that might be possible.

How would you assert that a given std::vector only was filtered by std::ranges::copy_if once? And how would you test that the code that was in the predicate for it wasn't duplicated?

How would you write a failing test for this function keeping the constraint that you are working with std::vector?

    std::vector<int> doThing(const std::vector<int>& nums) {
        std::vector<int> tmp1;
        std::vector<int> tmp2;
        std::ranges::copy_if(data,
                             std::back_inserter(tmp1),
                             [](int n) { return n % 2 == 0; }
        );
        std::ranges::copy_if(tmp1,
                             std::back_inserter(tmp2),
                             [](int n) { return n % 2 == 0; }
        );
        return tmp2;
    }

I know how I would do it in python. This is built into the stdlibs testing library, with mocks.

Maybe dependency injection and function pointers for the copy if function. Then you can check the call counts in your tests. But idk the cpp eco system and what's available there to do it.

  • The python code would be

        def some_call():
            return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        
        def print_evens(nums):
            for n in filter(lambda n: n % 2 == 0, nums):
                print(n)
        
        def func():
            filtered = list(filter(lambda n: n % 2 == 0, some_call()))
            print_evens(filtered)
        
        if __name__ == "__main__":
            func()
    

    How would you write a failing test that prevents the list from some_call() from having the same filter applied to it twice?