catchorg / catchorg/Catch2

Assert that the code does not compile

Open
#2,610 2 comments 4 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
21.5k
Forks
3.5k
Avg merge
3d 16h
Merged PRs (30d)
2

Description

**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](https://en.cppreference.com/w/cpp/language/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:

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

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

Contributor guide

Open the contributing guide

Research direction

Start by locating the existing STATIC_REQUIRE_FALSE assertion and reviewing how compile-time assertions are tested. Use the proposed C++20 requires expression and TEST_CASE example as the acceptance target; done means invalid expressions can be checked through a dedicated assertion without a hard compilation failure.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
testing-qa
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.