unittest behaviour
user1234
user1234 at 12.de
Mon Dec 16 08:52:31 UTC 2024
On Sunday, 15 December 2024 at 08:45:22 UTC, DLearner wrote:
> Please consider:
>
> ```
> size_t foo() {
> static size_t var1 = 1;
>
> var1 = var1 + 1;
> return var1;
> }
>
> unittest {
>
> assert(foo() == 2);
> assert(foo() == 3);
> }
>
> ```
>
> which works as expected.
>
> But
>
> ```
> size_t foo1() {
> static size_t var1 = 1;
>
> var1 = var1 + 1;
> return var1;
> }
>
> unittest {
> assert(foo1() == 2);
> }
>
> unittest {
> assert(foo1() == 2);
> }
>
> ```
>
> Fails on the second unittest.
>
> I appreciate this behaviour matches the docs (so not a bug),
> but is it desirable?
Yes. Remember that you have the function attribute `pure` [[1]].
It would have avoided the problem.. for instance:
```d
size_t foo1() {
static size_t var1 = 1;
var1 = var1 + 1;
return var1;
}
pure unittest {
assert(foo1() == 2);
}
pure unittest {
assert(foo1() == 2);
}
```
refuses to compile with the following errors
> test.d(9,15): Error: `pure` function
> `temp_7F58D0140210.__unittest_L8_C6` cannot call impure
> function `temp_7F58D0140210.foo1`
> test.d(13,15): Error: `pure` function
> `temp_7F58D0140210.__unittest_L12_C6` cannot call impure
> function `temp_7F58D0140210.foo1`
With `pure` that you would have seen the problem, that is "oh,
the global state".
[1]: https://dlang.org/spec/function.html#pure-functions
More information about the Digitalmars-d-learn
mailing list