Is it a bug in unittest ?

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Sep 1 11:23:12 PDT 2016


On Thu, Sep 01, 2016 at 06:11:55PM +0000, angel via Digitalmars-d wrote:
> If one creates a unittest block in a templated class (or struct), the
> unittest block will be multiplied per class specialization, which
> might turn out to be quite large number.
> 
> E.g.
>  struct A(T) {
>      ...
>      unittest {
>          ...
>      }
>  }
> 
>  ...
> 
>  auto a = A!int;
>  auto b = A!int;
>  auto c = A!double;
> 
> The unittest block will be instantiated twice (per A!int and
> A!double).  But in some (many ?) cases unittest doesn't even exercise
> the generics, merely using some particular type.
> 
> What is it, a bug ?

It can be construed to be a bug or a feature, depending on how you use
it. :-)

A unittest block inside a template is generally useful for testing
things that depend on the template parameters, e.g., to ensure that
A!int, A!double, A!string, etc., all satisfy certain requirements.  But
if the unittest block tests only specific instantiations, e.g., only
A!int, then it's better to move it outside the template body, so that
it's only instantiated once.

In other words, unittest inside a template body is useful for testing
*all* instantiations of a template; unittest outside a template body is
useful for testing *specific* instantiations.

Of course, moving unittests outside the template is troublesome if
you're using the ddoc'd unittest feature (where the body of a unittest
becomes part of a member function's documentation). In such cases you
could do something like this:

	struct A(T) {
		/// ddoc body here
		auto myMethod(Args)(Args args) { ... }

		static if (T == int)
		///
		unittest {
			... // test A!int here
		}
	}

	// of course, make sure the unittest actually runs!
	version(unittest) auto A_int = A!int;


T

-- 
Doubtless it is a good thing to have an open mind, but a truly open mind should be open at both ends, like the food-pipe, with the capacity for excretion as well as absorption. -- Northrop Frye


More information about the Digitalmars-d mailing list