There must be module with test assertions in Phobos

Quirin Schroll qs.il.paperinik at gmail.com
Tue Apr 4 12:11:28 UTC 2023


On Thursday, 30 March 2023 at 17:01:26 UTC, Dmytro Katyukha wrote:
> I think, it could be enough to have following asserts in 
> stadard library:
> - `assertEqual`
> - `assertNotEqual`
> - `assertTrue`
> - `assertFalse`
> - `assertIn`
> - `assertNotIn`
> - `assertThrows`
> - `assertGreater`
> - `assertGreaterEqual`
> - `assertLessEqual`

I’d say most are superfluous:
- `assertEqual(a, b)` why not use `assert(a == b)`?
- `assertNotEqual(a, b)` why not use `assert(a != b)`?
- `assertTrue(cond)` why not use `assert(cond)`?
- `assertFalse(cond)` why not use `assert(!cond)`?
- `assertGreater` why not use `assert(a > b)`?
- `assertGreaterEqual` why not use `assert(a >= b)`?
- `assertLessEqual` why not use `assert(a <= b)`?

These have non-trivial, but straightforward lowerings:
- `assertIn` why not use `canFind` (or `any`) in 
`std.algorithm.searching`?
- `assertNotIn` why not use `!canFind` (or `!any`)?

This one is the only one that has value for DRY:
- `assertThrows`

Instead of
```d
assertThrows!Exception(expression);
```
one could write
```d
try { expression(); assert(0); } catch (Exception) {}
```
but I see that it is a non-trivial pattern and `assertThrows` 
just documents clearly what is expected. Even this isn’t that 
much.

Those functions can provide better error messages, but to be 
honest, the D compiler’s unittest failure messages should be 
improved instead. The “superfluous” list is just an enumeration 
of expressions commonly found in `assert` expressions that should 
have special treatment by the compiler. For `assertThrows`, maybe 
it could even be worth adding it as a primitive:
```d
assert throw(ExceptionType, expression, message)
```
The message is optional, of course. A `static assert` version 
should exist as well.


More information about the Digitalmars-d mailing list