On 2/3/2010 9:34 PM, Trip Volpe wrote:
I'm working on a set of handy unit testing accessories for my projects. What
I'd love to achieve is something like this:
expectEqual( myFoo, 3 );
Which, on failure, would result in something along the lines of this diagnostic:
somefile.d:37: Test failure!
Expected: myFoo == 3
Actual: 100, 3
Using a bit of template magic with alias parameters, I've come close:
void expectEquals(alias A, alias B)
( string file = __FILE__, int line = __LINE__ )
{
if(A != B) {
writefln( "Error: %s, line %d", file, line );
writefln( " expected: %s == % s", A.stringof, B.stringof );
writefln( " actual: %s, %s", A, B );
}
}
void main() {
int myFoo = 100;
expectEquals! ( myFoo, 3 );
}
This will produce the output
Error: test.d, line 33
expected: myFoo == 3
actual: 100, 3
Unfortunately, this isn't quite there yet. Alias parameters can only match
single symbols, so something like this won't compile:
int myFoo = 100;
int myArray[5];
expectEquals! ( myFoo, myArray[0] );
So my question is, would it be a good idea to add the ability in future
versions for template parameters to alias entire expressions? It would be
perfect for making templated assertions like this and probably has many other
metaprogramming applications. As a recent convert from C++, I still miss the
ability of macro systems (like GoogleTest) to print highly reflective unit test
assertion messages.
Would there be any drawbacks or difficulties in doing this that I'm completely
missing? :-P
You could potentially use a mixin to do this. The resulting code would
look something like this.
void main()
{
int myFoo = 100;
mixin(expectEquals! ( "myFoo == 3" ));
}