Ensure file handle is always closed in tests