-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtest_datastore.py
2191 lines (1804 loc) · 86.8 KB
/
test_datastore.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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of daf_butler.
#
# Developed for the LSST Data Management System.
# This product includes software developed by the LSST Project
# (http://www.lsst.org).
# See the COPYRIGHT file at the top-level directory of this distribution
# for details of code ownership.
#
# This software is dual licensed under the GNU General Public License and also
# under a 3-clause BSD license. Recipients may choose which of these licenses
# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
# respectively. If you choose the GPL option then the following text applies
# (but note that there is still no warranty even if you opt for BSD instead):
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
import contextlib
import os
import pickle
import shutil
import tempfile
import time
import unittest
import unittest.mock
import uuid
from collections.abc import Callable, Iterator
from typing import Any, cast
import yaml
import lsst.utils.tests
from lsst.daf.butler import (
Config,
DataCoordinate,
DatasetIdGenEnum,
DatasetRef,
DatasetType,
DatasetTypeNotSupportedError,
Datastore,
DimensionUniverse,
FileDataset,
StorageClass,
StorageClassFactory,
)
from lsst.daf.butler.datastore import DatasetRefURIs, DatastoreConfig, DatastoreValidationError, NullDatastore
from lsst.daf.butler.datastore.cache_manager import (
DatastoreCacheManager,
DatastoreCacheManagerConfig,
DatastoreDisabledCacheManager,
)
from lsst.daf.butler.datastore.stored_file_info import StoredFileInfo
from lsst.daf.butler.formatters.yaml import YamlFormatter
from lsst.daf.butler.tests import (
BadNoWriteFormatter,
BadWriteFormatter,
DatasetTestHelper,
DatastoreTestHelper,
DummyRegistry,
MetricsExample,
MetricsExampleDataclass,
MetricsExampleModel,
)
from lsst.daf.butler.tests.dict_convertible_model import DictConvertibleModel
from lsst.daf.butler.tests.utils import TestCaseMixin
from lsst.resources import ResourcePath
from lsst.utils import doImport
TESTDIR = os.path.dirname(__file__)
def makeExampleMetrics(use_none: bool = False) -> MetricsExample:
"""Make example dataset that can be stored in butler."""
if use_none:
array = None
else:
array = [563, 234, 456.7, 105, 2054, -1045]
return MetricsExample(
{"AM1": 5.2, "AM2": 30.6},
{"a": [1, 2, 3], "b": {"blue": 5, "red": "green"}},
array,
)
class TransactionTestError(Exception):
"""Specific error for transactions, to prevent misdiagnosing
that might otherwise occur when a standard exception is used.
"""
pass
class DatastoreTestsBase(DatasetTestHelper, DatastoreTestHelper, TestCaseMixin):
"""Support routines for datastore testing"""
root: str | None = None
universe: DimensionUniverse
storageClassFactory: StorageClassFactory
@classmethod
def setUpClass(cls) -> None:
# Storage Classes are fixed for all datastores in these tests
scConfigFile = os.path.join(TESTDIR, "config/basic/storageClasses.yaml")
cls.storageClassFactory = StorageClassFactory()
cls.storageClassFactory.addFromConfig(scConfigFile)
# Read the Datastore config so we can get the class
# information (since we should not assume the constructor
# name here, but rely on the configuration file itself)
datastoreConfig = DatastoreConfig(cls.configFile)
cls.datastoreType = cast(type[Datastore], doImport(datastoreConfig["cls"]))
cls.universe = DimensionUniverse()
def setUp(self) -> None:
self.setUpDatastoreTests(DummyRegistry, DatastoreConfig)
def tearDown(self) -> None:
if self.root is not None and os.path.exists(self.root):
shutil.rmtree(self.root, ignore_errors=True)
class DatastoreTests(DatastoreTestsBase):
"""Some basic tests of a simple datastore."""
hasUnsupportedPut = True
rootKeys: tuple[str, ...] | None = None
isEphemeral: bool = False
validationCanFail: bool = False
def testConfigRoot(self) -> None:
full = DatastoreConfig(self.configFile)
config = DatastoreConfig(self.configFile, mergeDefaults=False)
newroot = "/random/location"
self.datastoreType.setConfigRoot(newroot, config, full)
if self.rootKeys:
for k in self.rootKeys:
self.assertIn(newroot, config[k])
def testConstructor(self) -> None:
datastore = self.makeDatastore()
self.assertIsNotNone(datastore)
self.assertIs(datastore.isEphemeral, self.isEphemeral)
def testConfigurationValidation(self) -> None:
datastore = self.makeDatastore()
sc = self.storageClassFactory.getStorageClass("ThingOne")
datastore.validateConfiguration([sc])
sc2 = self.storageClassFactory.getStorageClass("ThingTwo")
if self.validationCanFail:
with self.assertRaises(DatastoreValidationError):
datastore.validateConfiguration([sc2], logFailures=True)
dimensions = self.universe.conform(("visit", "physical_filter"))
dataId = {
"instrument": "dummy",
"visit": 52,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
ref = self.makeDatasetRef("metric", dimensions, sc, dataId)
datastore.validateConfiguration([ref])
def testParameterValidation(self) -> None:
"""Check that parameters are validated"""
sc = self.storageClassFactory.getStorageClass("ThingOne")
dimensions = self.universe.conform(("visit", "physical_filter"))
dataId = {
"instrument": "dummy",
"visit": 52,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
ref = self.makeDatasetRef("metric", dimensions, sc, dataId)
datastore = self.makeDatastore()
data = {1: 2, 3: 4}
datastore.put(data, ref)
newdata = datastore.get(ref)
self.assertEqual(data, newdata)
with self.assertRaises(KeyError):
newdata = datastore.get(ref, parameters={"missing": 5})
def testBasicPutGet(self) -> None:
metrics = makeExampleMetrics()
datastore = self.makeDatastore()
# Create multiple storage classes for testing different formulations
storageClasses = [
self.storageClassFactory.getStorageClass(sc)
for sc in ("StructuredData", "StructuredDataJson", "StructuredDataPickle")
]
dimensions = self.universe.conform(("visit", "physical_filter"))
dataId = {
"instrument": "dummy",
"visit": 52,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
dataId2 = {
"instrument": "dummy",
"visit": 53,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
for sc in storageClasses:
ref = self.makeDatasetRef("metric", dimensions, sc, dataId)
ref2 = self.makeDatasetRef("metric", dimensions, sc, dataId2)
# Make sure that using getManyURIs without predicting before the
# dataset has been put raises.
with self.assertRaises(FileNotFoundError):
datastore.getManyURIs([ref], predict=False)
# Make sure that using getManyURIs with predicting before the
# dataset has been put predicts the URI.
uris = datastore.getManyURIs([ref, ref2], predict=True)
self.assertIn("52", uris[ref].primaryURI.geturl())
self.assertIn("#predicted", uris[ref].primaryURI.geturl())
self.assertIn("53", uris[ref2].primaryURI.geturl())
self.assertIn("#predicted", uris[ref2].primaryURI.geturl())
datastore.put(metrics, ref)
# Does it exist?
self.assertTrue(datastore.exists(ref))
self.assertTrue(datastore.knows(ref))
multi = datastore.knows_these([ref])
self.assertTrue(multi[ref])
multi = datastore.mexists([ref, ref2])
self.assertTrue(multi[ref])
self.assertFalse(multi[ref2])
# Get
metricsOut = datastore.get(ref, parameters=None)
self.assertEqual(metrics, metricsOut)
uri = datastore.getURI(ref)
self.assertEqual(uri.scheme, self.uriScheme)
uris = datastore.getManyURIs([ref])
self.assertEqual(len(uris), 1)
ref, uri = uris.popitem()
self.assertTrue(uri.primaryURI.exists())
self.assertFalse(uri.componentURIs)
# Get a component -- we need to construct new refs for them
# with derived storage classes but with parent ID
for comp in ("data", "output"):
compRef = ref.makeComponentRef(comp)
output = datastore.get(compRef)
self.assertEqual(output, getattr(metricsOut, comp))
uri = datastore.getURI(compRef)
self.assertEqual(uri.scheme, self.uriScheme)
uris = datastore.getManyURIs([compRef])
self.assertEqual(len(uris), 1)
storageClass = sc
# Check that we can put a metric with None in a component and
# get it back as None
metricsNone = makeExampleMetrics(use_none=True)
dataIdNone = {
"instrument": "dummy",
"visit": 54,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
refNone = self.makeDatasetRef("metric", dimensions, sc, dataIdNone)
datastore.put(metricsNone, refNone)
comp = "data"
for comp in ("data", "output"):
compRef = refNone.makeComponentRef(comp)
output = datastore.get(compRef)
self.assertEqual(output, getattr(metricsNone, comp))
# Check that a put fails if the dataset type is not supported
if self.hasUnsupportedPut:
sc = StorageClass("UnsupportedSC", pytype=type(metrics))
ref = self.makeDatasetRef("unsupportedType", dimensions, sc, dataId)
with self.assertRaises(DatasetTypeNotSupportedError):
datastore.put(metrics, ref)
# These should raise
ref = self.makeDatasetRef("metrics", dimensions, storageClass, dataId)
with self.assertRaises(FileNotFoundError):
# non-existing file
datastore.get(ref)
# Get a URI from it
uri = datastore.getURI(ref, predict=True)
self.assertEqual(uri.scheme, self.uriScheme)
with self.assertRaises(FileNotFoundError):
datastore.getURI(ref)
def testTrustGetRequest(self) -> None:
"""Check that we can get datasets that registry knows nothing about."""
datastore = self.makeDatastore()
# Skip test if the attribute is not defined
if not hasattr(datastore, "trustGetRequest"):
return
metrics = makeExampleMetrics()
i = 0
for sc_name in ("StructuredDataNoComponents", "StructuredData", "StructuredComposite"):
i += 1
datasetTypeName = f"test_metric{i}" # Different dataset type name each time.
if sc_name == "StructuredComposite":
disassembled = True
else:
disassembled = False
# Start datastore in default configuration of using registry
datastore.trustGetRequest = False
# Create multiple storage classes for testing with or without
# disassembly
sc = self.storageClassFactory.getStorageClass(sc_name)
dimensions = self.universe.conform(("visit", "physical_filter"))
dataId = {
"instrument": "dummy",
"visit": 52 + i,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
ref = self.makeDatasetRef(datasetTypeName, dimensions, sc, dataId)
datastore.put(metrics, ref)
# Does it exist?
self.assertTrue(datastore.exists(ref))
self.assertTrue(datastore.knows(ref))
multi = datastore.knows_these([ref])
self.assertTrue(multi[ref])
multi = datastore.mexists([ref])
self.assertTrue(multi[ref])
# Get
metricsOut = datastore.get(ref)
self.assertEqual(metrics, metricsOut)
# Get the URI(s)
primaryURI, componentURIs = datastore.getURIs(ref)
if disassembled:
self.assertIsNone(primaryURI)
self.assertEqual(len(componentURIs), 3)
else:
self.assertIn(datasetTypeName, primaryURI.path)
self.assertFalse(componentURIs)
# Delete registry entry so now we are trusting
datastore.removeStoredItemInfo(ref)
# Now stop trusting and check that things break
datastore.trustGetRequest = False
# Does it exist?
self.assertFalse(datastore.exists(ref))
self.assertFalse(datastore.knows(ref))
multi = datastore.knows_these([ref])
self.assertFalse(multi[ref])
multi = datastore.mexists([ref])
self.assertFalse(multi[ref])
with self.assertRaises(FileNotFoundError):
datastore.get(ref)
if sc_name != "StructuredDataNoComponents":
with self.assertRaises(FileNotFoundError):
datastore.get(ref.makeComponentRef("data"))
# URI should fail unless we ask for prediction
with self.assertRaises(FileNotFoundError):
datastore.getURIs(ref)
predicted_primary, predicted_disassembled = datastore.getURIs(ref, predict=True)
if disassembled:
self.assertIsNone(predicted_primary)
self.assertEqual(len(predicted_disassembled), 3)
for uri in predicted_disassembled.values():
self.assertEqual(uri.fragment, "predicted")
self.assertIn(datasetTypeName, uri.path)
else:
self.assertIn(datasetTypeName, predicted_primary.path)
self.assertFalse(predicted_disassembled)
self.assertEqual(predicted_primary.fragment, "predicted")
# Now enable registry-free trusting mode
datastore.trustGetRequest = True
# Try again to get it
metricsOut = datastore.get(ref)
self.assertEqual(metricsOut, metrics)
# Does it exist?
self.assertTrue(datastore.exists(ref))
# Get a component
if sc_name != "StructuredDataNoComponents":
comp = "data"
compRef = ref.makeComponentRef(comp)
output = datastore.get(compRef)
self.assertEqual(output, getattr(metrics, comp))
# Get the URI -- if we trust this should work even without
# enabling prediction.
primaryURI2, componentURIs2 = datastore.getURIs(ref)
self.assertEqual(primaryURI2, primaryURI)
self.assertEqual(componentURIs2, componentURIs)
# Check for compatible storage class.
if sc_name in ("StructuredDataNoComponents", "StructuredData"):
# Make new dataset ref with compatible storage class.
ref_comp = ref.overrideStorageClass("StructuredDataDictJson")
# Without `set_retrieve_dataset_type_method` it will fail to
# find correct file.
self.assertFalse(datastore.exists(ref_comp))
with self.assertRaises(FileNotFoundError):
datastore.get(ref_comp)
with self.assertRaises(FileNotFoundError):
datastore.get(ref, storageClass="StructuredDataDictJson")
# Need a special method to generate stored dataset type.
def _stored_dataset_type(name: str, ref: DatasetRef = ref) -> DatasetType:
if name == ref.datasetType.name:
return ref.datasetType
raise ValueError(f"Unexpected dataset type name {ref.datasetType.name}")
datastore.set_retrieve_dataset_type_method(_stored_dataset_type)
# Storage class override with original dataset ref.
metrics_as_dict = datastore.get(ref, storageClass="StructuredDataDictJson")
self.assertIsInstance(metrics_as_dict, dict)
# get() should return a dict now.
metrics_as_dict = datastore.get(ref_comp)
self.assertIsInstance(metrics_as_dict, dict)
# exists() should work as well.
self.assertTrue(datastore.exists(ref_comp))
datastore.set_retrieve_dataset_type_method(None)
def testDisassembly(self) -> None:
"""Test disassembly within datastore."""
metrics = makeExampleMetrics()
if self.isEphemeral:
# in-memory datastore does not disassemble
return
# Create multiple storage classes for testing different formulations
# of composites. One of these will not disassemble to provide
# a reference.
storageClasses = [
self.storageClassFactory.getStorageClass(sc)
for sc in (
"StructuredComposite",
"StructuredCompositeTestA",
"StructuredCompositeTestB",
"StructuredCompositeReadComp",
"StructuredData", # No disassembly
"StructuredCompositeReadCompNoDisassembly",
)
]
# Create the test datastore
datastore = self.makeDatastore()
# Dummy dataId
dimensions = self.universe.conform(("visit", "physical_filter"))
dataId = {"instrument": "dummy", "visit": 428, "physical_filter": "R"}
for i, sc in enumerate(storageClasses):
with self.subTest(storageClass=sc.name):
# Create a different dataset type each time round
# so that a test failure in this subtest does not trigger
# a cascade of tests because of file clashes
ref = self.makeDatasetRef(f"metric_comp_{i}", dimensions, sc, dataId)
disassembled = sc.name not in {"StructuredData", "StructuredCompositeReadCompNoDisassembly"}
datastore.put(metrics, ref)
baseURI, compURIs = datastore.getURIs(ref)
if disassembled:
self.assertIsNone(baseURI)
self.assertEqual(set(compURIs), {"data", "output", "summary"})
else:
self.assertIsNotNone(baseURI)
self.assertEqual(compURIs, {})
metrics_get = datastore.get(ref)
self.assertEqual(metrics_get, metrics)
# Retrieve the composite with read parameter
stop = 4
metrics_get = datastore.get(ref, parameters={"slice": slice(stop)})
self.assertEqual(metrics_get.summary, metrics.summary)
self.assertEqual(metrics_get.output, metrics.output)
self.assertEqual(metrics_get.data, metrics.data[:stop])
# Retrieve a component
data = datastore.get(ref.makeComponentRef("data"))
self.assertEqual(data, metrics.data)
# On supported storage classes attempt to access a read
# only component
if "ReadComp" in sc.name:
cRef = ref.makeComponentRef("counter")
counter = datastore.get(cRef)
self.assertEqual(counter, len(metrics.data))
counter = datastore.get(cRef, parameters={"slice": slice(stop)})
self.assertEqual(counter, stop)
datastore.remove(ref)
def prepDeleteTest(self, n_refs: int = 1) -> tuple[Datastore, tuple[DatasetRef, ...]]:
metrics = makeExampleMetrics()
datastore = self.makeDatastore()
# Put
dimensions = self.universe.conform(("visit", "physical_filter"))
sc = self.storageClassFactory.getStorageClass("StructuredData")
refs = []
for i in range(n_refs):
dataId = {
"instrument": "dummy",
"visit": 638 + i,
"physical_filter": "U",
"band": "u",
"day_obs": 20250101,
}
ref = self.makeDatasetRef("metric", dimensions, sc, dataId)
datastore.put(metrics, ref)
# Does it exist?
self.assertTrue(datastore.exists(ref))
# Get
metricsOut = datastore.get(ref)
self.assertEqual(metrics, metricsOut)
refs.append(ref)
return datastore, *refs
def testRemove(self) -> None:
datastore, ref = self.prepDeleteTest()
# Remove
datastore.remove(ref)
# Does it exist?
self.assertFalse(datastore.exists(ref))
# Do we now get a predicted URI?
uri = datastore.getURI(ref, predict=True)
self.assertEqual(uri.fragment, "predicted")
# Get should now fail
with self.assertRaises(FileNotFoundError):
datastore.get(ref)
# Can only delete once
with self.assertRaises(FileNotFoundError):
datastore.remove(ref)
def testForget(self) -> None:
datastore, ref = self.prepDeleteTest()
# Remove
datastore.forget([ref])
# Does it exist (as far as we know)?
self.assertFalse(datastore.exists(ref))
# Do we now get a predicted URI?
uri = datastore.getURI(ref, predict=True)
self.assertEqual(uri.fragment, "predicted")
# Get should now fail
with self.assertRaises(FileNotFoundError):
datastore.get(ref)
# Forgetting again is a silent no-op
datastore.forget([ref])
# Predicted URI should still point to the file.
self.assertTrue(uri.exists())
def testTransfer(self) -> None:
metrics = makeExampleMetrics()
dimensions = self.universe.conform(("visit", "physical_filter"))
dataId = {
"instrument": "dummy",
"visit": 2048,
"physical_filter": "Uprime",
"band": "u",
"day_obs": 20250101,
}
sc = self.storageClassFactory.getStorageClass("StructuredData")
ref = self.makeDatasetRef("metric", dimensions, sc, dataId)
inputDatastore = self.makeDatastore("test_input_datastore")
outputDatastore = self.makeDatastore("test_output_datastore")
inputDatastore.put(metrics, ref)
outputDatastore.transfer(inputDatastore, ref)
metricsOut = outputDatastore.get(ref)
self.assertEqual(metrics, metricsOut)
def testBasicTransaction(self) -> None:
datastore = self.makeDatastore()
storageClass = self.storageClassFactory.getStorageClass("StructuredData")
dimensions = self.universe.conform(("visit", "physical_filter"))
nDatasets = 6
dataIds = [
{"instrument": "dummy", "visit": i, "physical_filter": "V", "band": "v", "day_obs": 20250101}
for i in range(nDatasets)
]
data = [
(
self.makeDatasetRef("metric", dimensions, storageClass, dataId),
makeExampleMetrics(),
)
for dataId in dataIds
]
succeed = data[: nDatasets // 2]
fail = data[nDatasets // 2 :]
# All datasets added in this transaction should continue to exist
with datastore.transaction():
for ref, metrics in succeed:
datastore.put(metrics, ref)
# Whereas datasets added in this transaction should not
with self.assertRaises(TransactionTestError):
with datastore.transaction():
for ref, metrics in fail:
datastore.put(metrics, ref)
raise TransactionTestError("This should propagate out of the context manager")
# Check for datasets that should exist
for ref, metrics in succeed:
# Does it exist?
self.assertTrue(datastore.exists(ref))
# Get
metricsOut = datastore.get(ref, parameters=None)
self.assertEqual(metrics, metricsOut)
# URI
uri = datastore.getURI(ref)
self.assertEqual(uri.scheme, self.uriScheme)
# Check for datasets that should not exist
for ref, _ in fail:
# These should raise
with self.assertRaises(FileNotFoundError):
# non-existing file
datastore.get(ref)
with self.assertRaises(FileNotFoundError):
datastore.getURI(ref)
def testNestedTransaction(self) -> None:
datastore = self.makeDatastore()
storageClass = self.storageClassFactory.getStorageClass("StructuredData")
dimensions = self.universe.conform(("visit", "physical_filter"))
metrics = makeExampleMetrics()
dataId = {"instrument": "dummy", "visit": 0, "physical_filter": "V", "band": "v", "day_obs": 20250101}
refBefore = self.makeDatasetRef("metric", dimensions, storageClass, dataId)
datastore.put(metrics, refBefore)
with self.assertRaises(TransactionTestError):
with datastore.transaction():
dataId = {
"instrument": "dummy",
"visit": 1,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
refOuter = self.makeDatasetRef("metric", dimensions, storageClass, dataId)
datastore.put(metrics, refOuter)
with datastore.transaction():
dataId = {
"instrument": "dummy",
"visit": 2,
"physical_filter": "V",
"band": "v",
"day_obs": 20250101,
}
refInner = self.makeDatasetRef("metric", dimensions, storageClass, dataId)
datastore.put(metrics, refInner)
# All datasets should exist
for ref in (refBefore, refOuter, refInner):
metricsOut = datastore.get(ref, parameters=None)
self.assertEqual(metrics, metricsOut)
raise TransactionTestError("This should roll back the transaction")
# Dataset(s) inserted before the transaction should still exist
metricsOut = datastore.get(refBefore, parameters=None)
self.assertEqual(metrics, metricsOut)
# But all datasets inserted during the (rolled back) transaction
# should be gone
with self.assertRaises(FileNotFoundError):
datastore.get(refOuter)
with self.assertRaises(FileNotFoundError):
datastore.get(refInner)
def _prepareIngestTest(self) -> tuple[MetricsExample, DatasetRef]:
storageClass = self.storageClassFactory.getStorageClass("StructuredData")
dimensions = self.universe.conform(("visit", "physical_filter"))
metrics = makeExampleMetrics()
dataId = {"instrument": "dummy", "visit": 0, "physical_filter": "V", "band": "v", "day_obs": 20250101}
ref = self.makeDatasetRef("metric", dimensions, storageClass, dataId)
return metrics, ref
def runIngestTest(self, func: Callable[[MetricsExample, str, DatasetRef], None]) -> None:
metrics, ref = self._prepareIngestTest()
# The file will be deleted after the test.
# For symlink tests this leads to a situation where the datastore
# points to a file that does not exist. This will make os.path.exist
# return False but then the new symlink will fail with
# FileExistsError later in the code so the test still passes.
with _temp_yaml_file(metrics._asdict()) as path:
func(metrics, path, ref)
def testIngestNoTransfer(self) -> None:
"""Test ingesting existing files with no transfer."""
for mode in (None, "auto"):
# Some datastores have auto but can't do in place transfer
if mode == "auto" and "auto" in self.ingestTransferModes and not self.canIngestNoTransferAuto:
continue
with self.subTest(mode=mode):
datastore = self.makeDatastore()
def succeed(
obj: MetricsExample,
path: str,
ref: DatasetRef,
mode: str | None = mode,
datastore: Datastore = datastore,
) -> None:
"""Ingest a file already in the datastore root."""
# first move it into the root, and adjust the path
# accordingly
path = shutil.copy(path, datastore.root.ospath)
path = os.path.relpath(path, start=datastore.root.ospath)
datastore.ingest(FileDataset(path=path, refs=ref), transfer=mode)
self.assertEqual(obj, datastore.get(ref))
def failInputDoesNotExist(
obj: MetricsExample,
path: str,
ref: DatasetRef,
mode: str | None = mode,
datastore: Datastore = datastore,
) -> None:
"""Can't ingest files if we're given a bad path."""
with self.assertRaises(FileNotFoundError):
datastore.ingest(
FileDataset(path="this-file-does-not-exist.yaml", refs=ref), transfer=mode
)
self.assertFalse(datastore.exists(ref))
def failOutsideRoot(
obj: MetricsExample,
path: str,
ref: DatasetRef,
mode: str | None = mode,
datastore: Datastore = datastore,
) -> None:
"""Can't ingest files outside of datastore root unless
auto.
"""
if mode == "auto":
datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
self.assertTrue(datastore.exists(ref))
else:
with self.assertRaises(RuntimeError):
datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
self.assertFalse(datastore.exists(ref))
def failNotImplemented(
obj: MetricsExample,
path: str,
ref: DatasetRef,
mode: str | None = mode,
datastore: Datastore = datastore,
) -> None:
with self.assertRaises(NotImplementedError):
datastore.ingest(FileDataset(path=path, refs=ref), transfer=mode)
if mode in self.ingestTransferModes:
self.runIngestTest(failOutsideRoot)
self.runIngestTest(failInputDoesNotExist)
self.runIngestTest(succeed)
else:
self.runIngestTest(failNotImplemented)
def testIngestTransfer(self) -> None:
"""Test ingesting existing files after transferring them."""
for mode in ("copy", "move", "link", "hardlink", "symlink", "relsymlink", "auto"):
with self.subTest(mode=mode):
datastore = self.makeDatastore(mode)
def succeed(
obj: MetricsExample,
path: str,
ref: DatasetRef,
mode: str | None = mode,
datastore: Datastore = datastore,
) -> None:
"""Ingest a file by transferring it to the template
location.
"""
datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
self.assertEqual(obj, datastore.get(ref))
file_exists = os.path.exists(path)
if mode == "move":
self.assertFalse(file_exists)
else:
self.assertTrue(file_exists)
def failInputDoesNotExist(
obj: MetricsExample,
path: str,
ref: DatasetRef,
mode: str | None = mode,
datastore: Datastore = datastore,
) -> None:
"""Can't ingest files if we're given a bad path."""
with self.assertRaises(FileNotFoundError):
# Ensure the file does not look like it is in
# datastore for auto mode
datastore.ingest(
FileDataset(path="../this-file-does-not-exist.yaml", refs=ref), transfer=mode
)
self.assertFalse(datastore.exists(ref), f"Checking not in datastore using mode {mode}")
def failNotImplemented(
obj: MetricsExample,
path: str,
ref: DatasetRef,
mode: str | None = mode,
datastore: Datastore = datastore,
) -> None:
with self.assertRaises(NotImplementedError):
datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
if mode in self.ingestTransferModes:
self.runIngestTest(failInputDoesNotExist)
self.runIngestTest(succeed)
else:
self.runIngestTest(failNotImplemented)
def testIngestSymlinkOfSymlink(self) -> None:
"""Special test for symlink to a symlink ingest"""
metrics, ref = self._prepareIngestTest()
# The aim of this test is to create a dataset on disk, then
# create a symlink to it and finally ingest the symlink such that
# the symlink in the datastore points to the original dataset.
for mode in ("symlink", "relsymlink"):
if mode not in self.ingestTransferModes:
continue
print(f"Trying mode {mode}")
with _temp_yaml_file(metrics._asdict()) as realpath:
with tempfile.TemporaryDirectory() as tmpdir:
sympath = os.path.join(tmpdir, "symlink.yaml")
os.symlink(os.path.realpath(realpath), sympath)
datastore = self.makeDatastore()
datastore.ingest(FileDataset(path=os.path.abspath(sympath), refs=ref), transfer=mode)
uri = datastore.getURI(ref)
self.assertTrue(uri.isLocal, f"Check {uri.scheme}")
self.assertTrue(os.path.islink(uri.ospath), f"Check {uri} is a symlink")
linkTarget = os.readlink(uri.ospath)
if mode == "relsymlink":
self.assertFalse(os.path.isabs(linkTarget))
else:
self.assertTrue(os.path.samefile(linkTarget, realpath))
# Check that we can get the dataset back regardless of mode
metric2 = datastore.get(ref)
self.assertEqual(metric2, metrics)
# Cleanup the file for next time round loop
# since it will get the same file name in store
datastore.remove(ref)
def _populate_export_datastore(self, name: str) -> tuple[Datastore, list[DatasetRef]]:
datastore = self.makeDatastore(name)
# For now only the FileDatastore can be used for this test.
# ChainedDatastore that only includes InMemoryDatastores have to be
# skipped as well.
for name in datastore.names:
if not name.startswith("InMemoryDatastore"):
break
else:
raise unittest.SkipTest("in-memory datastore does not support record export/import")
metrics = makeExampleMetrics()
dimensions = self.universe.conform(("visit", "physical_filter"))
sc = self.storageClassFactory.getStorageClass("StructuredData")
refs = []
for visit in (2048, 2049, 2050):
dataId = {
"instrument": "dummy",
"visit": visit,
"physical_filter": "Uprime",
"band": "u",
"day_obs": 20250101,
}
ref = self.makeDatasetRef("metric", dimensions, sc, dataId)
datastore.put(metrics, ref)
refs.append(ref)
return datastore, refs
def testExportImportRecords(self) -> None:
"""Test for export_records and import_records methods."""
datastore, refs = self._populate_export_datastore("test_datastore")
for exported_refs in (refs, refs[1:]):
n_refs = len(exported_refs)
records = datastore.export_records(exported_refs)
self.assertGreater(len(records), 0)
self.assertTrue(set(records.keys()) <= set(datastore.names))
# In a ChainedDatastore each FileDatastore will have a complete set
for datastore_name in records:
record_data = records[datastore_name]
self.assertEqual(len(record_data.records), n_refs)
# Check that subsetting works, include non-existing dataset ID.
dataset_ids = {exported_refs[0].id, uuid.uuid4()}
subset = record_data.subset(dataset_ids)
assert subset is not None
self.assertEqual(len(subset.records), 1)
subset = record_data.subset({uuid.uuid4()})
self.assertIsNone(subset)
# Use the same datastore name to import relative path.
datastore2 = self.makeDatastore("test_datastore")
records = datastore.export_records(refs[1:])
datastore2.import_records(records)
with self.assertRaises(FileNotFoundError):
data = datastore2.get(refs[0])
data = datastore2.get(refs[1])
self.assertIsNotNone(data)
data = datastore2.get(refs[2])
self.assertIsNotNone(data)
def testExport(self) -> None:
datastore, refs = self._populate_export_datastore("test_datastore")
datasets = list(datastore.export(refs))
self.assertEqual(len(datasets), 3)
for transfer in (None, "auto"):
# Both will default to None
datasets = list(datastore.export(refs, transfer=transfer))
self.assertEqual(len(datasets), 3)
with self.assertRaises(TypeError):
list(datastore.export(refs, transfer="copy"))
with self.assertRaises(TypeError):
list(datastore.export(refs, directory="exportDir", transfer="move"))
# Create a new ref that is not known to the datastore and try to
# export it.