Fix memory leaks in case of failed tests
Before this commit if the tests failed, there were memory leaks
and tests created writeonly files (which you can't add to git,
for example). This commit makes sure that tests will overwrite
permissions to make the files read-write and close the image
no matter if the tests are passing or not.