improve test and error message for writing to file