Better cleanup of temporary files in tests

Not sure I've squashed them all, but this is a start