Misc test leaks

Here is a collection of small fixes for many test cases that otherwise would fail (on Windows) or leave file descriptors unclosed.