Validate static asserts
Ali Çehreli
acehreli at yahoo.com
Fri Sep 9 18:15:39 UTC 2022
On 9/9/22 10:35, Dennis wrote:
> On Friday, 9 September 2022 at 16:41:54 UTC, Andrey Zherikov wrote:
>> What's about new `compileOutput` trait that returns compiler output?
>> ```d
>> static assert(__traits(compileOutput, { <my code> }) == "message");
>> ```
>
> As a compiler dev, that sounds terrifying. It would make basically every
> change to dmd a breaking change.
For that very reason, I wrote the function 'assertErrorStringContains()'
a couple of days ago to ensure *my* strings were in the output:
A precondition:
void test_1(int i)
in (i > 0, fooError("The value must be positive", i, 42))
{
// ...
}
A unit test that ensures it fails and checks string pieces appear in the
output:
/*
The .msg text of the error contains both the error string and
the data
that is included in the error.
*/
assertErrorStringContains(() => test_1(-1), [ "The value must be
positive",
"-1, 42" ]);
Here is assertErrorStringContains:
// Assert that the expression throws an Error object and that its
string
// representation contains all expected strings.
void assertErrorStringContains(void delegate() expr, string[] expected)
{
bool thrown = false;
try
{
expr();
}
catch (Error err)
{
thrown = true;
import std.algorithm : any, canFind, splitter;
import std.conv : to;
import std.format : format;
auto lines = err.to!string.splitter('\n');
foreach (exp; expected)
{
assert(lines.any!(line => line.canFind(exp)),
format!"Failed to find \"%s\" in the output:
%-(\n |%s%)"(
exp, lines));
}
}
assert(thrown);
}
Ali
More information about the Digitalmars-d-learn
mailing list