-
Notifications
You must be signed in to change notification settings - Fork 28
/
conftest.py
387 lines (307 loc) · 10.6 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import json
from pathlib import Path
from pytest import fixture
import os, os.path
from pytest import TempPathFactory
import cProfile
import pstats
import mock
import yaml
import re
# ==============================================================================
import crds
from crds.core import log, utils
from crds.core import config as crds_config
# ==============================================================================
HERE = os.path.abspath(os.path.dirname(__file__) or ".")
CRDS_DIR = os.path.abspath(os.path.dirname(crds.__file__))
RETENTION_COUNT=1
RETENTION_POLICY='none'
def pytest_addoption(parser):
parser.addoption(
"--test_data",
action="store",
dest="test_data",
default=os.path.abspath("test/data"),
help="Default pytest data path",
)
parser.addoption(
"--test_cache",
action="store",
dest="test_cache",
default=os.environ.get("CRDS_TESTING_CACHE", "/tmp/crds-cache-test"),
help="Default CRDS Test Cache",
)
parser.addoption(
"--default_cache",
action="store",
dest="default_cache",
default=os.environ.get("CRDS_PATH", "/tmp/crds-cache-default-test")
)
@fixture(scope='session')
def test_data(request):
return request.config.getoption("test_data")
@fixture(scope='session')
def test_cache(request):
return request.config.getoption("test_cache")
@fixture(scope='session')
def default_cache(request):
return request.config.getoption("default_cache")
@fixture(scope='session')
def test_mappath(test_cache):
return os.path.join(test_cache, "mappings")
@fixture(scope='session')
def crds_forwarded_url():
return "https://localhost:8001/"
@fixture(scope='function')
def crds_shared_group_cache():
return crds_config.get_crds_path()
@fixture(scope='session')
def test_temp_dir(request):
try:
tmp_path_factory = TempPathFactory(
request.config.option.basetemp,
RETENTION_COUNT,
RETENTION_POLICY,
trace=request.config.trace.get("tmpdir"),
_ispytest=True
)
except Exception: # pytest < 7.3
tmp_path_factory = TempPathFactory(
request.config.option.basetemp, trace=request.config.trace.get("tmpdir"), _ispytest=True
)
basepath = tmp_path_factory.getbasetemp()
return basepath
@fixture(scope='function')
def hst_data(test_data):
return f"{test_data}/hst"
@fixture(scope='function')
def jwst_data(test_data):
return f"{test_data}/jwst"
@fixture(scope='function')
def roman_data(test_data):
return f"{test_data}/roman"
# ==============================================================================
@fixture(scope='function')
def tmp_rc(test_temp_dir):
_tmprc = os.path.join(test_temp_dir, 'tmp_rc_submit_')
os.makedirs(_tmprc, exist_ok=True)
return _tmprc
@fixture(scope='function')
def submit_test_files(tmp_rc):
# Create empty test files in the temporary directory:
filenames = ['ipppssoot_ccd.fits', 'opppssoot_bia.fits']
tempfiles = [os.path.join(tmp_rc, x) for x in filenames]
for fpath in tempfiles:
with open(fpath, 'a'):
os.utime(fpath, None)
return tempfiles
@fixture(scope='function')
def mock_submit_form(tmp_rc, test_data):
# Create a file handle to use as a mockup of the urllib.request object:
mockup_form = os.path.join(tmp_rc, 'mocked_redcat_description.yml')
with open(os.path.join(test_data, "rc_description.yaml")) as yml:
form_description_yml = yaml.safe_load(yml)
with open(mockup_form, 'w') as f:
yaml.dump(form_description_yml)
return mockup_form
# ==============================================================================
class ConfigState:
def __init__(self, cache=None, url=None, clear_existing=True, observatory=None, mode=None):
self.cache = cache
self.url = url
self.clear_existing = clear_existing
self.observatory = observatory
self.mode = mode
self.old_state = None
self.new_state = None
def config_setup(self):
"""Reset the CRDS configuration state to support testing given the supplied parameters."""
log.set_test_mode()
self.old_state = crds_config.get_crds_state()
self.old_state["CRDS_CWD"] = os.getcwd()
if self.clear_existing:
crds_config.clear_crds_state()
self.new_state = dict(self.old_state)
# self.new_state["_CRDS_CACHE_READONLY"] = crds_config.get_cache_readonly()
self.new_state["CRDS_CWD"] = HERE
if self.url is not None:
self.new_state["CRDS_SERVER_URL"] = self.url
if self.cache is not None:
self.new_state["CRDS_PATH"] = self.cache
if self.observatory is not None:
self.new_state["CRDS_OBSERVATORY"] = self.observatory
if self.mode is not None:
self.new_state['CRDS_MODE'] = self.mode
crds_config.set_crds_state(self.new_state)
utils.clear_function_caches()
def cleanup(self):
"""Strictly speaking test cleanup is more than restoring CRDS state."""
crds_config.set_crds_state(self.old_state)
utils.clear_function_caches()
def reset_defaults(self):
"""Generic CRDS environment variables consistent across observatories.
Any kwargs passed into a ConfigState object will override these default values.
This reset is 'softer' than the crds built-in crds.config.clear_crds_state()."""
self.default_config = dict(
CRDS_PATH=os.environ.get("CRDS_PATH", "/tmp/crds-cache-default-test"),
CRDS_CONFIG_OFFSITE='1',
CRDS_READONLY_CACHE='0',
CRDS_REF_SUBDIR_MODE='None',
PASS_INVALID_VALUES='false',
CRDS_VERBOSITY='0',
CRDS_MODE='auto',
CRDS_CLIENT_RETRY_COUNT='3',
CRDS_CLIENT_RETRY_DELAY_SECONDS='20',
)
crds_config.set_crds_state(self.default_config)
@fixture(scope='function')
def default_shared_state(crds_shared_group_cache):
cfg = ConfigState(cache=crds_shared_group_cache)
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def hst_shared_cache_state(crds_shared_group_cache):
cfg = ConfigState(cache=crds_shared_group_cache, url="https://hst-crds.stsci.edu", observatory="hst")
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def hst_default_cache_state(default_cache):
cfg = ConfigState(cache=default_cache, mode='auto', url="https://hst-crds.stsci.edu", observatory="hst")
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def jwst_default_cache_state(default_cache):
cfg = ConfigState(cache=default_cache, mode='auto', url="https://jwst-crds.stsci.edu", observatory="jwst")
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture()
def hst_temp_cache_state(test_temp_dir):
cfg = ConfigState(
cache=str(test_temp_dir),
url="https://hst-crds.stsci.edu",
observatory="hst",
)
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def jwst_no_cache_state():
cfg = ConfigState(
cache=None,
url="https://jwst-crds.stsci.edu",
observatory="jwst",
mode='local')
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def jwst_shared_cache_state(crds_shared_group_cache):
cfg = ConfigState(
cache=crds_shared_group_cache,
url="https://jwst-crds.stsci.edu",
observatory="jwst")
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def jwst_serverless_state(crds_shared_group_cache):
cfg = ConfigState(
cache=crds_shared_group_cache,
url="https://jwst-crds-serverless.stsci.edu",
observatory="jwst"
)
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def hst_serverless_state(crds_shared_group_cache):
cfg = ConfigState(
cache=crds_shared_group_cache,
url="https://hst-serverless-mode.stsci.edu",
observatory="hst"
)
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture()
def hst_persistent_state(test_cache):
cfg = ConfigState(
cache=test_cache,
clear_existing=False,
observatory="hst",
)
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def roman_serverless_state(crds_shared_group_cache):
cfg = ConfigState(
cache=crds_shared_group_cache,
url="https://roman-crds-serverless.stsci.edu",
observatory="roman"
)
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def broken_state():
cfg = ConfigState(cache="/nowhere", url="https://server-is-out-of-town")
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def default_test_cache_state(test_cache):
cfg = ConfigState(cache=test_cache)
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def jwst_test_cache_state(test_cache):
cfg = ConfigState(cache=test_cache, observatory="jwst")
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def roman_test_cache_state(test_cache):
cfg = ConfigState(cache=test_cache, url="https://roman-serverless-mode.stsci.edu", observatory="roman")
cfg.config_setup()
yield cfg
cfg.cleanup()
@fixture(scope='function')
def tobs_test_cache_state(test_cache):
cfg = ConfigState(cache=test_cache, url="https://tobs-serverless-mode.stsci.edu", clear_existing=False)
cfg.config_setup()
yield cfg
cfg.cleanup()
# ==============================================================================
def run_and_profile(name, case, globs={}, locs={}):
"""Using `name` for a banner and divider, execute code string `case` in the
global namespace, both evaled printing result and under the profiler.
"""
utils.clear_function_caches()
log.divider()
log.divider(name + " example")
log.divider()
print(eval(case, globs, locs))
utils.clear_function_caches()
log.divider()
log.divider(name + " profile")
log.divider()
cProfile.run(case, "profile.stats")
stats = pstats.Stats('profile.stats')
stats.strip_dirs()
stats.sort_stats('cumulative')
stats.print_stats(100)
os.remove('profile.stats')
@fixture
def combined_spec(scope='session'):
return json.load(
open(Path(__file__).parent.parent / "crds" / "roman" / "specs" / "combined_specs.json", 'r'))
@fixture(scope='function')
def jwst_pmap_pattern():
return re.compile("jwst_[0-9]{4}.pmap")