Skip to content

Commit 4b4af55

Browse files
authored
Merge pull request #2520 from bsipocz/TST_fix_warnings
TST: fix warnings and stop ignoring them
2 parents 59e6f84 + c19f188 commit 4b4af55

File tree

26 files changed

+252
-128
lines changed

26 files changed

+252
-128
lines changed

astroquery/alfalfa/tests/test_alfalfa.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ def patch_get_readable_fileobj(request):
3838
@contextmanager
3939
def get_readable_fileobj_mockreturn(filename, **kwargs):
4040
file_obj = data_path(DATA_FILES['spectrum']) # TODO: add images option
41-
yield open(file_obj, 'rb') # read as bytes, assuming FITS
41+
# read as bytes, assuming FITS
42+
with open(file_obj, 'rb') as inputfile:
43+
yield inputfile
4244

4345
mp = request.getfixturevalue("monkeypatch")
4446

astroquery/besancon/tests/test_besancon.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ def get_readable_fileobj_mockreturn(filename, **kwargs):
6565
if isinstance(filename, str):
6666
if '1376235131.430670' in filename:
6767
is_binary = kwargs.get('encoding', None) == 'binary'
68-
file_obj = open(data_path('1376235131.430670.resu'),
69-
"r" + ('b' if is_binary else ''))
68+
with open(data_path('1376235131.430670.resu'), "r" + ('b' if is_binary else '')) as file_obj:
69+
yield file_obj
7070
else:
71-
file_obj = filename
72-
yield file_obj
71+
yield filename
7372

7473
mp = request.getfixturevalue("monkeypatch")
7574

astroquery/cadc/tests/test_cadctap.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"""
88
from io import BytesIO
99
from urllib.parse import urlsplit, parse_qs
10+
from pathlib import Path
1011
import os
1112
import sys
1213

@@ -177,7 +178,7 @@ def raise_for_status(self):
177178
class CapabilitiesResponse:
178179
def __init__(self):
179180
caps_file = data_path('tap_caps.xml')
180-
self.text = open(caps_file, 'r').read()
181+
self.text = Path(caps_file).read_text()
181182

182183
def raise_for_status(self):
183184
pass
@@ -406,7 +407,7 @@ def test_get_images():
406407
Mock(side_effect=lambda x, y, z: ['https://some.url']))
407408
def test_get_images_async():
408409
with patch('astroquery.utils.commons.get_readable_fileobj', autospec=True) as readable_fobj_mock:
409-
readable_fobj_mock.return_value = open(data_path('query_images.fits'), 'rb')
410+
readable_fobj_mock.return_value = Path(data_path('query_images.fits'))
410411

411412
cadc = Cadc()
412413
readable_objs = cadc.get_images_async('08h45m07.5s +54d18m00s',

astroquery/cadc/tests/test_cadctap_remote.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pytest
99
import os
1010
import requests
11+
from pathlib import Path
1112
from datetime import datetime
1213
from astropy.coordinates import SkyCoord
1314
from astropy.io import fits
@@ -66,7 +67,8 @@ def test_query_region(self):
6667
assert len(result) == len(result2[result2['collection'] == 'CFHT'])
6768

6869
# search for a target
69-
results = cadc.query_region(SkyCoord.from_name('M31'), radius=0.016)
70+
with pytest.warns(UserWarning, match='Radius should be of '):
71+
results = cadc.query_region(SkyCoord.from_name('M31'), radius=0.016)
7072
assert len(results) > 20
7173

7274
def test_query_name(self):
@@ -179,7 +181,6 @@ def test_authsession(self):
179181
result = cadc.exec_sync(query)
180182
assert len(result) == 0
181183

182-
@pytest.mark.xfail(reason='#2325')
183184
def test_get_images(self):
184185
cadc = Cadc()
185186
coords = '08h45m07.5s +54d18m00s'
@@ -223,7 +224,6 @@ def test_get_images_against_AS(self):
223224

224225
assert len(filtered_resp_urls) == len(image_urls)
225226

226-
@pytest.mark.xfail(reason='#2325')
227227
def test_get_images_async(self):
228228
cadc = Cadc()
229229
coords = '01h45m07.5s +23d18m00s'
@@ -293,3 +293,20 @@ def test_list_jobs(self):
293293
if len(jobs) > 5:
294294
jobs_subset = cadc.list_async_jobs(last=5)
295295
assert len(jobs_subset) == 5
296+
297+
@pytest.mark.xfail(reason='https://github.com/astropy/astroquery/issues/2538')
298+
def test_uploads(self, tmp_path):
299+
cadc = Cadc()
300+
# save a few observations on a local file
301+
output_file = Path(tmp_path, 'my_observations.xml')
302+
cadc.exec_sync("SELECT TOP 3 observationID FROM caom2.Observation",
303+
output_file=output_file)
304+
assert output_file.exists()
305+
306+
# now use them to join with the remote table
307+
results = cadc.exec_sync(
308+
"SELECT o.observationID, intent FROM caom2.Observation o JOIN "
309+
"tap_upload.test_upload tu ON o.observationID=tu.observationID",
310+
uploads={'test_upload': output_file})
311+
312+
assert len(results) == 3

astroquery/casda/tests/test_casda.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import astropy.units as u
1212
from astropy.table import Table, Column
1313
from astropy.io.votable import parse
14+
from astropy.io.votable.exceptions import W03, W50
1415
from astroquery import log
1516
import numpy as np
1617

@@ -269,7 +270,8 @@ def test_query_region_async_box(patch_get):
269270

270271

271272
def test_filter_out_unreleased():
272-
all_records = parse(data_path('partial_unreleased.xml'), verify='warn').get_first_table().to_table()
273+
with pytest.warns(W03):
274+
all_records = parse(data_path('partial_unreleased.xml'), verify='warn').get_first_table().to_table()
273275
assert all_records[0]['obs_release_date'] == '2017-08-02T03:51:19.728Z'
274276
assert all_records[1]['obs_release_date'] == '2218-01-02T16:51:00.728Z'
275277
assert all_records[2]['obs_release_date'] == ''
@@ -331,7 +333,8 @@ def test_stage_data(patch_get):
331333
casda = Casda()
332334
fake_login(casda, USERNAME, PASSWORD)
333335
casda.POLL_INTERVAL = 1
334-
urls = casda.stage_data(table, verbose=True)
336+
with pytest.warns(W50, match="Invalid unit string 'pixels'"):
337+
urls = casda.stage_data(table, verbose=True)
335338
assert urls == ['http://casda.csiro.au/download/web/111-000-111-000/askap_img.fits.checksum',
336339
'http://casda.csiro.au/download/web/111-000-111-000/askap_img.fits']
337340

@@ -348,7 +351,8 @@ def test_cutout(patch_get):
348351
casda = Casda()
349352
fake_login(casda, USERNAME, PASSWORD)
350353
casda.POLL_INTERVAL = 1
351-
urls = casda.cutout(table, coordinates=centre, radius=radius, verbose=True)
354+
with pytest.warns(W50, match="Invalid unit string 'pixels'"):
355+
urls = casda.cutout(table, coordinates=centre, radius=radius, verbose=True)
352356
assert urls == ['http://casda.csiro.au/download/web/111-000-111-000/cutout.fits.checksum',
353357
'http://casda.csiro.au/download/web/111-000-111-000/cutout.fits']
354358

@@ -363,7 +367,8 @@ def test_cutout_no_args(patch_get):
363367
casda.POLL_INTERVAL = 1
364368
with pytest.raises(ValueError,
365369
match=r"Please provide cutout parameters such as coordinates, band or channel\."):
366-
casda.cutout(table)
370+
with pytest.warns(W50, match="Invalid unit string 'pixels'"):
371+
casda.cutout(table)
367372

368373

369374
def test_cutout_unauthorised(patch_get):

astroquery/eso/tests/test_eso_remote.py

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Licensed under a 3-clause BSD style license - see LICENSE.rst
22
import numpy as np
33
import pytest
4+
import warnings
45

56
from astroquery.exceptions import LoginError, NoResultsWarning
67
from astroquery.eso import Eso
@@ -15,6 +16,9 @@
1516
# TODO: make this a configuration item
1617
SKIP_SLOW = True
1718

19+
SGRA_SURVEYS = ['195.B-0283', 'GIRAFFE', 'HARPS', 'HAWKI', 'KMOS',
20+
'MW-BULGE-PSFPHOT', 'VPHASplus', 'VVV', 'VVVX', 'XSHOOTER']
21+
1822

1923
@pytest.mark.remote_data
2024
class TestEso:
@@ -81,6 +85,7 @@ def test_empty_return(self):
8185
eso = Eso()
8286
surveys = eso.list_surveys(cache=False)
8387
assert len(surveys) > 0
88+
8489
# Avoid SESAME
8590
with pytest.warns(NoResultsWarning):
8691
result_s = eso.query_surveys(surveys[0], coord1=202.469575,
@@ -142,6 +147,8 @@ def test_retrieve_data_and_calib(self):
142147
# list.
143148
assert len(result) == 1
144149

150+
# TODO: remove filter when https://github.com/astropy/astroquery/issues/2539 is fixed
151+
@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")
145152
@pytest.mark.parametrize('instrument', instrument_list)
146153
def test_help(self, instrument):
147154
eso = Eso()
@@ -166,7 +173,7 @@ def test_each_instrument_SgrAstar(self, tmp_path):
166173
instruments = eso.list_instruments(cache=False)
167174

168175
for instrument in instruments:
169-
with pytest.warns(None) as record:
176+
with warnings.catch_warnings(record=True) as record:
170177
result_i = eso.query_instrument(instrument, coord1=266.41681662,
171178
coord2=-29.00782497, cache=False)
172179
# Sometimes there are ResourceWarnings, we ignore those for this test
@@ -175,36 +182,30 @@ def test_each_instrument_SgrAstar(self, tmp_path):
175182
else:
176183
assert len(result_i) > 0
177184

178-
@pytest.mark.filterwarnings("ignore::ResourceWarning")
179-
def test_each_survey_SgrAstar(self, tmp_path):
185+
def test_each_survey_and_SgrAstar(self, tmp_path):
180186
eso = Eso()
181187
eso.cache_location = tmp_path
188+
eso.ROW_LIMIT = 5
189+
182190

183191
surveys = eso.list_surveys(cache=False)
184192
for survey in surveys:
185-
with pytest.warns(None) as record:
193+
if survey in SGRA_SURVEYS:
186194
result_s = eso.query_surveys(survey, coord1=266.41681662,
187195
coord2=-29.00782497,
188196
box='01 00 00',
189197
cache=False)
190-
# Sometimes there are ResourceWarnings, we ignore those for this test
191-
if len(record) > 0 and NoResultsWarning in {record[i].category for i in range(len(record))}:
198+
assert len(result_s) > 0
199+
else:
200+
with pytest.warns(NoResultsWarning):
201+
result_s = eso.query_surveys(survey, coord1=266.41681662,
202+
coord2=-29.00782497,
203+
box='01 00 00',
204+
cache=False)
192205
assert result_s is None
193-
else:
194-
print([record[i].message for i in range(len(record))])
195-
assert len(result_s) > 0
196-
197-
@pytest.mark.skipif("SKIP_SLOW")
198-
@pytest.mark.parametrize('cache', (False, True))
199-
def test_each_survey_nosource(self, tmp_path, cache):
200-
eso = Eso()
201-
eso.cache_location = tmp_path
202-
eso.ROW_LIMIT = 5
203206

204-
surveys = eso.list_surveys(cache=cache)
205-
for survey in surveys:
206-
# just test that it doesn't crash
207-
eso.query_surveys(survey, cache=cache)
207+
generic_result = eso.query_surveys(survey)
208+
assert len(generic_result) > 0
208209

209210
def test_mixed_case_instrument(self, tmp_path):
210211
eso = Eso()

astroquery/exoplanet_orbit_database/exoplanet_orbit_database.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Licensed under a 3-clause BSD style license - see LICENSE.rst
22
import json
33
import os
4+
import warnings
45

56
from astropy.utils.data import download_file
67
from astropy.io import ascii
@@ -30,9 +31,9 @@ def __init__(self):
3031
def param_units(self):
3132
if self._param_units is None:
3233
module_dir = os.path.dirname(os.path.abspath(__file__))
33-
units_file = open(os.path.join(module_dir, 'data',
34-
'exoplanet_orbit_database_units.json'))
35-
self._param_units = json.load(units_file)
34+
filename = os.path.join(module_dir, 'data', 'exoplanet_orbit_database_units.json')
35+
with open(filename) as units_file:
36+
self._param_units = json.load(units_file)
3637

3738
return self._param_units
3839

@@ -82,7 +83,11 @@ def get_table(self, cache=True, show_progress=True, table_path=None):
8283
except ValueError:
8384
print(f"WARNING: Unit {self.param_units[col]} not recognised")
8485

85-
self._table = QTable(exoplanets_table)
86+
# Masked quantities are not supported in older astropy, warnings are raised for <v5.0
87+
with warnings.catch_warnings():
88+
warnings.filterwarnings('ignore', message='dropping mask in Quantity column',
89+
category=UserWarning)
90+
self._table = QTable(exoplanets_table)
8691

8792
return self._table
8893

astroquery/heasarc/tests/test_heasarc_remote_isdc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import pytest
44
import requests
55
from astropy.time import Time, TimeDelta
6+
import astropy.units as u
67

78
from ...heasarc import Heasarc, Conf
89
from ...utils import commons
@@ -83,7 +84,7 @@ def test_compare_time(self, patch_get):
8384

8485
heasarc = Heasarc()
8586

86-
month_ago = (Time.now() - TimeDelta(30)).isot[:10]
87+
month_ago = (Time.now() - TimeDelta(30 * u.day)).isot[:10]
8788
today = Time.now().isot[:10]
8889
T = month_ago + " .. " + today
8990

astroquery/ipac/irsa/ibe/core.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
https://irsa.ipac.caltech.edu/ibe/
99
"""
1010

11-
1211
import os
1312
import webbrowser
1413
from bs4 import BeautifulSoup
@@ -270,7 +269,7 @@ def list_missions(self, cache=True):
270269
response = self._request('GET', url, timeout=self.TIMEOUT,
271270
cache=cache)
272271

273-
root = BeautifulSoup(response.text)
272+
root = BeautifulSoup(response.text, 'html5lib')
274273
links = root.findAll('a')
275274

276275
missions = [os.path.basename(a.attrs['href'].rstrip('/'))
@@ -308,7 +307,7 @@ def list_datasets(self, mission=None, cache=True):
308307
response = self._request('GET', url, timeout=self.TIMEOUT,
309308
cache=cache)
310309

311-
root = BeautifulSoup(response.text)
310+
root = BeautifulSoup(response.text, 'html5lib')
312311
links = root.findAll('a')
313312
datasets = [a.text for a in links
314313
if a.attrs['href'].count('/') >= 4 # shown as '..'; ignore
@@ -362,7 +361,7 @@ def list_tables(self, mission=None, dataset=None, cache=True):
362361
response = self._request('GET', url, timeout=self.TIMEOUT,
363362
cache=cache)
364363

365-
root = BeautifulSoup(response.text)
364+
root = BeautifulSoup(response.text, 'html5lib')
366365
return [tr.find('td').string for tr in root.findAll('tr')[1:]]
367366

368367
# Unfortunately, the URL construction for each data set is different, and

astroquery/ipac/irsa/sha/tests/test_sha.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ def data_path(filename):
2222
def get_mockreturn(url, params=None, stream=False, timeout=10, **kwargs):
2323
if stream:
2424
filename = data_path(DATA_FILES['img'])
25-
return MockResponse(open(filename, 'rb').read(),
26-
content_type='image/fits', **kwargs)
25+
with open(filename, 'rb') as infile:
26+
return MockResponse(infile.read(), content_type='image/fits', **kwargs)
2727
elif params['RA'] == 163.6136:
2828
filename = data_path(DATA_FILES['pos_t'])
2929
elif params['NAIFID'] == 2003226:

0 commit comments

Comments
 (0)