Skip to content

Commit

Permalink
Fix #1035 unclosed file warning in GiftiImage
Browse files Browse the repository at this point in the history
- Change as proposed by @effigies

Test for `ResourceWarning` in `GiftiImage`

Backport of gh-1038
  • Loading branch information
HippocampusGirl authored and effigies committed Feb 7, 2022
1 parent 295a79b commit f436b73
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
4 changes: 2 additions & 2 deletions nibabel/gifti/gifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,8 +877,8 @@ def to_file_map(self, file_map=None):
"""
if file_map is None:
file_map = self.file_map
f = file_map['image'].get_prepare_fileobj('wb')
f.write(self.to_xml())
with file_map['image'].get_prepare_fileobj('wb') as f:
f.write(self.to_xml())

@classmethod
def from_file_map(klass, file_map, buffer_size=35000000):
Expand Down
12 changes: 11 additions & 1 deletion nibabel/gifti/tests/test_gifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import numpy as np

from nibabel.tmpdirs import InTemporaryDirectory

from ... import load
from .. import (GiftiImage, GiftiDataArray, GiftiLabel,
GiftiLabelTable, GiftiMetaData, GiftiNVPairs,
Expand Down Expand Up @@ -40,7 +42,7 @@ def test_agg_data():

assert_array_equal(surf_gii_img.agg_data('pointset'), point_data)
assert_array_equal(surf_gii_img.agg_data('triangle'), triangle_data)
assert_array_equal(func_gii_img.agg_data('time series'), func_data)
assert_array_equal(func_gii_img.agg_data('time series'), func_data)
assert_array_equal(shape_gii_img.agg_data('shape'), shape_data)

assert surf_gii_img.agg_data('time series') == ()
Expand Down Expand Up @@ -443,3 +445,11 @@ def test_darray_dtype_coercion_failures():
da_copy = gii_copy.darrays[0]
assert np.dtype(da_copy.data.dtype) == np.dtype(darray_dtype)
assert_array_equal(da_copy.data, da.data)


def test_gifti_file_close():
gii = load(test_data('gifti', 'ascii.gii'))
with pytest.WarningsRecorder() as record:
with InTemporaryDirectory():
gii.to_filename('test.gii')
assert not any(isinstance(r.message, ResourceWarning) for r in record.list)

0 comments on commit f436b73

Please sign in to comment.