-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtest_butler.py
3153 lines (2635 loc) · 135 KB
/
test_butler.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/>.
"""Tests for Butler."""
from __future__ import annotations
import json
import logging
import os
import pathlib
import pickle
import posixpath
import random
import re
import shutil
import string
import tempfile
import unittest
import unittest.mock
import uuid
from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, Any, cast
try:
import boto3
import botocore
from lsst.resources.s3utils import clean_test_environment_for_s3
try:
from moto import mock_aws # v5
except ImportError:
from moto import mock_s3 as mock_aws
except ImportError:
boto3 = None
def mock_aws(*args: Any, **kwargs: Any) -> Any: # type: ignore[no-untyped-def]
"""No-op decorator in case moto mock_aws can not be imported."""
return None
try:
from lsst.daf.butler.tests.server import create_test_server
except ImportError:
create_test_server = None
import astropy.time
from lsst.daf.butler import (
Butler,
ButlerConfig,
ButlerMetrics,
ButlerRepoIndex,
CollectionCycleError,
CollectionType,
Config,
DataCoordinate,
DatasetExistence,
DatasetNotFoundError,
DatasetProvenance,
DatasetRef,
DatasetType,
FileDataset,
NoDefaultCollectionError,
StorageClassFactory,
ValidationError,
script,
)
from lsst.daf.butler.datastore import NullDatastore
from lsst.daf.butler.datastore.file_templates import FileTemplate, FileTemplateValidationError
from lsst.daf.butler.datastores.file_datastore.retrieve_artifacts import ZipIndex
from lsst.daf.butler.datastores.fileDatastore import FileDatastore
from lsst.daf.butler.direct_butler import DirectButler
from lsst.daf.butler.registry import (
CollectionError,
CollectionTypeError,
ConflictingDefinitionError,
DataIdValueError,
DatasetTypeExpressionError,
MissingCollectionError,
OrphanedRecordError,
)
from lsst.daf.butler.registry.sql_registry import SqlRegistry
from lsst.daf.butler.repo_relocation import BUTLER_ROOT_TAG
from lsst.daf.butler.tests import MetricsExample, MetricsExampleModel, MultiDetectorFormatter
from lsst.daf.butler.tests.postgresql import TemporaryPostgresInstance, setup_postgres_test_db
from lsst.daf.butler.tests.utils import TestCaseMixin, makeTestTempDir, removeTestTempDir, safeTestTempDir
from lsst.resources import ResourcePath
from lsst.utils import doImportType
from lsst.utils.introspection import get_full_type_name
if TYPE_CHECKING:
import types
from lsst.daf.butler import DimensionGroup, Registry, StorageClass
TESTDIR = os.path.abspath(os.path.dirname(__file__))
def clean_environment() -> None:
"""Remove external environment variables that affect the tests."""
for k in ("DAF_BUTLER_REPOSITORY_INDEX",):
os.environ.pop(k, None)
def makeExampleMetrics() -> MetricsExample:
"""Return example dataset suitable for tests."""
return MetricsExample(
{"AM1": 5.2, "AM2": 30.6},
{"a": [1, 2, 3], "b": {"blue": 5, "red": "green"}},
[563, 234, 456.7, 752, 8, 9, 27],
)
class TransactionTestError(Exception):
"""Specific error for testing transactions, to prevent misdiagnosing
that might otherwise occur when a standard exception is used.
"""
pass
class ButlerConfigTests(unittest.TestCase):
"""Simple tests for ButlerConfig that are not tested in any other test
cases.
"""
def testSearchPath(self) -> None:
configFile = os.path.join(TESTDIR, "config", "basic", "butler.yaml")
with self.assertLogs("lsst.daf.butler", level="DEBUG") as cm:
config1 = ButlerConfig(configFile)
self.assertNotIn("testConfigs", "\n".join(cm.output))
overrideDirectory = os.path.join(TESTDIR, "config", "testConfigs")
with self.assertLogs("lsst.daf.butler", level="DEBUG") as cm:
config2 = ButlerConfig(configFile, searchPaths=[overrideDirectory])
self.assertIn("testConfigs", "\n".join(cm.output))
key = ("datastore", "records", "table")
self.assertNotEqual(config1[key], config2[key])
self.assertEqual(config2[key], "override_record")
class ButlerPutGetTests(TestCaseMixin):
"""Helper method for running a suite of put/get tests from different
butler configurations.
"""
root: str
default_run = "ingésτ😺"
storageClassFactory: StorageClassFactory
configFile: str | None
tmpConfigFile: str
@staticmethod
def addDatasetType(
datasetTypeName: str, dimensions: DimensionGroup, storageClass: StorageClass | str, registry: Registry
) -> DatasetType:
"""Create a DatasetType and register it"""
datasetType = DatasetType(datasetTypeName, dimensions, storageClass)
registry.registerDatasetType(datasetType)
return datasetType
@classmethod
def setUpClass(cls) -> None:
cls.storageClassFactory = StorageClassFactory()
if cls.configFile is not None:
cls.storageClassFactory.addFromConfig(cls.configFile)
def assertGetComponents(
self,
butler: Butler,
datasetRef: DatasetRef,
components: tuple[str, ...],
reference: Any,
collections: Any = None,
) -> None:
datasetType = datasetRef.datasetType
dataId = datasetRef.dataId
deferred = butler.getDeferred(datasetRef)
for component in components:
compTypeName = datasetType.componentTypeName(component)
result = butler.get(compTypeName, dataId, collections=collections)
self.assertEqual(result, getattr(reference, component))
result_deferred = deferred.get(component=component)
self.assertEqual(result_deferred, result)
def tearDown(self) -> None:
if self.root is not None:
removeTestTempDir(self.root)
def create_empty_butler(
self, run: str | None = None, writeable: bool | None = None, metrics: ButlerMetrics | None = None
):
"""Create a Butler for the test repository, without inserting test
data.
"""
butler = Butler.from_config(self.tmpConfigFile, run=run, writeable=writeable, metrics=metrics)
assert isinstance(butler, DirectButler), "Expect DirectButler in configuration"
return butler
def create_butler(
self,
run: str,
storageClass: StorageClass | str,
datasetTypeName: str,
metrics: ButlerMetrics | None = None,
) -> tuple[Butler, DatasetType]:
"""Create a Butler for the test repository and insert some test data
into it.
"""
butler = self.create_empty_butler(run=run, metrics=metrics)
collections = set(butler.collections.query("*"))
self.assertEqual(collections, {run})
# Create and register a DatasetType
dimensions = butler.dimensions.conform(["instrument", "visit"])
datasetType = self.addDatasetType(datasetTypeName, dimensions, storageClass, butler.registry)
# Add needed Dimensions
butler.registry.insertDimensionData("instrument", {"name": "DummyCamComp"})
butler.registry.insertDimensionData(
"physical_filter", {"instrument": "DummyCamComp", "name": "d-r", "band": "R"}
)
butler.registry.insertDimensionData(
"visit_system", {"instrument": "DummyCamComp", "id": 1, "name": "default"}
)
butler.registry.insertDimensionData("day_obs", {"instrument": "DummyCamComp", "id": 20200101})
visit_start = astropy.time.Time("2020-01-01 08:00:00.123456789", scale="tai")
visit_end = astropy.time.Time("2020-01-01 08:00:36.66", scale="tai")
butler.registry.insertDimensionData(
"visit",
{
"instrument": "DummyCamComp",
"id": 423,
"name": "fourtwentythree",
"physical_filter": "d-r",
"datetime_begin": visit_start,
"datetime_end": visit_end,
"day_obs": 20200101,
},
)
# Add more visits for some later tests
for visit_id in (424, 425):
butler.registry.insertDimensionData(
"visit",
{
"instrument": "DummyCamComp",
"id": visit_id,
"name": f"fourtwentyfour_{visit_id}",
"physical_filter": "d-r",
"day_obs": 20200101,
},
)
return butler, datasetType
def runPutGetTest(self, storageClass: StorageClass, datasetTypeName: str) -> Butler:
# New datasets will be added to run and tag, but we will only look in
# tag when looking up datasets.
run = self.default_run
butler, datasetType = self.create_butler(run, storageClass, datasetTypeName)
assert butler.run is not None
# Create and store a dataset
metric = makeExampleMetrics()
dataId = butler.registry.expandDataId({"instrument": "DummyCamComp", "visit": 423})
# Dataset should not exist if we haven't added it
with self.assertRaises(DatasetNotFoundError):
butler.get(datasetTypeName, dataId)
# Put and remove the dataset once as a DatasetRef, once as a dataId,
# and once with a DatasetType
# Keep track of any collections we add and do not clean up
expected_collections = {run}
counter = 0
ref = DatasetRef(datasetType, dataId, id=uuid.UUID(int=1), run="put_run_1")
args = tuple[DatasetRef] | tuple[str | DatasetType, DataCoordinate]
for args in ((ref,), (datasetTypeName, dataId), (datasetType, dataId)):
# Since we are using subTest we can get cascading failures
# here with the first attempt failing and the others failing
# immediately because the dataset already exists. Work around
# this by using a distinct run collection each time
counter += 1
this_run = f"put_run_{counter}"
butler.collections.register(this_run)
expected_collections.update({this_run})
with self.subTest(args=args):
kwargs: dict[str, Any] = {}
if not isinstance(args[0], DatasetRef): # type: ignore
kwargs["run"] = this_run
ref = butler.put(metric, *args, **kwargs)
self.assertIsInstance(ref, DatasetRef)
# Test get of a ref.
metricOut = butler.get(ref)
self.assertEqual(metric, metricOut)
# Test get
metricOut = butler.get(ref.datasetType.name, dataId, collections=this_run)
self.assertEqual(metric, metricOut)
# Test get with a datasetRef
metricOut = butler.get(ref)
self.assertEqual(metric, metricOut)
# Test getDeferred with dataId
metricOut = butler.getDeferred(ref.datasetType.name, dataId, collections=this_run).get()
self.assertEqual(metric, metricOut)
# Test getDeferred with a ref
metricOut = butler.getDeferred(ref).get()
self.assertEqual(metric, metricOut)
# Check we can get components
if storageClass.isComposite():
self.assertGetComponents(
butler, ref, ("summary", "data", "output"), metric, collections=this_run
)
primary_uri, secondary_uris = butler.getURIs(ref)
n_uris = len(secondary_uris)
if primary_uri:
n_uris += 1
# Can the artifacts themselves be retrieved?
if not butler._datastore.isEphemeral:
# Create a temporary directory to hold the retrieved
# artifacts.
with tempfile.TemporaryDirectory(
prefix="butler-artifacts-", ignore_cleanup_errors=True
) as artifact_root:
root_uri = ResourcePath(artifact_root, forceDirectory=True)
for preserve_path in (True, False):
destination = root_uri.join(f"{preserve_path}_{counter}/")
log = logging.getLogger("lsst.x")
log.debug("Using destination %s for args %s", destination, args)
# Use copy so that we can test that overwrite
# protection works (using "auto" for File URIs
# would use hard links and subsequent transfer
# would work because it knows they are the same
# file).
transferred = butler.retrieveArtifacts(
[ref], destination, preserve_path=preserve_path, transfer="copy"
)
self.assertGreater(len(transferred), 0)
artifacts = list(ResourcePath.findFileResources([destination]))
# Filter out the index file.
artifacts = [a for a in artifacts if a.basename() != ZipIndex.index_name]
self.assertEqual(set(transferred), set(artifacts))
for artifact in transferred:
path_in_destination = artifact.relative_to(destination)
self.assertIsNotNone(path_in_destination)
assert path_in_destination is not None
# When path is not preserved there should not
# be any path separators.
num_seps = path_in_destination.count("/")
if preserve_path:
self.assertGreater(num_seps, 0)
else:
self.assertEqual(num_seps, 0)
self.assertEqual(
len(artifacts),
n_uris,
"Comparing expected artifacts vs actual:"
f" {artifacts} vs {primary_uri} and {secondary_uris}",
)
if preserve_path:
# No need to run these twice
with self.assertRaises(ValueError):
butler.retrieveArtifacts([ref], destination, transfer="move")
with self.assertRaisesRegex(
ValueError, "^Destination location must refer to a directory"
):
butler.retrieveArtifacts(
[ref], ResourcePath("/some/file.txt", forceDirectory=False)
)
with self.assertRaises(FileExistsError):
butler.retrieveArtifacts([ref], destination)
transferred_again = butler.retrieveArtifacts(
[ref], destination, preserve_path=preserve_path, overwrite=True
)
self.assertEqual(set(transferred_again), set(transferred))
# Now remove the dataset completely.
butler.pruneDatasets([ref], purge=True, unstore=True)
# Lookup with original args should still fail.
kwargs = {"collections": this_run}
if isinstance(args[0], DatasetRef):
kwargs = {} # Prevent warning from being issued.
self.assertFalse(butler.exists(*args, **kwargs))
# get() should still fail.
with self.assertRaises((FileNotFoundError, DatasetNotFoundError)):
butler.get(ref)
# Registry shouldn't be able to find it by dataset_id anymore.
self.assertIsNone(butler.get_dataset(ref.id))
# Do explicit registry removal since we know they are
# empty
butler.collections.x_remove(this_run)
expected_collections.remove(this_run)
# Create DatasetRef for put using default run.
refIn = DatasetRef(datasetType, dataId, id=uuid.UUID(int=1), run=butler.run)
# Check that getDeferred fails with standalone ref.
with self.assertRaises(LookupError):
butler.getDeferred(refIn)
# Put the dataset again, since the last thing we did was remove it
# and we want to use the default collection.
ref = butler.put(metric, refIn)
# Get with parameters
stop = 4
sliced = butler.get(ref, parameters={"slice": slice(stop)})
self.assertNotEqual(metric, sliced)
self.assertEqual(metric.summary, sliced.summary)
self.assertEqual(metric.output, sliced.output)
assert metric.data is not None # for mypy
self.assertEqual(metric.data[:stop], sliced.data)
# getDeferred with parameters
sliced = butler.getDeferred(ref, parameters={"slice": slice(stop)}).get()
self.assertNotEqual(metric, sliced)
self.assertEqual(metric.summary, sliced.summary)
self.assertEqual(metric.output, sliced.output)
self.assertEqual(metric.data[:stop], sliced.data)
# getDeferred with deferred parameters
sliced = butler.getDeferred(ref).get(parameters={"slice": slice(stop)})
self.assertNotEqual(metric, sliced)
self.assertEqual(metric.summary, sliced.summary)
self.assertEqual(metric.output, sliced.output)
self.assertEqual(metric.data[:stop], sliced.data)
if storageClass.isComposite():
# Check that components can be retrieved
metricOut = butler.get(ref.datasetType.name, dataId)
compNameS = ref.datasetType.componentTypeName("summary")
compNameD = ref.datasetType.componentTypeName("data")
summary = butler.get(compNameS, dataId)
self.assertEqual(summary, metric.summary)
data = butler.get(compNameD, dataId)
self.assertEqual(data, metric.data)
if "counter" in storageClass.derivedComponents:
count = butler.get(ref.datasetType.componentTypeName("counter"), dataId)
self.assertEqual(count, len(data))
count = butler.get(
ref.datasetType.componentTypeName("counter"), dataId, parameters={"slice": slice(stop)}
)
self.assertEqual(count, stop)
compRef = butler.find_dataset(compNameS, dataId, collections=butler.collections.defaults)
assert compRef is not None
summary = butler.get(compRef)
self.assertEqual(summary, metric.summary)
# Create a Dataset type that has the same name but is inconsistent.
inconsistentDatasetType = DatasetType(
datasetTypeName, datasetType.dimensions, self.storageClassFactory.getStorageClass("Config")
)
# Getting with a dataset type that does not match registry fails
with self.assertRaisesRegex(
ValueError,
"(Supplied dataset type .* inconsistent with registry)"
"|(The new storage class .* is not compatible with the existing storage class)",
):
butler.get(inconsistentDatasetType, dataId)
# Combining a DatasetRef with a dataId should fail
with self.assertRaisesRegex(ValueError, "DatasetRef given, cannot use dataId as well"):
butler.get(ref, dataId)
# Getting with an explicit ref should fail if the id doesn't match.
with self.assertRaises((FileNotFoundError, DatasetNotFoundError)):
butler.get(DatasetRef(ref.datasetType, ref.dataId, id=uuid.UUID(int=101), run=butler.run))
# Getting a dataset with unknown parameters should fail
with self.assertRaisesRegex(KeyError, "Parameter 'unsupported' not understood"):
butler.get(ref, parameters={"unsupported": True})
# Check we have a collection
collections = set(butler.collections.query("*"))
self.assertEqual(collections, expected_collections)
# Clean up to check that we can remove something that may have
# already had a component removed
butler.pruneDatasets([ref], unstore=True, purge=True)
# Add the same ref again, so we can check that duplicate put fails.
ref = butler.put(metric, datasetType, dataId)
# Repeat put will fail.
with self.assertRaisesRegex(
ConflictingDefinitionError, "A database constraint failure was triggered"
):
butler.put(metric, datasetType, dataId)
# Remove the datastore entry.
butler.pruneDatasets([ref], unstore=True, purge=False, disassociate=False)
# Put will still fail
with self.assertRaisesRegex(
ConflictingDefinitionError, "A database constraint failure was triggered"
):
butler.put(metric, datasetType, dataId)
# Repeat the same sequence with resolved ref.
butler.pruneDatasets([ref], unstore=True, purge=True)
ref = butler.put(metric, refIn)
# Repeat put will fail.
with self.assertRaisesRegex(ConflictingDefinitionError, "Datastore already contains dataset"):
butler.put(metric, refIn)
# Remove the datastore entry.
butler.pruneDatasets([ref], unstore=True, purge=False, disassociate=False)
# In case of resolved ref this write will succeed.
ref = butler.put(metric, refIn)
# Leave the dataset in place since some downstream tests require
# something to be present
return butler
def testDeferredCollectionPassing(self) -> None:
# Construct a butler with no run or collection, but make it writeable.
butler = self.create_empty_butler(writeable=True)
# Create and register a DatasetType
dimensions = butler.dimensions.conform(["instrument", "visit"])
datasetType = self.addDatasetType(
"example", dimensions, self.storageClassFactory.getStorageClass("StructuredData"), butler.registry
)
# Add needed Dimensions
butler.registry.insertDimensionData("instrument", {"name": "DummyCamComp"})
butler.registry.insertDimensionData(
"physical_filter", {"instrument": "DummyCamComp", "name": "d-r", "band": "R"}
)
butler.registry.insertDimensionData("day_obs", {"instrument": "DummyCamComp", "id": 20250101})
butler.registry.insertDimensionData(
"visit",
{
"instrument": "DummyCamComp",
"id": 423,
"name": "fourtwentythree",
"physical_filter": "d-r",
"day_obs": 20250101,
},
)
dataId = {"instrument": "DummyCamComp", "visit": 423}
# Create dataset.
metric = makeExampleMetrics()
# Register a new run and put dataset.
run = "deferred"
self.assertTrue(butler.collections.register(run))
# Second time it will be allowed but indicate no-op
self.assertFalse(butler.collections.register(run))
ref = butler.put(metric, datasetType, dataId, run=run)
# Putting with no run should fail with TypeError.
with self.assertRaises(CollectionError):
butler.put(metric, datasetType, dataId)
# Dataset should exist.
self.assertTrue(butler.exists(datasetType, dataId, collections=[run]))
# We should be able to get the dataset back, but with and without
# a deferred dataset handle.
self.assertEqual(metric, butler.get(datasetType, dataId, collections=[run]))
self.assertEqual(metric, butler.getDeferred(datasetType, dataId, collections=[run]).get())
# Trying to find the dataset without any collection is an error.
with self.assertRaises(NoDefaultCollectionError):
butler.exists(datasetType, dataId)
with self.assertRaises(CollectionError):
butler.get(datasetType, dataId)
# Associate the dataset with a different collection.
butler.collections.register("tagged", type=CollectionType.TAGGED)
butler.registry.associate("tagged", [ref])
# Deleting the dataset from the new collection should make it findable
# in the original collection.
butler.pruneDatasets([ref], tags=["tagged"])
self.assertTrue(butler.exists(datasetType, dataId, collections=[run]))
class ButlerTests(ButlerPutGetTests):
"""Tests for Butler."""
useTempRoot = True
validationCanFail: bool
fullConfigKey: str | None
registryStr: str | None
datastoreName: list[str] | None
datastoreStr: list[str]
predictionSupported = True
"""Does getURIs support 'prediction mode'?"""
def setUp(self) -> None:
"""Create a new butler root for each test."""
self.root = makeTestTempDir(TESTDIR)
Butler.makeRepo(self.root, config=Config(self.configFile))
self.tmpConfigFile = os.path.join(self.root, "butler.yaml")
def are_uris_equivalent(self, uri1: ResourcePath, uri2: ResourcePath) -> bool:
"""Return True if two URIs refer to the same resource.
Subclasses may override to handle unique requirements.
"""
return uri1 == uri2
def testConstructor(self) -> None:
"""Independent test of constructor."""
butler = Butler.from_config(self.tmpConfigFile, run=self.default_run)
self.assertIsInstance(butler, Butler)
# Check that butler.yaml is added automatically.
if self.tmpConfigFile.endswith(end := "/butler.yaml"):
config_dir = self.tmpConfigFile[: -len(end)]
butler = Butler.from_config(config_dir, run=self.default_run)
self.assertIsInstance(butler, Butler)
# Even with a ResourcePath.
butler = Butler.from_config(ResourcePath(config_dir, forceDirectory=True), run=self.default_run)
self.assertIsInstance(butler, Butler)
collections = set(butler.collections.query("*"))
self.assertEqual(collections, {self.default_run})
# Check that some special characters can be included in run name.
special_run = "[email protected]"
butler_special = Butler.from_config(butler=butler, run=special_run)
collections = set(butler_special.registry.queryCollections("*@*"))
self.assertEqual(collections, {special_run})
butler2 = Butler.from_config(butler=butler, collections=["other"])
self.assertEqual(butler2.collections.defaults, ("other",))
self.assertIsNone(butler2.run)
self.assertEqual(type(butler._datastore), type(butler2._datastore))
self.assertEqual(butler._datastore.config, butler2._datastore.config)
# Test that we can use an environment variable to find this
# repository.
butler_index = Config()
butler_index["label"] = self.tmpConfigFile
for suffix in (".yaml", ".json"):
# Ensure that the content differs so that we know that
# we aren't reusing the cache.
bad_label = f"file://bucket/not_real{suffix}"
butler_index["bad_label"] = bad_label
with ResourcePath.temporary_uri(suffix=suffix) as temp_file:
butler_index.dumpToUri(temp_file)
with unittest.mock.patch.dict(os.environ, {"DAF_BUTLER_REPOSITORY_INDEX": str(temp_file)}):
self.assertEqual(Butler.get_known_repos(), {"label", "bad_label"})
uri = Butler.get_repo_uri("bad_label")
self.assertEqual(uri, ResourcePath(bad_label))
uri = Butler.get_repo_uri("label")
butler = Butler.from_config(uri, writeable=False)
self.assertIsInstance(butler, Butler)
butler = Butler.from_config("label", writeable=False)
self.assertIsInstance(butler, Butler)
with self.assertRaisesRegex(FileNotFoundError, "aliases:.*bad_label"):
Butler.from_config("not_there", writeable=False)
with self.assertRaisesRegex(FileNotFoundError, "resolved from alias 'bad_label'"):
Butler.from_config("bad_label")
with self.assertRaises(FileNotFoundError):
# Should ignore aliases.
Butler.from_config(ResourcePath("label", forceAbsolute=False))
with self.assertRaises(KeyError) as cm:
Butler.get_repo_uri("missing")
self.assertEqual(
Butler.get_repo_uri("missing", True), ResourcePath("missing", forceAbsolute=False)
)
self.assertIn("not known to", str(cm.exception))
# Should report no failure.
self.assertEqual(ButlerRepoIndex.get_failure_reason(), "")
with ResourcePath.temporary_uri(suffix=suffix) as temp_file:
# Now with empty configuration.
butler_index = Config()
butler_index.dumpToUri(temp_file)
with unittest.mock.patch.dict(os.environ, {"DAF_BUTLER_REPOSITORY_INDEX": str(temp_file)}):
with self.assertRaisesRegex(FileNotFoundError, "(no known aliases)"):
Butler.from_config("label")
with ResourcePath.temporary_uri(suffix=suffix) as temp_file:
# Now with bad contents.
with open(temp_file.ospath, "w") as fh:
print("'", file=fh)
with unittest.mock.patch.dict(os.environ, {"DAF_BUTLER_REPOSITORY_INDEX": str(temp_file)}):
with self.assertRaisesRegex(FileNotFoundError, "(no known aliases:.*could not be read)"):
Butler.from_config("label")
with unittest.mock.patch.dict(os.environ, {"DAF_BUTLER_REPOSITORY_INDEX": "file://not_found/x.yaml"}):
with self.assertRaises(FileNotFoundError):
Butler.get_repo_uri("label")
self.assertEqual(Butler.get_known_repos(), set())
with self.assertRaisesRegex(FileNotFoundError, "index file not found"):
Butler.from_config("label")
# Check that we can create Butler when the alias file is not found.
butler = Butler.from_config(self.tmpConfigFile, writeable=False)
self.assertIsInstance(butler, Butler)
with self.assertRaises(RuntimeError) as cm:
# No environment variable set.
Butler.get_repo_uri("label")
self.assertEqual(Butler.get_repo_uri("label", True), ResourcePath("label", forceAbsolute=False))
self.assertIn("No repository index defined", str(cm.exception))
with self.assertRaisesRegex(FileNotFoundError, "no known aliases.*No repository index"):
# No aliases registered.
Butler.from_config("not_there")
self.assertEqual(Butler.get_known_repos(), set())
def testDafButlerRepositories(self):
with unittest.mock.patch.dict(
os.environ,
{"DAF_BUTLER_REPOSITORIES": "label: 'https://someuri.com'\notherLabel: 'https://otheruri.com'\n"},
):
self.assertEqual(str(Butler.get_repo_uri("label")), "https://someuri.com")
with unittest.mock.patch.dict(
os.environ,
{
"DAF_BUTLER_REPOSITORIES": "label: https://someuri.com",
"DAF_BUTLER_REPOSITORY_INDEX": "https://someuri.com",
},
):
with self.assertRaisesRegex(RuntimeError, "Only one of the environment variables"):
Butler.get_repo_uri("label")
with unittest.mock.patch.dict(
os.environ,
{"DAF_BUTLER_REPOSITORIES": "invalid"},
):
with self.assertRaisesRegex(ValueError, "Repository index not in expected format"):
Butler.get_repo_uri("label")
def testBasicPutGet(self) -> None:
storageClass = self.storageClassFactory.getStorageClass("StructuredDataNoComponents")
self.runPutGetTest(storageClass, "test_metric")
def testCompositePutGetConcrete(self) -> None:
storageClass = self.storageClassFactory.getStorageClass("StructuredCompositeReadCompNoDisassembly")
butler = self.runPutGetTest(storageClass, "test_metric")
# Should *not* be disassembled
datasets = list(butler.registry.queryDatasets(..., collections=self.default_run))
self.assertEqual(len(datasets), 1)
uri, components = butler.getURIs(datasets[0])
self.assertIsInstance(uri, ResourcePath)
self.assertFalse(components)
self.assertEqual(uri.fragment, "", f"Checking absence of fragment in {uri}")
self.assertIn("423", str(uri), f"Checking visit is in URI {uri}")
# Predicted dataset
if self.predictionSupported:
dataId = {"instrument": "DummyCamComp", "visit": 424}
uri, components = butler.getURIs(datasets[0].datasetType, dataId=dataId, predict=True)
self.assertFalse(components)
self.assertIsInstance(uri, ResourcePath)
self.assertIn("424", str(uri), f"Checking visit is in URI {uri}")
self.assertEqual(uri.fragment, "predicted", f"Checking for fragment in {uri}")
def testCompositePutGetVirtual(self) -> None:
storageClass = self.storageClassFactory.getStorageClass("StructuredCompositeReadComp")
butler = self.runPutGetTest(storageClass, "test_metric_comp")
# Should be disassembled
datasets = list(butler.registry.queryDatasets(..., collections=self.default_run))
self.assertEqual(len(datasets), 1)
uri, components = butler.getURIs(datasets[0])
if butler._datastore.isEphemeral:
# Never disassemble in-memory datastore
self.assertIsInstance(uri, ResourcePath)
self.assertFalse(components)
self.assertEqual(uri.fragment, "", f"Checking absence of fragment in {uri}")
self.assertIn("423", str(uri), f"Checking visit is in URI {uri}")
else:
self.assertIsNone(uri)
self.assertEqual(set(components), set(storageClass.components))
for compuri in components.values():
self.assertIsInstance(compuri, ResourcePath)
self.assertIn("423", str(compuri), f"Checking visit is in URI {compuri}")
self.assertEqual(compuri.fragment, "", f"Checking absence of fragment in {compuri}")
if self.predictionSupported:
# Predicted dataset
dataId = {"instrument": "DummyCamComp", "visit": 424}
uri, components = butler.getURIs(datasets[0].datasetType, dataId=dataId, predict=True)
if butler._datastore.isEphemeral:
# Never disassembled
self.assertIsInstance(uri, ResourcePath)
self.assertFalse(components)
self.assertIn("424", str(uri), f"Checking visit is in URI {uri}")
self.assertEqual(uri.fragment, "predicted", f"Checking for fragment in {uri}")
else:
self.assertIsNone(uri)
self.assertEqual(set(components), set(storageClass.components))
for compuri in components.values():
self.assertIsInstance(compuri, ResourcePath)
self.assertIn("424", str(compuri), f"Checking visit is in URI {compuri}")
self.assertEqual(compuri.fragment, "predicted", f"Checking for fragment in {compuri}")
def testStorageClassOverrideGet(self) -> None:
"""Test storage class conversion on get with override."""
storageClass = self.storageClassFactory.getStorageClass("StructuredData")
datasetTypeName = "anything"
run = self.default_run
butler, datasetType = self.create_butler(run, storageClass, datasetTypeName)
# Create and store a dataset.
metric = makeExampleMetrics()
dataId = {"instrument": "DummyCamComp", "visit": 423}
ref = butler.put(metric, datasetType, dataId)
# Return native type.
retrieved = butler.get(ref)
self.assertEqual(retrieved, metric)
# Specify an override.
new_sc = self.storageClassFactory.getStorageClass("MetricsConversion")
model = butler.get(ref, storageClass=new_sc)
self.assertNotEqual(type(model), type(retrieved))
self.assertIs(type(model), new_sc.pytype)
self.assertEqual(retrieved, model)
# Defer but override later.
deferred = butler.getDeferred(ref)
model = deferred.get(storageClass=new_sc)
self.assertIs(type(model), new_sc.pytype)
self.assertEqual(retrieved, model)
# Defer but override up front.
deferred = butler.getDeferred(ref, storageClass=new_sc)
model = deferred.get()
self.assertIs(type(model), new_sc.pytype)
self.assertEqual(retrieved, model)
# Retrieve a component. Should be a tuple.
data = butler.get("anything.data", dataId, storageClass="StructuredDataDataTestTuple")
self.assertIs(type(data), tuple)
self.assertEqual(data, tuple(retrieved.data))
# Parameter on the write storage class should work regardless
# of read storage class.
data = butler.get(
"anything.data",
dataId,
storageClass="StructuredDataDataTestTuple",
parameters={"slice": slice(2, 4)},
)
self.assertEqual(len(data), 2)
# Try a parameter that is known to the read storage class but not
# the write storage class.
with self.assertRaises(KeyError):
butler.get(
"anything.data",
dataId,
storageClass="StructuredDataDataTestTuple",
parameters={"xslice": slice(2, 4)},
)
def testPytypePutCoercion(self) -> None:
"""Test python type coercion on Butler.get and put."""
# Store some data with the normal example storage class.
storageClass = self.storageClassFactory.getStorageClass("StructuredDataNoComponents")
datasetTypeName = "test_metric"
butler, _ = self.create_butler(self.default_run, storageClass, datasetTypeName)
dataId = {"instrument": "DummyCamComp", "visit": 423}
# Put a dict and this should coerce to a MetricsExample
test_dict = {"summary": {"a": 1}, "output": {"b": 2}}
metric_ref = butler.put(test_dict, datasetTypeName, dataId=dataId, visit=424)
test_metric = butler.get(metric_ref)
self.assertEqual(get_full_type_name(test_metric), "lsst.daf.butler.tests.MetricsExample")
self.assertEqual(test_metric.summary, test_dict["summary"])
self.assertEqual(test_metric.output, test_dict["output"])
# Check that the put still works if a DatasetType is given with
# a definition matching this python type.
registry_type = butler.get_dataset_type(datasetTypeName)
this_type = DatasetType(datasetTypeName, registry_type.dimensions, "StructuredDataDictJson")
metric2_ref = butler.put(test_dict, this_type, dataId=dataId, visit=425)
self.assertEqual(metric2_ref.datasetType, registry_type)
# The get will return the type expected by registry.
test_metric2 = butler.get(metric2_ref)
self.assertEqual(get_full_type_name(test_metric2), "lsst.daf.butler.tests.MetricsExample")
# Make a new DatasetRef with the compatible but different DatasetType.
# This should now return a dict.
new_ref = DatasetRef(this_type, metric2_ref.dataId, id=metric2_ref.id, run=metric2_ref.run)
test_dict2 = butler.get(new_ref)
self.assertEqual(get_full_type_name(test_dict2), "dict")
# Get it again with the wrong dataset type definition using get()
# rather than get(). This should be consistent with get()
# behavior and return the type of the DatasetType.
test_dict3 = butler.get(this_type, dataId=dataId, visit=425)
self.assertEqual(get_full_type_name(test_dict3), "dict")
def test_ingest_zip(self) -> None:
"""Create butler, export data, delete data, import from Zip."""
butler, dataset_type = self.create_butler(
run=self.default_run, storageClass="StructuredData", datasetTypeName="metrics"
)
metric = makeExampleMetrics()
refs = []
for visit in (423, 424, 425):
ref = butler.put(metric, dataset_type, instrument="DummyCamComp", visit=visit)
refs.append(ref)
# Retrieve a Zip file.
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdir:
zip = butler.retrieve_artifacts_zip(refs, destination=tmpdir)
# Ingest will fail.
with self.assertRaises(ConflictingDefinitionError):
butler.ingest_zip(zip)
# Clear out the collection.
butler.removeRuns([self.default_run], unstore=True)
self.assertFalse(butler.exists(refs[0]))
butler.ingest_zip(zip, transfer="copy")
# Check that the refs can be read again.
_ = [butler.get(ref) for ref in refs]
uri = butler.getURI(refs[2])
self.assertTrue(uri.exists())
# Delete one dataset. The Zip file should still exist and allow
# remaining refs to be read.
butler.pruneDatasets([refs[0]], purge=True, unstore=True)
self.assertTrue(uri.exists())
metric2 = butler.get(refs[1])
self.assertEqual(metric2, metric, msg=f"{metric2} != {metric}")
butler.removeRuns([self.default_run], unstore=True)
self.assertFalse(uri.exists())
self.assertFalse(butler.exists(refs[-1]))
with self.assertRaises(ValueError):
butler.retrieve_artifacts_zip([], destination=".")
def testIngest(self) -> None:
butler = self.create_empty_butler(run=self.default_run)
# Create and register a DatasetType
dimensions = butler.dimensions.conform(["instrument", "visit", "detector"])
storageClass = self.storageClassFactory.getStorageClass("StructuredDataDictYaml")
datasetTypeName = "metric"
datasetType = self.addDatasetType(datasetTypeName, dimensions, storageClass, butler.registry)
# Add needed Dimensions
butler.registry.insertDimensionData("instrument", {"name": "DummyCamComp"})
butler.registry.insertDimensionData(
"physical_filter", {"instrument": "DummyCamComp", "name": "d-r", "band": "R"}
)