[DM] Close files after writing, refactoring tests