Coverage for python/lsst/daf/butler/tests/_datasetsHelper.py: 32%
60 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-10-02 08:00 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-10-02 08:00 +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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28from __future__ import annotations
30__all__ = (
31 "DatasetTestHelper",
32 "DatastoreTestHelper",
33 "BadWriteFormatter",
34 "BadNoWriteFormatter",
35 "MultiDetectorFormatter",
36)
38import os
39from collections.abc import Iterable, Mapping
40from typing import TYPE_CHECKING, Any
42from lsst.daf.butler import DataCoordinate, DatasetRef, DatasetType, StorageClass
43from lsst.daf.butler.formatters.yaml import YamlFormatter
45if TYPE_CHECKING:
46 from lsst.daf.butler import Config, DatasetId, Datastore, Dimension, DimensionGraph
47 from lsst.daf.butler.registry import _ButlerRegistry
50class DatasetTestHelper:
51 """Helper methods for Datasets."""
53 def makeDatasetRef(
54 self,
55 datasetTypeName: str,
56 dimensions: DimensionGraph | Iterable[str | Dimension],
57 storageClass: StorageClass | str,
58 dataId: DataCoordinate | Mapping[str, Any],
59 *,
60 id: DatasetId | None = None,
61 run: str | None = None,
62 conform: bool = True,
63 ) -> DatasetRef:
64 """Make a DatasetType and wrap it in a DatasetRef for a test."""
65 return self._makeDatasetRef(
66 datasetTypeName,
67 dimensions,
68 storageClass,
69 dataId,
70 id=id,
71 run=run,
72 conform=conform,
73 )
75 def _makeDatasetRef(
76 self,
77 datasetTypeName: str,
78 dimensions: DimensionGraph | Iterable[str | Dimension],
79 storageClass: StorageClass | str,
80 dataId: DataCoordinate | Mapping,
81 *,
82 id: DatasetId | None = None,
83 run: str | None = None,
84 conform: bool = True,
85 ) -> DatasetRef:
86 # helper for makeDatasetRef
88 # Pretend we have a parent if this looks like a composite
89 compositeName, componentName = DatasetType.splitDatasetTypeName(datasetTypeName)
90 parentStorageClass = StorageClass("component") if componentName else None
92 datasetType = DatasetType(
93 datasetTypeName, dimensions, storageClass, parentStorageClass=parentStorageClass
94 )
96 if run is None:
97 run = "dummy"
98 if not isinstance(dataId, DataCoordinate):
99 dataId = DataCoordinate.standardize(dataId, graph=datasetType.dimensions)
100 return DatasetRef(datasetType, dataId, id=id, run=run, conform=conform)
103class DatastoreTestHelper:
104 """Helper methods for Datastore tests."""
106 root: str | None
107 config: Config
108 datastoreType: type[Datastore]
109 configFile: str
111 def setUpDatastoreTests(self, registryClass: type[_ButlerRegistry], configClass: type[Config]) -> None:
112 """Shared setUp code for all Datastore tests."""
113 self.registry = registryClass()
114 self.config = configClass(self.configFile)
116 # Some subclasses override the working root directory
117 if self.root is not None:
118 self.datastoreType.setConfigRoot(self.root, self.config, self.config.copy())
120 def makeDatastore(self, sub: str | None = None) -> Datastore:
121 """Make a new Datastore instance of the appropriate type.
123 Parameters
124 ----------
125 sub : str, optional
126 If not None, the returned Datastore will be distinct from any
127 Datastore constructed with a different value of ``sub``. For
128 PosixDatastore, for example, the converse is also true, and ``sub``
129 is used as a subdirectory to form the new root.
131 Returns
132 -------
133 datastore : `Datastore`
134 Datastore constructed by this routine using the supplied
135 optional subdirectory if supported.
136 """
137 config = self.config.copy()
138 if sub is not None and self.root is not None:
139 self.datastoreType.setConfigRoot(os.path.join(self.root, sub), config, self.config)
140 if sub is not None:
141 # Ensure that each datastore gets its own registry
142 registryClass = type(self.registry)
143 registry = registryClass()
144 else:
145 registry = self.registry
146 return self.datastoreType(config=config, bridgeManager=registry.getDatastoreBridgeManager())
149class BadWriteFormatter(YamlFormatter):
150 """A formatter that never works but does leave a file behind."""
152 def _readFile(self, path: str, pytype: type[Any] | None = None) -> Any:
153 raise NotImplementedError("This formatter can not read anything")
155 def _writeFile(self, inMemoryDataset: Any) -> None:
156 """Write an empty file and then raise an exception."""
157 with open(self.fileDescriptor.location.path, "wb"):
158 pass
159 raise RuntimeError("Did not succeed in writing file")
162class BadNoWriteFormatter(BadWriteFormatter):
163 """A formatter that always fails without writing anything."""
165 def _writeFile(self, inMemoryDataset: Any) -> None:
166 raise RuntimeError("Did not writing anything at all")
169class MultiDetectorFormatter(YamlFormatter):
170 """A formatter that requires a detector to be specified in the dataID."""
172 def _writeFile(self, inMemoryDataset: Any) -> None:
173 raise NotImplementedError("Can not write")
175 def _fromBytes(self, serializedDataset: bytes, pytype: type[Any] | None = None) -> Any:
176 data = super()._fromBytes(serializedDataset)
177 if self.dataId is None:
178 raise RuntimeError("This formatter requires a dataId")
179 if "detector" not in self.dataId:
180 raise RuntimeError("This formatter requires detector to be present in dataId")
181 key = f"detector{self.dataId['detector']}"
182 assert pytype is not None
183 if key in data:
184 return pytype(data[key])
185 raise RuntimeError(f"Could not find '{key}' in data file")