2323from ....io import fits
2424from ....tests .helper import raises , catch_warnings , ignore_warnings
2525from ....utils .data import conf , get_pkg_data_filename
26+ from ....utils .exceptions import AstropyUserWarning
2627from ....utils import data
2728
2829
2930class TestCore (FitsTestCase ):
30- def test_with_statement (self ):
31- with fits .open (self .data ('ascii.fits' )) as f :
32- pass
3331
3432 @raises (OSError )
3533 def test_missing_file (self ):
@@ -40,13 +38,12 @@ def test_filename_is_bytes_object(self):
4038 fits .open (self .data ('ascii.fits' ).encode ())
4139
4240 def test_naxisj_check (self ):
43- hdulist = fits .open (self .data ('o4sp040b0_raw.fits' ))
41+ with fits .open (self .data ('o4sp040b0_raw.fits' )) as hdulist :
42+ hdulist [1 ].header ['NAXIS3' ] = 500
4443
45- hdulist [1 ].header ['NAXIS3' ] = 500
46-
47- assert 'NAXIS3' in hdulist [1 ].header
48- hdulist .verify ('silentfix' )
49- assert 'NAXIS3' not in hdulist [1 ].header
44+ assert 'NAXIS3' in hdulist [1 ].header
45+ hdulist .verify ('silentfix' )
46+ assert 'NAXIS3' not in hdulist [1 ].header
5047
5148 def test_byteswap (self ):
5249 p = fits .PrimaryHDU ()
@@ -74,14 +71,12 @@ def test_fits_file_path_object(self):
7471 Testing when fits file is passed as pathlib.Path object #4412.
7572 """
7673 fpath = pathlib .Path (get_pkg_data_filename ('data/tdim.fits' ))
77- hdulist = fits .open (fpath )
78-
79- assert hdulist [0 ].filebytes () == 2880
80- assert hdulist [1 ].filebytes () == 5760
81-
82- hdulist2 = fits .open (self .data ('tdim.fits' ))
74+ with fits .open (fpath ) as hdulist :
75+ assert hdulist [0 ].filebytes () == 2880
76+ assert hdulist [1 ].filebytes () == 5760
8377
84- assert FITSDiff (hdulist2 , hdulist ).identical is True
78+ with fits .open (self .data ('tdim.fits' )) as hdulist2 :
79+ assert FITSDiff (hdulist2 , hdulist ).identical is True
8580
8681 def test_add_del_columns (self ):
8782 p = fits .ColDefs ([])
@@ -154,12 +149,12 @@ def test_set_card_value(self):
154149 assert header .cards [0 ].comment == comment
155150
156151 def test_uint (self ):
157- hdulist_f = fits . open ( self .data ('o4sp040b0_raw.fits' ), uint = False )
158- hdulist_i = fits .open (self . data ( 'o4sp040b0_raw.fits' ) , uint = True )
159-
160- assert hdulist_f [1 ].data .dtype == np .float32
161- assert hdulist_i [1 ].data .dtype == np .uint16
162- assert np .all (hdulist_f [1 ].data == hdulist_i [1 ].data )
152+ filename = self .data ('o4sp040b0_raw.fits' )
153+ with fits .open (filename , uint = False ) as hdulist_f :
154+ with fits . open ( filename , uint = True ) as hdulist_i :
155+ assert hdulist_f [1 ].data .dtype == np .float32
156+ assert hdulist_i [1 ].data .dtype == np .uint16
157+ assert np .all (hdulist_f [1 ].data == hdulist_i [1 ].data )
163158
164159 def test_fix_missing_card_append (self ):
165160 hdu = fits .ImageHDU ()
@@ -317,48 +312,50 @@ def test_getext(self):
317312 Test the various different ways of specifying an extension header in
318313 the convenience functions.
319314 """
320-
321- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , 1 )
315+ filename = self . data ( 'test0.fits' )
316+ hl , ext = _getext (filename , 'readonly' , 1 )
322317 assert ext == 1
323- pytest .raises (ValueError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
318+ pytest .raises (ValueError , _getext , filename , 'readonly' ,
324319 1 , 2 )
325- pytest .raises (ValueError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
320+ pytest .raises (ValueError , _getext , filename , 'readonly' ,
326321 (1 , 2 ))
327- pytest .raises (ValueError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
322+ pytest .raises (ValueError , _getext , filename , 'readonly' ,
328323 'sci' , 'sci' )
329- pytest .raises (TypeError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
324+ pytest .raises (TypeError , _getext , filename , 'readonly' ,
330325 1 , 2 , 3 )
331- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , ext = 1 )
326+ hl , ext = _getext (filename , 'readonly' , ext = 1 )
332327 assert ext == 1
333- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , ext = ('sci' , 2 ))
328+ hl , ext = _getext (filename , 'readonly' , ext = ('sci' , 2 ))
334329 assert ext == ('sci' , 2 )
335- pytest .raises (TypeError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
330+ pytest .raises (TypeError , _getext , filename , 'readonly' ,
336331 1 , ext = ('sci' , 2 ), extver = 3 )
337- pytest .raises (TypeError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
332+ pytest .raises (TypeError , _getext , filename , 'readonly' ,
338333 ext = ('sci' , 2 ), extver = 3 )
339334
340- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , 'sci' )
335+ hl , ext = _getext (filename , 'readonly' , 'sci' )
341336 assert ext == ('sci' , 1 )
342- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , 'sci' , 1 )
337+ hl , ext = _getext (filename , 'readonly' , 'sci' , 1 )
343338 assert ext == ('sci' , 1 )
344- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , ('sci' , 1 ))
339+ hl , ext = _getext (filename , 'readonly' , ('sci' , 1 ))
345340 assert ext == ('sci' , 1 )
346- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , 'sci' ,
341+ hl , ext = _getext (filename , 'readonly' , 'sci' ,
347342 extver = 1 , do_not_scale_image_data = True )
348343 assert ext == ('sci' , 1 )
349- pytest .raises (TypeError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
344+ pytest .raises (TypeError , _getext , filename , 'readonly' ,
350345 'sci' , ext = 1 )
351- pytest .raises (TypeError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
346+ pytest .raises (TypeError , _getext , filename , 'readonly' ,
352347 'sci' , 1 , extver = 2 )
353348
354- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , extname = 'sci' )
349+ hl , ext = _getext (filename , 'readonly' , extname = 'sci' )
355350 assert ext == ('sci' , 1 )
356- hl , ext = _getext (self . data ( 'test0.fits' ) , 'readonly' , extname = 'sci' ,
351+ hl , ext = _getext (filename , 'readonly' , extname = 'sci' ,
357352 extver = 1 )
358353 assert ext == ('sci' , 1 )
359- pytest .raises (TypeError , _getext , self . data ( 'test0.fits' ) , 'readonly' ,
354+ pytest .raises (TypeError , _getext , filename , 'readonly' ,
360355 extver = 1 )
361356
357+ hl .close () # Close file handler
358+
362359 def test_extension_name_case_sensitive (self ):
363360 """
364361 Tests that setting fits.conf.extension_name_case_sensitive at
@@ -385,26 +382,29 @@ def test_hdu_fromstring(self):
385382 Tests creating a fully-formed HDU object from a string containing the
386383 bytes of the HDU.
387384 """
385+ infile = self .data ('test0.fits' )
386+ outfile = self .temp ('test.fits' )
388387
389- dat = open (self .data ('test0.fits' ), 'rb' ).read ()
388+ with open (infile , 'rb' ) as fin :
389+ dat = fin .read ()
390390
391391 offset = 0
392- with fits .open (self . data ( 'test0.fits' ) ) as hdul :
392+ with fits .open (infile ) as hdul :
393393 hdulen = hdul [0 ]._data_offset + hdul [0 ]._data_size
394394 hdu = fits .PrimaryHDU .fromstring (dat [:hdulen ])
395395 assert isinstance (hdu , fits .PrimaryHDU )
396396 assert hdul [0 ].header == hdu .header
397397 assert hdu .data is None
398398
399399 hdu .header ['TEST' ] = 'TEST'
400- hdu .writeto (self . temp ( 'test.fits' ) )
401- with fits .open (self . temp ( 'test.fits' ) ) as hdul :
400+ hdu .writeto (outfile )
401+ with fits .open (outfile ) as hdul :
402402 assert isinstance (hdu , fits .PrimaryHDU )
403403 assert hdul [0 ].header [:- 1 ] == hdu .header [:- 1 ]
404404 assert hdul [0 ].header ['TEST' ] == 'TEST'
405405 assert hdu .data is None
406406
407- with fits .open (self . data ( 'test0.fits' ) )as hdul :
407+ with fits .open (infile )as hdul :
408408 for ext_hdu in hdul [1 :]:
409409 offset += hdulen
410410 hdulen = len (str (ext_hdu .header )) + ext_hdu ._data_size
@@ -540,32 +540,31 @@ def test_writeto(self):
540540 Simple test for writing a trivial header and some data to a file
541541 with the `writeto()` convenience function.
542542 """
543-
543+ filename = self . temp ( 'array.fits' )
544544 data = np .zeros ((100 , 100 ))
545545 header = fits .Header ()
546- fits .writeto (self .temp ('array.fits' ), data , header = header ,
547- overwrite = True )
548- hdul = fits .open (self .temp ('array.fits' ))
549- assert len (hdul ) == 1
550- assert (data == hdul [0 ].data ).all ()
546+ fits .writeto (filename , data , header = header , overwrite = True )
547+ with fits .open (filename ) as hdul :
548+ assert len (hdul ) == 1
549+ assert (data == hdul [0 ].data ).all ()
551550
552551 def test_writeto_2 (self ):
553552 """
554553 Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/107
555554
556555 Test of `writeto()` with a trivial header containing a single keyword.
557556 """
558-
557+ filename = self . temp ( 'array.fits' )
559558 data = np .zeros ((100 , 100 ))
560559 header = fits .Header ()
561560 header .set ('CRPIX1' , 1. )
562- fits .writeto (self . temp ( 'array.fits' ) , data , header = header ,
561+ fits .writeto (filename , data , header = header ,
563562 overwrite = True , output_verify = 'silentfix' )
564- hdul = fits .open (self . temp ( 'array.fits' ))
565- assert len (hdul ) == 1
566- assert (data == hdul [0 ].data ).all ()
567- assert 'CRPIX1' in hdul [0 ].header
568- assert hdul [0 ].header ['CRPIX1' ] == 1.0
563+ with fits .open (filename ) as hdul :
564+ assert len (hdul ) == 1
565+ assert (data == hdul [0 ].data ).all ()
566+ assert 'CRPIX1' in hdul [0 ].header
567+ assert hdul [0 ].header ['CRPIX1' ] == 1.0
569568
570569
571570class TestFileFunctions (FitsTestCase ):
@@ -864,7 +863,8 @@ def test_read_closed_file(self):
864863
865864 f = open (self .data ('test0.fits' ), 'rb' )
866865 f .close ()
867- assert len (fits .open (f )) == 5
866+ with fits .open (f ) as f2 :
867+ assert len (f2 ) == 5
868868
869869 def test_read_open_gzip_file (self ):
870870 """Read from an open gzip file object."""
@@ -1041,7 +1041,9 @@ def mmap_patched(*args, **kwargs):
10411041
10421042 with fits .open (self .data ('test0.fits' ), memmap = True ) as hdulist :
10431043 with patch .object (mmap , 'mmap' , side_effect = mmap_patched ) as p :
1044- data = hdulist [1 ].data
1044+ with pytest .warns (AstropyUserWarning , match = "Could not memory "
1045+ "map array with mode='readonly'" ):
1046+ data = hdulist [1 ].data
10451047 p .reset_mock ()
10461048 assert not data .flags .writeable
10471049
@@ -1272,6 +1274,7 @@ def test_streaming_hdu(self):
12721274 shdu = self ._make_streaming_hdu (self .temp ('new.fits' ))
12731275 assert isinstance (shdu .size , int )
12741276 assert shdu .size == 100
1277+ shdu .close ()
12751278
12761279 @raises (ValueError )
12771280 def test_streaming_hdu_file_wrong_mode (self ):
@@ -1293,9 +1296,9 @@ def test_streaming_hdu_write_file(self):
12931296 shdu .write (arr )
12941297 assert shdu .writecomplete
12951298 assert shdu .size == 100
1296- hdul = fits .open (self .temp ('new.fits' ))
1297- assert len (hdul ) == 1
1298- assert (hdul [0 ].data == arr ).all ()
1299+ with fits .open (self .temp ('new.fits' )) as hdul :
1300+ assert len (hdul ) == 1
1301+ assert (hdul [0 ].data == arr ).all ()
12991302
13001303 def test_streaming_hdu_write_file_like (self ):
13011304 """Test streaming an HDU to an open file-like object."""
@@ -1328,14 +1331,19 @@ def test_fix_invalid_extname(self, capsys):
13281331 ihdu = fits .ImageHDU ()
13291332 ihdu .header ['EXTNAME' ] = 12345678
13301333 hdul = fits .HDUList ([phdu , ihdu ])
1334+ filename = self .temp ('temp.fits' )
13311335
1332- pytest .raises (fits .VerifyError , hdul .writeto , self . temp ( 'temp.fits' ) ,
1336+ pytest .raises (fits .VerifyError , hdul .writeto , filename ,
13331337 output_verify = 'exception' )
1334- hdul .writeto (self .temp ('temp.fits' ), output_verify = 'fix' )
1335- with fits .open (self .temp ('temp.fits' )):
1338+ with pytest .warns (fits .verify .VerifyWarning ,
1339+ match = 'Verification reported errors' ):
1340+ hdul .writeto (filename , output_verify = 'fix' )
1341+ with fits .open (filename ):
13361342 assert hdul [1 ].name == '12345678'
13371343 assert hdul [1 ].header ['EXTNAME' ] == '12345678'
13381344
1345+ hdul .close ()
1346+
13391347 def _make_streaming_hdu (self , fileobj ):
13401348 hd = fits .Header ()
13411349 hd ['SIMPLE' ] = (True , 'conforms to FITS standard' )
@@ -1358,5 +1366,5 @@ def test_error_if_memmap_impossible(self):
13581366
13591367 # However, it should not fail if do_not_scale_image_data was used:
13601368 # See https://github.com/astropy/astropy/issues/3766
1361- hdul = fits .open (pth , memmap = True , do_not_scale_image_data = True )
1362- hdul [0 ].data # Just make sure it doesn't crash
1369+ with fits .open (pth , memmap = True , do_not_scale_image_data = True ) as hdul :
1370+ hdul [0 ].data # Just make sure it doesn't crash
0 commit comments