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

61 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-05 03:17 -0700

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 

33import uuid 

34from collections.abc import Iterable 

35from typing import TYPE_CHECKING, Any 

36 

37from lsst.daf.butler import DatasetRef, DatasetType, StorageClass 

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

39 

40if TYPE_CHECKING: 

41 from lsst.daf.butler import ( 

42 Config, 

43 DataCoordinate, 

44 DatasetId, 

45 Datastore, 

46 Dimension, 

47 DimensionGraph, 

48 Registry, 

49 ) 

50 

51 

52class DatasetTestHelper: 

53 """Helper methods for Datasets""" 

54 

55 def makeDatasetRef( 

56 self, 

57 datasetTypeName: str, 

58 dimensions: DimensionGraph | Iterable[str | Dimension], 

59 storageClass: StorageClass | str, 

60 dataId: DataCoordinate, 

61 *, 

62 id: DatasetId | None = None, 

63 run: str | None = None, 

64 conform: bool = True, 

65 ) -> DatasetRef: 

66 """Make a DatasetType and wrap it in a DatasetRef for a test""" 

67 return self._makeDatasetRef( 

68 datasetTypeName, dimensions, storageClass, dataId, id=id, run=run, conform=conform 

69 ) 

70 

71 def _makeDatasetRef( 

72 self, 

73 datasetTypeName: str, 

74 dimensions: DimensionGraph | Iterable[str | Dimension], 

75 storageClass: StorageClass | str, 

76 dataId: DataCoordinate, 

77 *, 

78 id: DatasetId | None = None, 

79 run: str | None = None, 

80 conform: bool = True, 

81 ) -> DatasetRef: 

82 # helper for makeDatasetRef 

83 

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

85 compositeName, componentName = DatasetType.splitDatasetTypeName(datasetTypeName) 

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

87 

88 datasetType = DatasetType( 

89 datasetTypeName, dimensions, storageClass, parentStorageClass=parentStorageClass 

90 ) 

91 

92 if run is None: 

93 run = "dummy" 

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

95 

96 

97class DatastoreTestHelper: 

98 """Helper methods for Datastore tests""" 

99 

100 root: str 

101 id: DatasetId 

102 config: Config 

103 datastoreType: type[Datastore] 

104 configFile: str 

105 

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

107 """Shared setUp code for all Datastore tests""" 

108 self.registry = registryClass() 

109 

110 # Need to keep ID for each datasetRef since we have no butler 

111 # for these tests 

112 self.id = uuid.uuid4() 

113 

114 self.config = configClass(self.configFile) 

115 

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

119 

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

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

122 

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. 

130 

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

147 

148 

149class BadWriteFormatter(YamlFormatter): 

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

151 

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

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

154 

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

160 

161 

162class BadNoWriteFormatter(BadWriteFormatter): 

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

164 

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

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

167 

168 

169class MultiDetectorFormatter(YamlFormatter): 

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

171 raise NotImplementedError("Can not write") 

172 

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

174 data = super()._fromBytes(serializedDataset) 

175 if self.dataId is None: 

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

177 if "detector" not in self.dataId: 

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

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

180 assert pytype is not None 

181 if key in data: 

182 return pytype(data[key]) 

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