Coverage for python/lsst/daf/butler/tests/_datasetsHelper.py: 32%
60 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-23 09:30 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-23 09:30 +0000
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from __future__ import annotations
24__all__ = (
25 "DatasetTestHelper",
26 "DatastoreTestHelper",
27 "BadWriteFormatter",
28 "BadNoWriteFormatter",
29 "MultiDetectorFormatter",
30)
32import os
33from collections.abc import Iterable, Mapping
34from typing import TYPE_CHECKING, Any
36from lsst.daf.butler import DataCoordinate, DatasetRef, DatasetType, StorageClass
37from lsst.daf.butler.formatters.yaml import YamlFormatter
39if TYPE_CHECKING:
40 from lsst.daf.butler import Config, DatasetId, Datastore, Dimension, DimensionGraph, Registry
43class DatasetTestHelper:
44 """Helper methods for Datasets"""
46 def makeDatasetRef(
47 self,
48 datasetTypeName: str,
49 dimensions: DimensionGraph | Iterable[str | Dimension],
50 storageClass: StorageClass | str,
51 dataId: DataCoordinate | Mapping[str, Any],
52 *,
53 id: DatasetId | None = None,
54 run: str | None = None,
55 conform: bool = True,
56 ) -> DatasetRef:
57 """Make a DatasetType and wrap it in a DatasetRef for a test"""
58 return self._makeDatasetRef(
59 datasetTypeName,
60 dimensions,
61 storageClass,
62 dataId,
63 id=id,
64 run=run,
65 conform=conform,
66 )
68 def _makeDatasetRef(
69 self,
70 datasetTypeName: str,
71 dimensions: DimensionGraph | Iterable[str | Dimension],
72 storageClass: StorageClass | str,
73 dataId: DataCoordinate | Mapping,
74 *,
75 id: DatasetId | None = None,
76 run: str | None = None,
77 conform: bool = True,
78 ) -> DatasetRef:
79 # helper for makeDatasetRef
81 # Pretend we have a parent if this looks like a composite
82 compositeName, componentName = DatasetType.splitDatasetTypeName(datasetTypeName)
83 parentStorageClass = StorageClass("component") if componentName else None
85 datasetType = DatasetType(
86 datasetTypeName, dimensions, storageClass, parentStorageClass=parentStorageClass
87 )
89 if run is None:
90 run = "dummy"
91 if not isinstance(dataId, DataCoordinate):
92 dataId = DataCoordinate.standardize(dataId, graph=datasetType.dimensions)
93 return DatasetRef(datasetType, dataId, id=id, run=run, conform=conform)
96class DatastoreTestHelper:
97 """Helper methods for Datastore tests"""
99 root: str | None
100 config: Config
101 datastoreType: type[Datastore]
102 configFile: str
104 def setUpDatastoreTests(self, registryClass: type[Registry], configClass: type[Config]) -> None:
105 """Shared setUp code for all Datastore tests"""
106 self.registry = registryClass()
107 self.config = configClass(self.configFile)
109 # Some subclasses override the working root directory
110 if self.root is not None:
111 self.datastoreType.setConfigRoot(self.root, self.config, self.config.copy())
113 def makeDatastore(self, sub: str | None = None) -> Datastore:
114 """Make a new Datastore instance of the appropriate type.
116 Parameters
117 ----------
118 sub : str, optional
119 If not None, the returned Datastore will be distinct from any
120 Datastore constructed with a different value of ``sub``. For
121 PosixDatastore, for example, the converse is also true, and ``sub``
122 is used as a subdirectory to form the new root.
124 Returns
125 -------
126 datastore : `Datastore`
127 Datastore constructed by this routine using the supplied
128 optional subdirectory if supported.
129 """
130 config = self.config.copy()
131 if sub is not None and self.root is not None:
132 self.datastoreType.setConfigRoot(os.path.join(self.root, sub), config, self.config)
133 if sub is not None:
134 # Ensure that each datastore gets its own registry
135 registryClass = type(self.registry)
136 registry = registryClass()
137 else:
138 registry = self.registry
139 return self.datastoreType(config=config, bridgeManager=registry.getDatastoreBridgeManager())
142class BadWriteFormatter(YamlFormatter):
143 """A formatter that never works but does leave a file behind."""
145 def _readFile(self, path: str, pytype: type[Any] | None = None) -> Any:
146 raise NotImplementedError("This formatter can not read anything")
148 def _writeFile(self, inMemoryDataset: Any) -> None:
149 """Write an empty file and then raise an exception."""
150 with open(self.fileDescriptor.location.path, "wb"):
151 pass
152 raise RuntimeError("Did not succeed in writing file")
155class BadNoWriteFormatter(BadWriteFormatter):
156 """A formatter that always fails without writing anything."""
158 def _writeFile(self, inMemoryDataset: Any) -> None:
159 raise RuntimeError("Did not writing anything at all")
162class MultiDetectorFormatter(YamlFormatter):
163 def _writeFile(self, inMemoryDataset: Any) -> None:
164 raise NotImplementedError("Can not write")
166 def _fromBytes(self, serializedDataset: bytes, pytype: type[Any] | None = None) -> Any:
167 data = super()._fromBytes(serializedDataset)
168 if self.dataId is None:
169 raise RuntimeError("This formatter requires a dataId")
170 if "detector" not in self.dataId:
171 raise RuntimeError("This formatter requires detector to be present in dataId")
172 key = f"detector{self.dataId['detector']}"
173 assert pytype is not None
174 if key in data:
175 return pytype(data[key])
176 raise RuntimeError(f"Could not find '{key}' in data file")