Skip to content

BUGFIX: prevent gaia from querying server at import time #3344

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 15 additions & 18 deletions astroquery/esa/euclid/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,23 +605,20 @@
flag to display information about the process

"""
try:
sub_context = self.EUCLID_MESSAGES
conn_handler = self._TapPlus__getconnhandler()
response = conn_handler.execute_tapget(sub_context, verbose=verbose)
if response.status == 200:
if isinstance(response, Iterable):
for line in response:

try:
print(line.decode("utf-8").split('=', 1)[1])
except ValueError as e:
print(e)
except IndexError:
print("Archive down for maintenance")

except OSError:
print("Status messages could not be retrieved")
sub_context = self.EUCLID_MESSAGES
conn_handler = self._TapPlus__getconnhandler()
response = conn_handler.execute_tapget(sub_context, verbose=verbose)
if response.status == 200:
if isinstance(response, Iterable):
for line in response:

Check warning on line 613 in astroquery/esa/euclid/core.py

View check run for this annotation

Codecov / codecov/patch

astroquery/esa/euclid/core.py#L608-L613

Added lines #L608 - L613 were not covered by tests

try:
print(line.decode("utf-8").split('=', 1)[1])
except ValueError as e:
print(e)
except IndexError:
print("Archive down for maintenance")

Check warning on line 620 in astroquery/esa/euclid/core.py

View check run for this annotation

Codecov / codecov/patch

astroquery/esa/euclid/core.py#L615-L620

Added lines #L615 - L620 were not covered by tests


@staticmethod
def __set_dirs(output_file, observation_id):
Expand Down Expand Up @@ -1443,4 +1440,4 @@
return job.get_results()


Euclid = EuclidClass()
Euclid = EuclidClass(show_server_messages=False)
14 changes: 7 additions & 7 deletions astroquery/esa/euclid/tests/test_euclidtap.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,25 +125,25 @@ def column_attrs():


def test_load_environments():
tap = EuclidClass(environment='PDR')
tap = EuclidClass(environment='PDR', show_server_messages=False)

assert tap is not None

tap = EuclidClass(environment='IDR')
tap = EuclidClass(environment='IDR', show_server_messages=False)

assert tap is not None

tap = EuclidClass(environment='OTF')
tap = EuclidClass(environment='OTF', show_server_messages=False)

assert tap is not None

tap = EuclidClass(environment='REG')
tap = EuclidClass(environment='REG', show_server_messages=False)

assert tap is not None

environment = 'WRONG'
try:
tap = EuclidClass(environment='WRONG')
tap = EuclidClass(environment='WRONG', show_server_messages=False)
except Exception as e:
assert str(e).startswith(f"Invalid environment {environment}. Valid values: {list(conf.ENVIRONMENTS.keys())}")

Expand Down Expand Up @@ -637,7 +637,7 @@ def test_get_product_list_by_tile_index():


def test_get_product_list_errors():
tap = EuclidClass()
tap = EuclidClass(show_server_messages=False)

with pytest.raises(ValueError, match="Missing required argument: 'product_type'"):
tap.get_product_list(observation_id='13', product_type=None)
Expand Down Expand Up @@ -1105,7 +1105,7 @@ def test_get_scientific_data_product_list():


def test_get_scientific_data_product_list_exceptions():
eculid = EuclidClass()
eculid = EuclidClass(show_server_messages=False)

with pytest.raises(ValueError, match="Include a valid parameter to retrieve a LE3 product."):
eculid.get_scientific_product_list(observation_id=None, tile_index=None, category=None, group=None,
Expand Down
19 changes: 8 additions & 11 deletions astroquery/esa/hubble/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -940,16 +940,13 @@
the status of eHST TAP
"""

try:
subContext = conf.EHST_MESSAGES
connHandler = self._tap._TapPlus__getconnhandler()
response = connHandler.execute_tapget(subContext, verbose=False)
if response.status == 200:
for line in response:
string_message = line.decode("utf-8")
print(string_message[string_message.index('=') + 1:])
except OSError:
print("Status messages could not be retrieved")
subContext = conf.EHST_MESSAGES
connHandler = self._tap._TapPlus__getconnhandler()
response = connHandler.execute_tapget(subContext, verbose=False)
if response.status == 200:
for line in response:
string_message = line.decode("utf-8")
print(string_message[string_message.index('=') + 1:])

Check warning on line 949 in astroquery/esa/hubble/core.py

View check run for this annotation

Codecov / codecov/patch

astroquery/esa/hubble/core.py#L947-L949

Added lines #L947 - L949 were not covered by tests

def get_columns(self, table_name, *, only_names=True, verbose=False):
"""Get the available columns for a table in EHST TAP service
Expand Down Expand Up @@ -1061,4 +1058,4 @@
return full_path


ESAHubble = ESAHubbleClass()
ESAHubble = ESAHubbleClass(show_messages=False)
3 changes: 2 additions & 1 deletion astroquery/esa/hubble/tests/test_esa_hubble_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
from astroquery.esa.hubble import ESAHubble
from astropy import coordinates

esa_hubble = ESAHubble()
# don't show messages during test: it creates a remote call
esa_hubble = ESAHubble(show_messages=False)


def data_path(filename):
Expand Down
19 changes: 8 additions & 11 deletions astroquery/esa/jwst/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,16 +694,13 @@ def get_status_messages(self):
the status of JWST TAP
"""

try:
subContext = conf.JWST_MESSAGES
connHandler = self.__jwsttap._TapPlus__getconnhandler()
response = connHandler.execute_tapget(subContext, verbose=False)
if response.status == 200:
for line in response:
string_message = line.decode("utf-8")
print(string_message[string_message.index('=') + 1:])
except OSError:
print("Status messages could not be retrieved")
subContext = conf.JWST_MESSAGES
connHandler = self.__jwsttap._TapPlus__getconnhandler()
response = connHandler.execute_tapget(subContext, verbose=False)
if response.status == 200:
for line in response:
string_message = line.decode("utf-8")
print(string_message[string_message.index('=') + 1:])

def get_product_list(self, *, observation_id=None,
cal_level="ALL",
Expand Down Expand Up @@ -1275,4 +1272,4 @@ def get_decoded_string(str):
return str


Jwst = JwstClass()
Jwst = JwstClass(show_messages=False)
36 changes: 16 additions & 20 deletions astroquery/gaia/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1168,23 +1168,19 @@
"""Retrieve the messages to inform users about
the status of Gaia TAP
"""
try:
sub_context = self.GAIA_MESSAGES
conn_handler = self._TapPlus__getconnhandler()
response = conn_handler.execute_tapget(sub_context, verbose=False)
if response.status == 200:
if isinstance(response, Iterable):
for line in response:

try:
print(line.decode("utf-8").split('=', 1)[1])
except ValueError as e:
print(e)
except IndexError:
print("Archive down for maintenance")

except OSError:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This exception catching is a particular problem: it hid from the tests that there is a remote query being performed, since pytest-remotedata raises an OSError

print("Status messages could not be retrieved")


Gaia = GaiaClass()
sub_context = self.GAIA_MESSAGES
conn_handler = self._TapPlus__getconnhandler()
response = conn_handler.execute_tapget(sub_context, verbose=False)
if response.status == 200:
if isinstance(response, Iterable):
for line in response:

try:
print(line.decode("utf-8").split('=', 1)[1])
except ValueError as e:
print(e)
except IndexError:
print("Archive down for maintenance")

Check warning on line 1183 in astroquery/gaia/core.py

View check run for this annotation

Codecov / codecov/patch

astroquery/gaia/core.py#L1180-L1183

Added lines #L1180 - L1183 were not covered by tests


Gaia = GaiaClass(show_server_messages=False)
101 changes: 101 additions & 0 deletions astroquery/tests/test_imports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import sys
import importlib
import pytest
import socket
from unittest.mock import patch
from pytest_remotedata.disable_internet import no_internet
from pytest_remotedata.disable_internet import INTERNET_OFF

# List of all astroquery modules to test
ASTROQUERY_MODULES = [
'astroquery.alma',
'astroquery.astrometry_net',
'astroquery.besancon',
'astroquery.cadc',
'astroquery.cosmosim',
'astroquery.esa',
'astroquery.esasky',
'astroquery.eso',
'astroquery.exoplanet_orbit_database',
'astroquery.fermi',
'astroquery.gaia',
'astroquery.gama',
'astroquery.gemini',
'astroquery.heasarc',
'astroquery.hitran',
'astroquery.ipac.irsa.ibe',
'astroquery.hips2fits',
'astroquery.image_cutouts',
'astroquery.imcce',
'astroquery.ipac',
'astroquery.ipac.irsa',
'astroquery.ipac.irsa.irsa_dust',
'astroquery.ipac.ned',
'astroquery.ipac.nexsci.nasa_exoplanet_archive',
'astroquery.jplhorizons',
'astroquery.jplsbdb',
'astroquery.jplspec',
'astroquery.linelists',
'astroquery.magpis',
'astroquery.mast',
'astroquery.mocserver',
'astroquery.mpc',
'astroquery.nasa_ads',
'astroquery.nist',
'astroquery.nvas',
'astroquery.oac',
'astroquery.ogle',
'astroquery.open_exoplanet_catalogue',
'astroquery.sdss',
'astroquery.simbad',
'astroquery.skyview',
'astroquery.solarsystem',
'astroquery.splatalogue',
'astroquery.svo_fps',
'astroquery.utils',
'astroquery.vamdc',
'astroquery.vo_conesearch',
'astroquery.vizier',
'astroquery.vsa',
'astroquery.wfau',
'astroquery.xmatch',
]

class SocketTracker:
def __init__(self):
self.socket_attempts = []

def __call__(self, *args, **kwargs):
# Record the attempt
self.socket_attempts.append((args, kwargs))
# Raise a clear error to indicate socket creation
raise RuntimeError("Socket creation attempted during import")


@pytest.mark.parametrize("module_name", ASTROQUERY_MODULES)
def test_no_http_calls_during_import(module_name):
"""
Test that importing astroquery modules does not make any remote calls.

This is a regression test for 3343, and the error that raises is not
properly caught by the framework below, but that's an unrelated issue.

This is the error shown if Gaia(show_server_messages=True) is called:
```
E TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
```
"""
with no_internet():
if module_name in sys.modules:
del sys.modules[module_name]

tracker = SocketTracker()
with patch('socket.socket', tracker):
importlib.import_module(module_name)

assert not tracker.socket_attempts, (
f"Module {module_name} attempted to create {len(tracker.socket_attempts)} "
f"socket(s) during import:\n" +
"\n".join(f" - {args} {kwargs}" for args, kwargs in tracker.socket_attempts)
)
Loading