catchorg / Catch2

A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch)
https://discord.gg/4CWS9zD
Boost Software License 1.0
18.6k stars 3.05k forks source link

Assert that the code does not compile #2610

Open alabuzhev opened 1 year ago

alabuzhev commented 1 year ago

Description Testing unhappy paths is as important as testing happy paths, so Catch2 has quite a few useful assertions like REQUIRE_THROWS, REQUIRE_THROWS_AS etc. However, those are run time, and these days a lot of things is happening at compile time. Especially with introduction of constraints and concepts in C++20.

It is logical to check that your custom constraint works as expected, i.e. not only accepts valid types, but rejects invalid ones. Validating the happy path is trivial ("it compiles"), the unhappy one - not so much (for obvious reasons). Luckily, C++20 introduced the requires expression, that allows to turn a hard compilation error into a constexpr false.

It would be nice to have an out-of-the-box assertion for this.

Additional context A new assertion could piggyback on the existing STATIC_REQUIRE_FALSE and should be trivial to implement:

#define STATIC_REQUIRE_ERROR(Type, ...) \
    { \
        constexpr auto Result = []<typename TestType>() \
        { \
            return requires { __VA_ARGS__; }; \
        }.template operator()<Type>(); \
        STATIC_REQUIRE_FALSE(Result); \
    }
TEST_CASE("test")
{
    // std::common_type_t<int, void> should not compile
    STATIC_REQUIRE_ERROR(int, typename std::common_type_t<TestType, void>);
}

Compiler Explorer demo: https://godbolt.org/z/hc9WoMrKf

p4vook commented 9 months ago

Maybe create a PR with this macro?

UPD: interface could probably be better, though

ChrisThrasher commented 9 months ago

This does look like an interesting feature but remember that Catch2 is a C++14 library (with optional C++17 features) so anything requiring C++20 is out of scope until the next major version which as of yet isn't in the works.