Ah, simple solution to unittests inside templates

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sun Sep 18 03:00:29 PDT 2016


On Saturday, September 17, 2016 21:23:58 Andrej Mitrovic via Digitalmars-d 
wrote:
> On Saturday, 17 September 2016 at 17:22:52 UTC, Andrei
>
> Alexandrescu wrote:
> > The unittest documentation is nicely generated. The unittest
> > code itself is only generated for one instantiation.
>
> I had a similar thought, but I didn't really like verbosity of
> the static if.

It also has the downside that the unit tests still end up in the code of
anyone using the template. It's now only when they use the template with
that particular instantiation, so it's definitely not as bad as just putting
the unittest block inside the templated type like you would if it weren't
templated, but it's still definitely worse than what you get with a
non-templated type.

> I think at some point someone suggested we could implement
> explicit support for such unittests via `static unittest`:
>
> /** Awesome struct */
> struct Awesome(T)
> {
>      /** Awesome function. */
>      void awesome() {}
>
>      ///
>      static unittest
>      {
>          Awesome!int awesome;
>          awesome.awesome;
>      }
> }
>
> A static unittest would not have implicit access to anything
> internal in the aggregation (this is different to your solution
> where the unittest has access to all fields of the Awesome!int
> instance).
>
> Note the difference inside the unittest: it uses `Awesome!int
> awesome` instead of the previous `Awesome awesome`. In your case
> it implicitly refers to the Awesome!int instantiation, however
> you're actually presenting uncompilable code to the user! The
> user might copy-paste it into a main function but it would fail
> to build.
>
> So the feature might have some merit as it would avoid generating
> docs with code which may not even work.

Yes. That's DIP 82:

http://wiki.dlang.org/DIP82

I need to go over it again and then introduce it into the new DIP process.
But I really think that that's where we should go to fix this problem. It
makes for a clean solution that allows you to easily choose whether a
unittest block inside of a template is treated as part of the template or
whether it's just syntactically inside the template so that it can be used
for documentation and so that it can be next to what it's testing, but it's
not actually part of the template semantically.

- Jonathan M Davis



More information about the Digitalmars-d mailing list