-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathconftest.py
More file actions
547 lines (454 loc) · 16.4 KB
/
Copy pathconftest.py
File metadata and controls
547 lines (454 loc) · 16.4 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import json
from pathlib import Path
from pytest import fixture
import os, os.path
from pytest import TempPathFactory
import cProfile
import pstats
import yaml
import re
from moto import mock_aws
import boto3
# ==============================================================================
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, **kwargs):
"""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
for k, v in kwargs.items():
self.new_state[k] = v
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_S3_ENABLED='0',
CRDS_DOWNLOAD_PLUGIN="",
CRDS_DOWNLOAD_MODE="auto",
CRDS_MAPPING_URI="",
CRDS_REFERENCE_URI="",
CRDS_CONFIG_URI="",
)
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()
roman_aws_config_kwargs = dict(
CRDS_S3_ENABLED='1',
CRDS_S3_RETURN_URI='0',
CRDS_DOWNLOAD_PLUGIN="crds_s3_get \${FILENAME} -d \${OUTPUT_PATH} -s \${FILE_SIZE} -c \${FILE_SHA1SUM}",
CRDS_DOWNLOAD_MODE="plugin",
CRDS_MAPPING_URI=f"s3://stpubdata-mock/roman/crds/mappings/roman",
CRDS_REFERENCE_URI=f"s3://stpubdata-mock/roman/crds/references/roman",
CRDS_CONFIG_URI=f"s3://stpubdata-mock/roman/crds/config/roman",
)
@fixture(scope='function')
def roman_s3_cache_state(default_cache):
cfg = ConfigState(
cache=default_cache,
mode='s3',
url="https://roman-crds-serverless.stsci.edu",
observatory="roman",
)
cfg.config_setup(**roman_aws_config_kwargs)
yield cfg
cfg.cleanup()
@fixture(scope='function')
def roman_s3_test_cache_state(test_cache):
cfg = ConfigState(
cache=test_cache,
mode='s3',
url="https://roman-crds-serverless.stsci.edu",
observatory="roman",
)
cfg.config_setup(**roman_aws_config_kwargs)
yield cfg
cfg.cleanup()
@fixture()
def roman_temp_cache_state(test_temp_dir):
cfg = ConfigState(
cache=str(test_temp_dir),
url="https://roman-crds-serverless.stsci.edu",
observatory="roman",
)
cfg.config_setup(**roman_aws_config_kwargs)
yield cfg
cfg.cleanup()
@fixture(scope="function")
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ["AWS_ACCESS_KEY_ID"] = "testing"
os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
os.environ["AWS_SECURITY_TOKEN"] = "testing"
os.environ["AWS_SESSION_TOKEN"] = "testing"
os.environ["AWS_DEFAULT_REGION"] = "us-east-1"
@fixture
def moto_server():
from moto.server import ThreadedMotoServer
server = ThreadedMotoServer(port=5000)
server.start()
yield server
server.stop()
@fixture(scope="function")
def roman_s3_bucket(roman_s3_cache_state, roman_data, aws_credentials, moto_server):
"""
Return a mocked S3 bucket populated with mappings
The server_config file is from roman test data and is fixed at roman_0055.pmap as "latest".
"""
# setup: upload S3 objects to the mocked S3 bucket
bucket_name = "stpubdata-mock"
pfx = "roman/crds"
mappings = [
'roman_0055.pmap',
'roman_wfi_0053.imap',
'roman_wfi_absflux_0001.rmap',
'roman_wfi_abvegaoffset_0002.rmap',
'roman_wfi_apcorr_0003.rmap',
'roman_wfi_area_0002.rmap',
'roman_wfi_dark_0007.rmap',
'roman_wfi_darkdecaysignal_0002.rmap',
'roman_wfi_detectorstatus_0002.rmap',
'roman_wfi_distortion_0002.rmap',
'roman_wfi_dustmap_0003.rmap',
'roman_wfi_epsf_0004.rmap',
'roman_wfi_etc_0002.rmap',
'roman_wfi_flat_0006.rmap',
'roman_wfi_gain_0003.rmap',
'roman_wfi_integralnonlinearity_0002.rmap',
'roman_wfi_inverselinearity_0005.rmap',
'roman_wfi_ipc_0003.rmap',
'roman_wfi_linearity_0005.rmap',
'roman_wfi_mask_0003.rmap',
'roman_wfi_matable_0004.rmap',
'roman_wfi_optmodel_0001.rmap',
'roman_wfi_photom_0004.rmap',
'roman_wfi_readnoise_0005.rmap',
'roman_wfi_refpix_0003.rmap',
'roman_wfi_relflux_0001.rmap',
'roman_wfi_saturation_0003.rmap',
'roman_wfi_sflat_0001.rmap',
'roman_wfi_skycells_0002.rmap',
'roman_wfi_specpsf_0001.rmap'
]
with mock_aws():
s3 = boto3.client("s3", endpoint_url="http://127.0.0.1:5000")
s3.create_bucket(Bucket=bucket_name)
for mapping in mappings:
fpath = os.path.join(crds_config.get_crds_path(), "mappings/roman", mapping)
with open(fpath, 'rb') as f:
s3.put_object(Bucket=bucket_name, Key=f"{pfx}/mappings/roman/{mapping}", Body=f.read())
# sync config
cfg_path = os.path.join(roman_data, "server_config")
with open(cfg_path, 'rb') as f:
s3.put_object(Bucket=bucket_name, Key=f"{pfx}/config/roman/server_config", Body=f.read())
yield bucket_name
@fixture(scope="function")
def roman_s3_test_bucket(roman_s3_test_cache_state, roman_data, aws_credentials, moto_server):
"""
Return a mocked S3 bucket populated with mappings
Uses contents of crds-cache-test to populate the mocked s3 bucket.
"""
# setup: upload S3 objects to the mocked S3 bucket
bucket_name = "stpubdata-mock"
pfx = "roman/crds"
mappings = os.listdir(os.path.join(roman_s3_test_cache_state.cache, "mappings/roman"))
refs = os.listdir(os.path.join(roman_s3_test_cache_state.cache, "references/roman"))
# cfg = os.path.join(roman_s3_test_cache_state.cache, "config/roman/server_config")
# make sure we get the updated config - test cache isn't getting updated version
cfg = os.path.join(roman_data, "test_cache_config/server_config")
with mock_aws():
s3 = boto3.client("s3", endpoint_url="http://127.0.0.1:5000")
s3.create_bucket(Bucket=bucket_name)
for mapping in mappings:
fpath = crds_config.locate_file(mapping, "roman")
with open(fpath, 'rb') as f:
s3.put_object(Bucket=bucket_name, Key=f"{pfx}/mappings/roman/{mapping}", Body=f.read())
for ref in refs:
fpath = crds_config.locate_file(ref, "roman")
with open(fpath, 'rb') as f:
s3.put_object(Bucket=bucket_name, Key=f"{pfx}/references/roman/{ref}", Body=f.read())
## sync config
with open(cfg, 'rb') as f:
s3.put_object(Bucket=bucket_name, Key=f"{pfx}/config/roman/server_config", Body=f.read())
yield bucket_name
# ==============================================================================
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")
@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()