I want to propose that we provide a mechanism to semantically detach unit tests from the scope they are written in. Such unittests would be treated as if they were not in the same scope or module. This includes detached unit tests inside templates. The only stipulation is that the current module is assumed imported.
For a strawman syntax, let's do what everyone does ... overload static
!
import std.stdio;
// static unittests help validate API does not include private functions
struct S
{
private int x;
unittest {
auto s = S(42);
s.foo(); // ok, this is not a detached unittest
}
static unittest {
auto s = S(23);
//s.x == 23; // error, x not visible
}
}
private void foo(S s) {
assert(s.x == 42);
}
static unittest {
auto s = S(42);
//s.foo(); // error, foo not visible.
}
// static unittests help with documentation on templated types
struct Arr(T) {
private T[] arr;
void append(T val) {
arr ~= val;
}
///
static unittest {
// Arr arr; // Error, you are not in this scope, so Arr is an uninstantiated template
Arr!int arr; // ok
arr.append(1);
import std.stdio; // must re-import things as if you weren't in this module
// writeln(arr.arr); // nope, this is a private member
writeln(arr.getArray()); // must use public API
}
T[] getArray() => arr;
}
thoughts?
-Steve