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

60 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-14 19:21 +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/>. 

21 

22from __future__ import annotations 

23 

24__all__ = ( 

25 "DatasetTestHelper", 

26 "DatastoreTestHelper", 

27 "BadWriteFormatter", 

28 "BadNoWriteFormatter", 

29 "MultiDetectorFormatter", 

30) 

31 

32import os 

33from collections.abc import Iterable, Mapping 

34from typing import TYPE_CHECKING, Any 

35 

36from lsst.daf.butler import DataCoordinate, DatasetRef, DatasetType, StorageClass 

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

38 

39if TYPE_CHECKING: 

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

41 

42 

43class DatasetTestHelper: 

44 """Helper methods for Datasets.""" 

45 

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 ) 

67 

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 

80 

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 

84 

85 datasetType = DatasetType( 

86 datasetTypeName, dimensions, storageClass, parentStorageClass=parentStorageClass 

87 ) 

88 

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) 

94 

95 

96class DatastoreTestHelper: 

97 """Helper methods for Datastore tests.""" 

98 

99 root: str | None 

100 config: Config 

101 datastoreType: type[Datastore] 

102 configFile: str 

103 

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) 

108 

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()) 

112 

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

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

115 

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. 

123 

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()) 

140 

141 

142class BadWriteFormatter(YamlFormatter): 

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

144 

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

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

147 

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") 

153 

154 

155class BadNoWriteFormatter(BadWriteFormatter): 

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

157 

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

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

160 

161 

162class MultiDetectorFormatter(YamlFormatter): 

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

164 

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

166 raise NotImplementedError("Can not write") 

167 

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

169 data = super()._fromBytes(serializedDataset) 

170 if self.dataId is None: 

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

172 if "detector" not in self.dataId: 

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

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

175 assert pytype is not None 

176 if key in data: 

177 return pytype(data[key]) 

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