unittesting generic functions

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Thu Aug 14 14:34:02 PDT 2014


On 8/14/14, 1:25 PM, Walter Bright wrote:
> On 8/13/2014 9:02 PM, H. S. Teoh via Digitalmars-d wrote:
>> 4) How much can you realistically test on a generic type argument T,
>> that you can't already cover with concrete types? I'm finding that the
>> per-instantiation behaviour of unittest blocks inside templated
>> structs/classes is rarely desired, esp. when you write ddoc unittests
>> (because you want code examples in the docs to involve concrete types,
>> not abstract types, otherwise they are of limited use to the reader).
>> Because of this, I often move unittests outside the aggregate or enclose
>> them in static if's. This suggests that perhaps per-instantiation
>> unittests are only of limited utility.
>
> Just to expand on this, one of the great advantages of template
> functions and separate unittests is the unittest can instantiate the
> template function with "mocked up" arguments. Instantiating the unittest
> for every type passed to it would defeat that method.

Clearly unittests that mock up arguments etc. are a useful device for 
unittesting. But the point of generic unittests is a tad different and 
has to do with a fundamental difference between C++'s and D's approach 
to generics.

In C++ it's entirely acceptable to fail to instantiate a template. In 
fact the C++ idiom SFINAE is literally based on that - "Substitution 
Failure Is Not An Error". There's a bunch of detail to it but bottom 
line it's totally fine for a template to fail to instantiate, both 
technically and socially (e.g. you get syntax errors in the template 
code etc). There's a good amount of dissatisfaction in the C++ community 
about that, which has led to a lot of work on concepts.

In D, it's not acceptable to fail to instantiate; a template should 
either instantiate and work, get filtered out by a template constraint, 
or fail with information by means of a static assert. Random syntax 
errors inside the template are considered poor style.

It follows that once a D template gets instantiated, it's supposed to 
work as expected for the entire range of types it was meant to.


Andrei



More information about the Digitalmars-d mailing list