Improve unit tests crashing on exit

Various commits related to failing unit tests.

The unit tests still crash on exit on my machine, but I observed that the build machine behaves differently, so maybe these changes will improve things there.