Skip to content

Commit 0caebf0

Browse files
authored
Merge pull request #2526 from jdavies-st/2107-test-files-left-behind
MNT: Fix tests that leave behind files in the repo
2 parents 404fa41 + 87d3601 commit 0caebf0

File tree

26 files changed

+374
-447
lines changed

26 files changed

+374
-447
lines changed

.github/workflows/ci_crontests.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ on:
88
schedule:
99
# run every Monday at 5am UTC
1010
- cron: '0 5 * * 1'
11+
workflow_dispatch:
1112

1213
permissions:
1314
contents: read

astroquery/alma/tests/test_alma_remote.py

Lines changed: 38 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
11
# Licensed under a 3-clause BSD style license - see LICENSE.rst
2-
import tempfile
3-
import shutil
4-
import numpy as np
5-
import pytest
6-
72
from datetime import datetime
83
import os
4+
from pathlib import Path
95
from urllib.parse import urlparse
106
import re
117
from unittest.mock import Mock, MagicMock, patch
128

139
from astropy import coordinates
1410
from astropy import units as u
11+
import numpy as np
12+
import pytest
1513

1614
from astroquery.exceptions import CorruptDataWarning
1715
from astroquery.utils.commons import ASTROPY_LT_4_1
@@ -49,15 +47,6 @@ def alma(request):
4947

5048
@pytest.mark.remote_data
5149
class TestAlma:
52-
@pytest.fixture()
53-
def temp_dir(self, request):
54-
my_temp_dir = tempfile.mkdtemp()
55-
56-
def fin():
57-
shutil.rmtree(my_temp_dir)
58-
request.addfinalizer(fin)
59-
return my_temp_dir
60-
6150
def test_public(self, alma):
6251
results = alma.query(payload=None, public=True, maxrec=100)
6352
assert len(results) == 100
@@ -68,8 +57,8 @@ def test_public(self, alma):
6857
for row in results:
6958
assert row['data_rights'] == 'Proprietary'
7059

71-
def test_SgrAstar(self, temp_dir, alma):
72-
alma.cache_location = temp_dir
60+
def test_SgrAstar(self, tmp_path, alma):
61+
alma.cache_location = tmp_path
7362

7463
result_s = alma.query_object('Sgr A*', legacy_columns=True)
7564

@@ -122,9 +111,9 @@ def test_ra_dec(self, alma):
122111
assert len(result) > 0
123112

124113
@pytest.mark.skipif("SKIP_SLOW")
125-
def test_m83(self, temp_dir, alma):
114+
def test_m83(self, tmp_path, alma):
126115
# Runs for over 9 minutes
127-
alma.cache_location = temp_dir
116+
alma.cache_location = tmp_path
128117

129118
m83_data = alma.query_object('M83', science=True, legacy_columns=True)
130119
uids = np.unique(m83_data['Member ous id'])
@@ -149,20 +138,20 @@ def test_data_proprietary(self, alma):
149138
with pytest.raises(AttributeError):
150139
alma.is_proprietary('uid://NON/EXI/STING')
151140

152-
def test_retrieve_data(self, temp_path, alma):
141+
def test_retrieve_data(self, tmp_path, alma):
153142
"""
154143
Regression test for issue 2490 (the retrieval step will simply fail if
155144
given a blank line, so all we're doing is testing that it runs)
156145
"""
157-
alma.cache_location = temp_path
146+
alma.cache_location = tmp_path
158147

159148
# small solar TP-only data set (<1 GB)
160149
uid = 'uid://A001/X87c/X572'
161150

162151
alma.retrieve_data_from_uid([uid])
163152

164-
def test_data_info(self, temp_dir, alma):
165-
alma.cache_location = temp_dir
153+
def test_data_info(self, tmp_path, alma):
154+
alma.cache_location = tmp_path
166155

167156
uid = 'uid://A001/X12a3/Xe9'
168157
data_info = alma.get_data_info(uid, expand_tarfiles=True)
@@ -189,8 +178,8 @@ def test_data_info(self, temp_dir, alma):
189178
file_url = url
190179
break
191180
assert file_url
192-
alma.download_files([file_url], savedir=temp_dir)
193-
assert os.stat(os.path.join(temp_dir, file)).st_size
181+
alma.download_files([file_url], savedir=tmp_path)
182+
assert Path(tmp_path, file).stat().st_size
194183

195184
# mock downloading an entire program
196185
download_files_mock = Mock()
@@ -200,9 +189,9 @@ def test_data_info(self, temp_dir, alma):
200189
comparison = download_files_mock.mock_calls[0][1] == data_info_tar['access_url']
201190
assert comparison.all()
202191

203-
def test_download_data(self, temp_dir, alma):
192+
def test_download_data(self, tmp_path, alma):
204193
# test only fits files from a program
205-
alma.cache_location = temp_dir
194+
alma.cache_location = tmp_path
206195

207196
uid = 'uid://A001/X12a3/Xe9'
208197
data_info = alma.get_data_info(uid, expand_tarfiles=True)
@@ -214,14 +203,14 @@ def test_download_data(self, temp_dir, alma):
214203
alma._download_file = download_mock
215204
urls = [x['access_url'] for x in data_info
216205
if fitsre.match(x['access_url'])]
217-
results = alma.download_files(urls, savedir=temp_dir)
206+
results = alma.download_files(urls, savedir=tmp_path)
218207
alma._download_file.call_count == len(results)
219208
assert len(results) == len(urls)
220209

221-
def test_download_and_extract(self, temp_dir, alma):
210+
def test_download_and_extract(self, tmp_path, alma):
222211
# TODO: slowish, runs for ~90s
223212

224-
alma.cache_location = temp_dir
213+
alma.cache_location = tmp_path
225214
alma._cycle0_tarfile_content_table = {'ID': ''}
226215

227216
uid = 'uid://A001/X12a3/Xe9'
@@ -261,10 +250,10 @@ def test_download_and_extract(self, temp_dir, alma):
261250
[asdm_url], include_asdm=True, regex=r'.*\.py')
262251
delete_mock.assert_called_once_with(
263252
'cache_path/' + asdm_url.split('/')[-1])
264-
assert downloaded_asdm == [os.path.join(temp_dir, 'foo.py')]
253+
assert downloaded_asdm == [Path(tmp_path, 'foo.py')]
265254

266-
def test_doc_example(self, temp_dir, alma):
267-
alma.cache_location = temp_dir
255+
def test_doc_example(self, tmp_path, alma):
256+
alma.cache_location = tmp_path
268257
m83_data = alma.query_object('M83', legacy_columns=True)
269258
# the order can apparently sometimes change
270259
# These column names change too often to keep testing.
@@ -299,8 +288,8 @@ def test_doc_example(self, temp_dir, alma):
299288
# file sizes are replaced with -1
300289
assert (totalsize_mous.to(u.GB).value > 52)
301290

302-
def test_query(self, temp_dir, alma):
303-
alma.cache_location = temp_dir
291+
def test_query(self, tmp_path, alma):
292+
alma.cache_location = tmp_path
304293

305294
result = alma.query(payload={'start_date': '<11-11-2011'},
306295
public=False, legacy_columns=True, science=True)
@@ -395,9 +384,9 @@ def test_user(self, alma):
395384
# This has been reported, as it is definitely a bug.
396385
@pytest.mark.xfail
397386
@pytest.mark.bigdata
398-
def test_cycle1(self, temp_dir, alma):
387+
def test_cycle1(self, tmp_path, alma):
399388
# About 500 MB
400-
alma.cache_location = temp_dir
389+
alma.cache_location = tmp_path
401390
target = 'NGC4945'
402391
project_code = '2012.1.00912.S'
403392
payload = {'project_code': project_code,
@@ -442,9 +431,9 @@ def test_cycle1(self, temp_dir, alma):
442431

443432
@pytest.mark.skipif("SKIP_SLOW")
444433
@pytest.mark.xfail(reason="Not working anymore")
445-
def test_cycle0(self, temp_dir, alma):
434+
def test_cycle0(self, tmp_path, alma):
446435
# About 20 MB
447-
alma.cache_location = temp_dir
436+
alma.cache_location = tmp_path
448437

449438
target = 'NGC4945'
450439
project_code = '2011.0.00121.S'
@@ -477,7 +466,7 @@ def test_cycle0(self, temp_dir, alma):
477466
# There are 10 small files, but only 8 unique
478467
assert len(data) == 8
479468

480-
def test_keywords(self, temp_dir, alma):
469+
def test_keywords(self, tmp_path, alma):
481470

482471
alma.help_tap()
483472
result = alma.query_tap(
@@ -545,44 +534,34 @@ def test_big_download_regression(alma):
545534

546535

547536
@pytest.mark.remote_data
548-
def test_download_html_file(alma):
537+
def test_download_html_file(alma, tmp_path):
538+
alma.cache_location = tmp_path
549539
result = alma.download_files(['https://{}/dataPortal/member.uid___A001_X1284_X1353.qa2_report.html'.format(download_hostname)])
550540
assert result
551541

552542

553543
@pytest.mark.remote_data
554-
def test_verify_html_file(alma, caplog):
555-
# first, make sure the file is not cached (in case this test gets called repeatedly)
556-
# (we are hacking the file later in this test to trigger different failure modes so
557-
# we need it fresh)
558-
try:
559-
result = alma.download_files(['https://{}/dataPortal/member.uid___A001_X1284_X1353.qa2_report.html'.format(download_hostname)], verify_only=True)
560-
local_filepath = result[0]
561-
os.remove(local_filepath)
562-
except FileNotFoundError:
563-
pass
564-
565-
caplog.clear()
544+
def test_verify_html_file(alma, caplog, tmp_path):
545+
alma.cache_location = tmp_path
566546

567547
# download the file
568548
result = alma.download_files(['https://{}/dataPortal/member.uid___A001_X1284_X1353.qa2_report.html'.format(download_hostname)])
569549
assert 'member.uid___A001_X1284_X1353.qa2_report.html' in result[0]
570550

571551
result = alma.download_files(['https://{}/dataPortal/member.uid___A001_X1284_X1353.qa2_report.html'.format(download_hostname)], verify_only=True)
572552
assert 'member.uid___A001_X1284_X1353.qa2_report.html' in result[0]
573-
local_filepath = result[0]
574-
existing_file_length = 66336
575-
assert f"Found cached file {local_filepath} with expected size {existing_file_length}." in caplog.text
553+
local_filepath = Path(result[0])
554+
expected_file_length = local_filepath.stat().st_size
555+
assert f"Found cached file {local_filepath} with expected size {expected_file_length}." in caplog.text
576556

577557
# manipulate the file
578558
with open(local_filepath, 'ab') as fh:
579559
fh.write(b"Extra Text")
580560

581561
caplog.clear()
582-
length = 66336
583-
existing_file_length = length + 10
562+
new_file_length = expected_file_length + 10
584563
with pytest.warns(expected_warning=CorruptDataWarning,
585-
match=f"Found cached file {local_filepath} with size {existing_file_length} > expected size {length}. The download is likely corrupted."):
564+
match=f"Found cached file {local_filepath} with size {new_file_length} > expected size {expected_file_length}. The download is likely corrupted."):
586565
result = alma.download_files(['https://{}/dataPortal/member.uid___A001_X1284_X1353.qa2_report.html'.format(download_hostname)], verify_only=True)
587566
assert 'member.uid___A001_X1284_X1353.qa2_report.html' in result[0]
588567

@@ -593,10 +572,5 @@ def test_verify_html_file(alma, caplog):
593572
caplog.clear()
594573
result = alma.download_files(['https://{}/dataPortal/member.uid___A001_X1284_X1353.qa2_report.html'.format(download_hostname)], verify_only=True)
595574
assert 'member.uid___A001_X1284_X1353.qa2_report.html' in result[0]
596-
length = 66336
597575
existing_file_length = 10
598-
assert f"Found cached file {local_filepath} with size {existing_file_length} < expected size {length}. The download should be continued." in caplog.text
599-
600-
# cleanup: we don't want `test_download_html_file` to fail if this test is re-run
601-
if os.path.exists(local_filepath):
602-
os.remove(local_filepath)
576+
assert f"Found cached file {local_filepath} with size {existing_file_length} < expected size {expected_file_length}. The download should be continued." in caplog.text

astroquery/cds/core.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ def _args_to_payload(self, **kwargs):
256256
self.path_moc_file = os.path.join(os.getcwd(), 'moc.fits')
257257
if os.path.isfile(self.path_moc_file): # Silent overwrite
258258
os.remove(self.path_moc_file)
259-
region.write(self.path_moc_file, format="fits")
259+
region.save(self.path_moc_file, format="fits")
260260
# add the moc region payload to the request payload
261261
elif isinstance(region, CircleSkyRegion):
262262
# add the cone region payload to the request payload

astroquery/cds/tests/test_mocserver_remote.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def test_field_l_param(self, field_l):
6868
@pytest.mark.skipif('mocpy' not in sys.modules,
6969
reason="requires MOCPy")
7070
@pytest.mark.parametrize('moc_order', [5, 10])
71-
def test_moc_order_param(self, moc_order):
71+
def test_moc_order_param(self, moc_order, tmp_cwd):
7272
moc_region = MOC.from_json({'0': [1]})
7373

7474
result = cds.query_region(region=moc_region,

astroquery/conftest.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# Licensed under a 3-clause BSD style license - see LICENSE.rst
22
import os
3+
from pathlib import Path
4+
5+
import pytest
36
# this contains imports plugins that configure py.test for astropy tests.
47
# by importing them here in conftest.py they are discoverable by py.test
58
# no matter how it is invoked within the source tree.
@@ -57,3 +60,14 @@ def pytest_addoption(parser):
5760
help='ALMA site (almascience.nrao.edu, almascience.eso.org or '
5861
'almascience.nao.ac.jp for example)'
5962
)
63+
64+
65+
@pytest.fixture(scope='function')
66+
def tmp_cwd(tmp_path):
67+
"""Perform test in a pristine temporary working directory."""
68+
old_dir = Path.cwd()
69+
os.chdir(tmp_path)
70+
try:
71+
yield tmp_path
72+
finally:
73+
os.chdir(old_dir)

astroquery/esa/iso/tests/test_iso.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def test_get_postcard_link_verbose(self):
5858
link = ida.get_postcard_link(**parameters)
5959

6060
@pytest.mark.remote_data
61-
def test_download_data(self):
61+
def test_download_data(self, tmp_cwd):
6262
parameters = {'tdt': "40001501",
6363
'product_level': "DEFAULT_DATA_SET",
6464
'retrieval_type': "OBSERVATION",
@@ -69,7 +69,7 @@ def test_download_data(self):
6969
assert res == "file.tar", "File name is " + res + " and not file.tar"
7070

7171
@pytest.mark.remote_data
72-
def test_download_postcard(self):
72+
def test_download_postcard(self, tmp_cwd):
7373
parameters = {'tdt': "40001501",
7474
'filename': "file",
7575
'verbose': False}

astroquery/esa/xmm_newton/tests/test_xmm_newton_remote.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def _create_tar(self, tarname, files):
112112
shutil.rmtree(ob_name)
113113

114114
@pytest.mark.remote_data
115-
def test_download_data(self):
115+
def test_download_data(self, tmp_cwd):
116116
parameters = {'observation_id': "0112880801",
117117
'level': "ODF",
118118
'filename': 'file',
@@ -121,7 +121,7 @@ def test_download_data(self):
121121
xsa.download_data(**parameters)
122122

123123
@pytest.mark.remote_data
124-
def test_download_data_single_file(self):
124+
def test_download_data_single_file(self, tmp_cwd):
125125
parameters = {'observation_id': "0762470101",
126126
'level': "PPS",
127127
'name': 'OBSMLI',
@@ -133,7 +133,7 @@ def test_download_data_single_file(self):
133133
xsa.download_data(**parameters)
134134

135135
@pytest.mark.remote_data
136-
def test_get_postcard(self):
136+
def test_get_postcard(self, tmp_cwd):
137137
parameters = {'observation_id': "0112880801",
138138
'image_type': "OBS_EPIC",
139139
'filename': None,
@@ -142,7 +142,7 @@ def test_get_postcard(self):
142142
xsa.get_postcard(**parameters)
143143

144144
@pytest.mark.remote_data
145-
def test_get_postcard_filename(self):
145+
def test_get_postcard_filename(self, tmp_cwd):
146146
parameters = {'observation_id': "0112880801",
147147
'image_type': "OBS_EPIC",
148148
'filename': "test",
@@ -195,7 +195,6 @@ def test_get_epic_metadata(self):
195195
assert report_diff_values(slew_source, table)
196196

197197
@pytest.mark.remote_data
198-
@pytest.mark.xfail(raises=LoginError)
199198
def test_download_proprietary_data_incorrect_credentials(self):
200199
parameters = {'observation_id': "0762470101",
201200
'prop': 'True',
@@ -207,10 +206,10 @@ def test_download_proprietary_data_incorrect_credentials(self):
207206
'extension': 'FTZ',
208207
'verbose': False}
209208
xsa = XMMNewtonClass(self.get_dummy_tap_handler())
210-
xsa.download_data(**parameters)
209+
with pytest.raises(LoginError):
210+
xsa.download_data(**parameters)
211211

212212
@pytest.mark.remote_data
213-
@pytest.mark.xfail(raises=LoginError)
214213
def test_download_proprietary_data_without_credentials(self):
215214
parameters = {'observation_id': "0883780101",
216215
'level': "PPS",
@@ -220,10 +219,11 @@ def test_download_proprietary_data_without_credentials(self):
220219
'extension': 'FTZ',
221220
'verbose': False}
222221
xsa = XMMNewtonClass(self.get_dummy_tap_handler())
223-
xsa.download_data(**parameters)
222+
with pytest.raises(LoginError):
223+
xsa.download_data(**parameters)
224224

225225
@pytest.mark.remote_data
226-
def test_get_epic_spectra(self):
226+
def test_get_epic_spectra(self, tmp_cwd):
227227
_tarname = "tarfile.tar"
228228
_source_number = 83
229229
_instruments = ["M1", "M1_arf", "M1_bkg", "M1_rmf",

0 commit comments

Comments
 (0)