Skip to content

Commit 1482981

Browse files
committed
Ensuring we don't override existing sessions
1 parent 7a4a7bf commit 1482981

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

astroquery/query.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -185,11 +185,19 @@ class BaseVOQuery:
185185
"""
186186
def __init__(self):
187187
super().__init__()
188-
self._session = requests.Session()
189-
self._session.headers['User-Agent'] = (
190-
f"astroquery/{version.version} pyVO/{pyvo.__version__} Python/{platform.python_version()} "
191-
f"({platform.system()}) "
192-
f"{self._session.headers['User-Agent']}")
188+
if not hasattr(self, '_session'):
189+
# We don't want to override another, e.g. already authenticated session from another baseclass
190+
self._session = requests.Session()
191+
192+
user_agents = self._session.headers['User-Agent'].split()
193+
if 'astroquery' in user_agents[0]:
194+
if 'pyVO' not in user_agents[1]:
195+
user_agents[0] = f"astroquery/{version.version} pyVO/{pyvo.__version__}"
196+
else:
197+
user_agents = [f"astroquery/{version.version} pyVO/{pyvo.__version__} "
198+
f"Python/{platform.python_version()} ({platform.system()})"] + user_agents
199+
200+
self._session.headers['User-Agent'] = " ".join(user_agents)
193201

194202
self.name = self.__class__.__name__.split("Class")[0]
195203

astroquery/tests/test_query.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Licensed under a 3-clause BSD style license - see LICENSE.rst
2+
from astroquery.query import BaseQuery, BaseVOQuery
3+
4+
5+
class with_VO(BaseVOQuery, BaseQuery):
6+
pass
7+
8+
9+
class without_VO(BaseQuery):
10+
pass
11+
12+
13+
class only_VO(BaseVOQuery):
14+
pass
15+
16+
17+
def test_session_VO_header():
18+
test_instance = with_VO()
19+
user_agent = test_instance._session.headers['User-Agent']
20+
assert 'astroquery' in user_agent
21+
assert 'pyVO' in user_agent
22+
assert user_agent.count('astroquery') == 1
23+
24+
25+
def test_session_nonVO_header():
26+
test_instance = without_VO()
27+
user_agent = test_instance._session.headers['User-Agent']
28+
assert 'astroquery' in user_agent
29+
assert 'pyVO' not in user_agent
30+
assert user_agent.count('astroquery') == 1
31+
32+
33+
def test_session_hooks():
34+
# Test that we don't override the session in the BaseVOQuery
35+
test_instance = with_VO()
36+
assert len(test_instance._session.hooks['response']) > 0
37+
38+
test_VO_instance = only_VO()
39+
assert len(test_VO_instance._session.hooks['response']) == 0

0 commit comments

Comments
 (0)