[Issue 11255] Support for inner unittests

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri May 28 00:39:25 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=11255

--- Comment #2 from Witold Baryluk <witold.baryluk+d at gmail.com> ---
One would think that it might be possible to access nested static functions
using some naming tricks, from outside, like this:

```d
int bar(int a) {
    static int d;

    static int foo(int b) {
        b = d;
        return b + 1;
    }

    return foo(a);
}

unittest {
  alias foo = bar.foo;
  assert(foo(5) == 6);
}
```

but this have two issues that I can think of:

1) nested static functions can access nested static variables, other nested
functions (including themselves), and globals. That can be problematic for
unittesting.

2) It is possible to create multiple nested functions with the same name (not
just function overloads), for example:

```d
int bar(int a) {
    static int d;

    if (a > 10) {
        static int foo(int b) {
            b = d;
            return b + 1;
        }
        return foo(a);
    } else {
        static int foo(int b) {
            b += d * 100;
            return b + 100;
        }
        return foo(a);
    }
}
unittest {
  bar.foo  // refers to which foo?
}
```

or make multiple different symbols with the same name:

```d
int bar(int a) {
    static int d;

    if (a > 10) {
        static int foo(int b) {
            b = d;
            return b + 1;
        }
        return foo(a);
    } else {
        int foo = 5;
        return foo + a;
    }
}

unittest {
  bar.foo // refers to what?
}
```

So, that is going to be too complex and require too much ambiguity.

Directly nested unittest makes this obvious and explicit, by using local
scoping rules and lookup:

```
int bar(int a) {
    static int d;

    if (a > 10) {
        static int foo(int b) {
            b = d;
            return b + 1;
        }
        unittest {
            d = 42;
            assert(foo(137) == 43);
        }
        return foo(a);
    } else {
        static int foo(int b) {
            b += d * 100;
            return b + 100;
        }
        unittest {
            d = 1;
            assert(foo(137) == 337);
        }
        return foo(a);
    }
}

```

--


More information about the Digitalmars-d-bugs mailing list