Helpers for writing unittests

Idan Arye via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 30 17:54:28 PDT 2015


On Friday, 31 July 2015 at 00:30:23 UTC, Jonathan M Davis wrote:
> On Friday, 31 July 2015 at 00:07:43 UTC, Idan Arye wrote:
>> Thoughts?
>
> Some unit test helpers for this sort of thing might be nice, 
> but I don't think that it really buys us much with this 
> particular case. You could just as easily do
>
> unittest
> {
>     foreach(T; TypeTuple!(ubyte, byte, ushort, short, uint, 
> int, ulong, long))
>         static assert(is(typeof(foo(T.init)));
> }
>
> and the code is basically as long as is with assertCompilesWith 
> - shorter even. The above example is longer due to not using an 
> alias for the integral types like you did, but if that same 
> alias were used, then it becomes
>
> unittest
> {
>     foreach(T; IntegerTypes)
>         static assert(is(typeof(foo(T.init)));
> }
>
> which isn't all that different than
>
> unittest
> {
>     assertCompilesWith!(IntegerTypes, (x) {
>         foo(x);
>     });
> }

The resulting compilation errors are extremely different. With 
your method we get:

/d391/f994.d(31): Error: static assert (is(typeof(__error))) is 
false

which doesn't tell us what the problem is. With my method we get:

/d433/f500.d(25): Error: cannot implicitly convert expression (x) 
of type ulong to int /d433/f500.d(31): Error: template instance 
f500.foo!ulong error instantiating

And yes, a lot of "static stack trace" after that, but these too 
lines tells us what the problem is and which template parameters 
caused it.

Of course, if you just ran the function inside the foreach loop 
you'd get nice error messages as well - but then you'd have to 
write tests that actually run. Which is easy for numbers, because 
they are all the same type of data with different sizes, but can 
get tricky when you have more complex types, that differ more in 
their behavior.


More information about the Digitalmars-d mailing list