Coverage for python/lsst/daf/butler/tests/_datasetsHelper.py: 32%

60 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-16 10:44 +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/>. 

27 

28from __future__ import annotations 

29 

30__all__ = ( 

31 "DatasetTestHelper", 

32 "DatastoreTestHelper", 

33 "BadWriteFormatter", 

34 "BadNoWriteFormatter", 

35 "MultiDetectorFormatter", 

36) 

37 

38import os 

39from collections.abc import Iterable, Mapping 

40from typing import TYPE_CHECKING, Any 

41 

42from lsst.daf.butler import DataCoordinate, DatasetRef, DatasetType, DimensionGroup, StorageClass 

43from lsst.daf.butler.formatters.yaml import YamlFormatter 

44 

45if TYPE_CHECKING: 

46 from lsst.daf.butler import Config, DatasetId, Datastore, Dimension, DimensionGraph 

47 

48 

49class DatasetTestHelper: 

50 """Helper methods for Datasets.""" 

51 

52 def makeDatasetRef( 

53 self, 

54 datasetTypeName: str, 

55 dimensions: DimensionGroup | DimensionGraph | Iterable[str | Dimension], 

56 storageClass: StorageClass | str, 

57 dataId: DataCoordinate | Mapping[str, Any], 

58 *, 

59 id: DatasetId | None = None, 

60 run: str | None = None, 

61 conform: bool = True, 

62 ) -> DatasetRef: 

63 """Make a DatasetType and wrap it in a DatasetRef for a test. 

64 

65 Parameters 

66 ---------- 

67 datasetTypeName : `str` 

68 The name of the dataset type. 

69 dimensions : `DimensionGroup` or `~collections.abc.Iterable` of `str` \ 

70 or `Dimension` 

71 The dimensions to use for this dataset type. 

72 storageClass : `StorageClass` or `str` 

73 The relevant storage class. 

74 dataId : `DataCoordinate` or `~collections.abc.Mapping` 

75 The data ID of this ref. 

76 id : `DatasetId` or `None`, optional 

77 The Id of this ref. Will be assigned automatically. 

78 run : `str` or `None`, optional 

79 The run for this ref. Will be assigned a default value if `None`. 

80 conform : `bool`, optional 

81 Whther to force the dataID to be checked for conformity with 

82 the provided dimensions. 

83 

84 Returns 

85 ------- 

86 ref : `DatasetRef` 

87 The new ref. 

88 """ 

89 return self._makeDatasetRef( 

90 datasetTypeName, 

91 dimensions, 

92 storageClass, 

93 dataId, 

94 id=id, 

95 run=run, 

96 conform=conform, 

97 ) 

98 

99 def _makeDatasetRef( 

100 self, 

101 datasetTypeName: str, 

102 dimensions: DimensionGroup | DimensionGraph | Iterable[str | Dimension], 

103 storageClass: StorageClass | str, 

104 dataId: DataCoordinate | Mapping, 

105 *, 

106 id: DatasetId | None = None, 

107 run: str | None = None, 

108 conform: bool = True, 

109 ) -> DatasetRef: 

110 # helper for makeDatasetRef 

111 

112 # Pretend we have a parent if this looks like a composite 

113 compositeName, componentName = DatasetType.splitDatasetTypeName(datasetTypeName) 

114 parentStorageClass = StorageClass("component") if componentName else None 

115 

116 datasetType = DatasetType( 

117 datasetTypeName, dimensions, storageClass, parentStorageClass=parentStorageClass 

118 ) 

119 

120 if run is None: 

121 run = "dummy" 

122 if not isinstance(dataId, DataCoordinate): 

123 dataId = DataCoordinate.standardize(dataId, dimensions=datasetType.dimensions) 

124 return DatasetRef(datasetType, dataId, id=id, run=run, conform=conform) 

125 

126 

127class DatastoreTestHelper: 

128 """Helper methods for Datastore tests.""" 

129 

130 root: str | None 

131 config: Config 

132 datastoreType: type[Datastore] 

133 configFile: str 

134 

135 def setUpDatastoreTests(self, registryClass: type, configClass: type[Config]) -> None: 

136 """Shared setUp code for all Datastore tests. 

137 

138 Parameters 

139 ---------- 

140 registryClass : `type` 

141 Type of registry to use. 

142 configClass : `type` 

143 Type of config to use. 

144 """ 

145 self.registry = registryClass() 

146 self.config = configClass(self.configFile) 

147 

148 # Some subclasses override the working root directory 

149 if self.root is not None: 

150 self.datastoreType.setConfigRoot(self.root, self.config, self.config.copy()) 

151 

152 def makeDatastore(self, sub: str | None = None) -> Datastore: 

153 """Make a new Datastore instance of the appropriate type. 

154 

155 Parameters 

156 ---------- 

157 sub : `str`, optional 

158 If not None, the returned Datastore will be distinct from any 

159 Datastore constructed with a different value of ``sub``. For 

160 PosixDatastore, for example, the converse is also true, and ``sub`` 

161 is used as a subdirectory to form the new root. 

162 

163 Returns 

164 ------- 

165 datastore : `Datastore` 

166 Datastore constructed by this routine using the supplied 

167 optional subdirectory if supported. 

168 """ 

169 config = self.config.copy() 

170 if sub is not None and self.root is not None: 

171 self.datastoreType.setConfigRoot(os.path.join(self.root, sub), config, self.config) 

172 if sub is not None: 

173 # Ensure that each datastore gets its own registry 

174 registryClass = type(self.registry) 

175 registry = registryClass() 

176 else: 

177 registry = self.registry 

178 return self.datastoreType(config=config, bridgeManager=registry.getDatastoreBridgeManager()) 

179 

180 

181class BadWriteFormatter(YamlFormatter): 

182 """A formatter that never works but does leave a file behind.""" 

183 

184 def _readFile(self, path: str, pytype: type[Any] | None = None) -> Any: 

185 raise NotImplementedError("This formatter can not read anything") 

186 

187 def _writeFile(self, inMemoryDataset: Any) -> None: 

188 """Write an empty file and then raise an exception.""" 

189 with open(self.fileDescriptor.location.path, "wb"): 

190 pass 

191 raise RuntimeError("Did not succeed in writing file") 

192 

193 

194class BadNoWriteFormatter(BadWriteFormatter): 

195 """A formatter that always fails without writing anything.""" 

196 

197 def _writeFile(self, inMemoryDataset: Any) -> None: 

198 raise RuntimeError("Did not writing anything at all") 

199 

200 

201class MultiDetectorFormatter(YamlFormatter): 

202 """A formatter that requires a detector to be specified in the dataID.""" 

203 

204 def _writeFile(self, inMemoryDataset: Any) -> None: 

205 raise NotImplementedError("Can not write") 

206 

207 def _fromBytes(self, serializedDataset: bytes, pytype: type[Any] | None = None) -> Any: 

208 data = super()._fromBytes(serializedDataset) 

209 if self.dataId is None: 

210 raise RuntimeError("This formatter requires a dataId") 

211 if "detector" not in self.dataId: 

212 raise RuntimeError("This formatter requires detector to be present in dataId") 

213 key = f"detector{self.dataId['detector']}" 

214 assert pytype is not None 

215 if key in data: 

216 return pytype(data[key]) 

217 raise RuntimeError(f"Could not find '{key}' in data file")