unittest{...} as "free" code bolck
spir
denis.spir at gmail.com
Thu Apr 14 04:09:55 PDT 2011
On 04/13/2011 10:38 PM, Andrei Alexandrescu wrote:
> Similarly, it would be great if next to e.g.
> http://d-programming-language.org/phobos-prerelease/std_algorithm.html#setUnion
> there would be a "Try it now" button. Clicking on that button would open an
> overlay with an edit window. The edit window initially contains the example text:
>
> unittest
> {
> int[] a = [ 1, 2, 4, 5, 7, 9 ];
> int[] b = [ 0, 1, 2, 4, 7, 8 ];
> int[] c = [ 10 ];
> assert(setUnion(a, b).length == a.length + b.length);
> assert(equal(setUnion(a, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9][]));
> assert(equal(setUnion(a, c, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9, 10][]));
> }
>
> Then the user can change, compile, and run that program, to ultimately close
> the overlay and return to the documentation.
I recently started to realise a side-effect of the unittest feature is to
provide D with "free code blocks", where one can just put any piece of code;
code that could go on a module's top-level in a dynamic language.
Typically, this allows clean trials. Eg, does '/' perform euclidean division or
true division, on integers / reals?
import std.stdio : writeln;
unittest {
writeln("ints");
writeln(2/2);
writeln(3/2);
}
unittest {
writeln("reals");
writeln(2.0/2);
writeln(3.0/2);
}
void main () {}
Sure, one can use main() for this. But unittest blocks are cleaner and allow
structuration. In the same vein, unittests can be cleanly used to *demonstrate*
language behaviour; for instance in tutorials, when showing issues like on
D-leran, or for... bug reports.
Denis
--
_________________
vita es estrany
spir.wikidot.com
More information about the Digitalmars-d
mailing list