Coverage for tests/test_templates.py: 12%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

161 statements  

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 

22"""Test file name templating.""" 

23 

24import os.path 

25import unittest 

26 

27from lsst.daf.butler import ( 

28 DatasetRef, 

29 DatasetType, 

30 DimensionGraph, 

31 DimensionUniverse, 

32 FileTemplate, 

33 FileTemplates, 

34 FileTemplatesConfig, 

35 FileTemplateValidationError, 

36 StorageClass, 

37) 

38 

39TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

40 

41PlaceHolder = StorageClass("PlaceHolder") 

42 

43 

44class TestFileTemplates(unittest.TestCase): 

45 """Test creation of paths from templates.""" 

46 

47 def makeDatasetRef( 

48 self, datasetTypeName, dataId=None, storageClassName="DefaultStorageClass", run="run2", conform=True 

49 ): 

50 """Make a simple DatasetRef""" 

51 if dataId is None: 

52 dataId = self.dataId 

53 

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

55 compositeName, componentName = DatasetType.splitDatasetTypeName(datasetTypeName) 

56 parentStorageClass = PlaceHolder if componentName else None 

57 

58 datasetType = DatasetType( 

59 datasetTypeName, 

60 DimensionGraph(self.universe, names=dataId.keys()), 

61 StorageClass(storageClassName), 

62 parentStorageClass=parentStorageClass, 

63 ) 

64 return DatasetRef(datasetType, dataId, id=1, run=run, conform=conform) 

65 

66 def setUp(self): 

67 self.universe = DimensionUniverse() 

68 self.dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "Most Amazing U Filter Ever"} 

69 

70 def assertTemplate(self, template, answer, ref): 

71 fileTmpl = FileTemplate(template) 

72 path = fileTmpl.format(ref) 

73 self.assertEqual(path, answer) 

74 

75 def testBasic(self): 

76 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}" 

77 self.assertTemplate( 

78 tmplstr, 

79 "run2/calexp/00052/Most_Amazing_U_Filter_Ever", 

80 self.makeDatasetRef("calexp", conform=False), 

81 ) 

82 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail" 

83 self.assertTemplate( 

84 tmplstr, 

85 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail", 

86 self.makeDatasetRef("calexp", conform=False), 

87 ) 

88 

89 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}" 

90 self.assertTemplate( 

91 tmplstr, 

92 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run2", 

93 self.makeDatasetRef("calexp", conform=False), 

94 ) 

95 self.assertTemplate( 

96 tmplstr, 

97 "run_2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2", 

98 self.makeDatasetRef("calexp", run="run/2", conform=False), 

99 ) 

100 

101 # Retain any "/" in run 

102 tmplstr = "{run:/}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}" 

103 self.assertTemplate( 

104 tmplstr, 

105 "run/2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2", 

106 self.makeDatasetRef("calexp", run="run/2", conform=False), 

107 ) 

108 

109 # Check that "." are replaced in the file basename, but not directory. 

110 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "g.10"} 

111 self.assertTemplate( 

112 tmplstr, 

113 "run.2/calexp/00052/g_10-trail-run_2", 

114 self.makeDatasetRef("calexp", run="run.2", dataId=dataId, conform=False), 

115 ) 

116 

117 with self.assertRaises(FileTemplateValidationError): 

118 FileTemplate("no fields at all") 

119 

120 with self.assertRaises(FileTemplateValidationError): 

121 FileTemplate("{visit}") 

122 

123 with self.assertRaises(FileTemplateValidationError): 

124 FileTemplate("{run}_{datasetType}") 

125 

126 def testRunOrCollectionNeeded(self): 

127 tmplstr = "{datasetType}/{visit:05d}/{physical_filter}" 

128 with self.assertRaises(FileTemplateValidationError): 

129 self.assertTemplate(tmplstr, "run2/calexp/00052/U", self.makeDatasetRef("calexp")) 

130 

131 def testOptional(self): 

132 """Optional units in templates.""" 

133 ref = self.makeDatasetRef("calexp", conform=False) 

134 tmplstr = "{run}/{datasetType}/v{visit:05d}_f{physical_filter:?}" 

135 self.assertTemplate( 

136 tmplstr, 

137 "run2/calexp/v00052_fMost_Amazing_U_Filter_Ever", 

138 self.makeDatasetRef("calexp", conform=False), 

139 ) 

140 

141 du = {"visit": 48, "tract": 265, "skymap": "big", "instrument": "dummy"} 

142 self.assertTemplate(tmplstr, "run2/calexpT/v00048", self.makeDatasetRef("calexpT", du, conform=False)) 

143 

144 # Ensure that this returns a relative path even if the first field 

145 # is optional 

146 tmplstr = "{run}/{tract:?}/{visit:?}/f{physical_filter}" 

147 self.assertTemplate(tmplstr, "run2/52/fMost_Amazing_U_Filter_Ever", ref) 

148 

149 # Ensure that // from optionals are converted to singles 

150 tmplstr = "{run}/{datasetType}/{patch:?}/{tract:?}/f{physical_filter}" 

151 self.assertTemplate(tmplstr, "run2/calexp/fMost_Amazing_U_Filter_Ever", ref) 

152 

153 # Optionals with some text between fields 

154 tmplstr = "{run}/{datasetType}/p{patch:?}_t{tract:?}/f{physical_filter}" 

155 self.assertTemplate(tmplstr, "run2/calexp/p/fMost_Amazing_U_Filter_Ever", ref) 

156 tmplstr = "{run}/{datasetType}/p{patch:?}_t{visit:04d?}/f{physical_filter}" 

157 self.assertTemplate(tmplstr, "run2/calexp/p_t0052/fMost_Amazing_U_Filter_Ever", ref) 

158 

159 def testComponent(self): 

160 """Test handling of components in templates.""" 

161 refMetricOutput = self.makeDatasetRef("metric.output") 

162 refMetric = self.makeDatasetRef("metric") 

163 refMaskedImage = self.makeDatasetRef("calexp.maskedimage.variance") 

164 refWcs = self.makeDatasetRef("calexp.wcs") 

165 

166 tmplstr = "{run}_c_{component}_v{visit}" 

167 self.assertTemplate(tmplstr, "run2_c_output_v52", refMetricOutput) 

168 

169 # We want this template to have both a directory and basename, to 

170 # test that the right parts of the output are replaced. 

171 tmplstr = "{component:?}/{run}_{component:?}_{visit}" 

172 self.assertTemplate(tmplstr, "run2_52", refMetric) 

173 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput) 

174 self.assertTemplate(tmplstr, "maskedimage.variance/run2_maskedimage_variance_52", refMaskedImage) 

175 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput) 

176 

177 # Providing a component but not using it 

178 tmplstr = "{run}/{datasetType}/v{visit:05d}" 

179 with self.assertRaises(KeyError): 

180 self.assertTemplate(tmplstr, "", refWcs) 

181 

182 def testFields(self): 

183 # Template, mandatory fields, optional non-special fields, 

184 # special fields, optional special fields 

185 testData = ( 

186 ( 

187 "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail", 

188 set(["visit", "physical_filter"]), 

189 set(), 

190 set(["run", "datasetType"]), 

191 set(), 

192 ), 

193 ( 

194 "{run}/{component:?}_{visit}", 

195 set(["visit"]), 

196 set(), 

197 set(["run"]), 

198 set(["component"]), 

199 ), 

200 ( 

201 "{run}/{component:?}_{visit:?}_{physical_filter}_{instrument}_{datasetType}", 

202 set(["physical_filter", "instrument"]), 

203 set(["visit"]), 

204 set(["run", "datasetType"]), 

205 set(["component"]), 

206 ), 

207 ) 

208 for tmplstr, mandatory, optional, special, optionalSpecial in testData: 

209 with self.subTest(template=tmplstr): 

210 tmpl = FileTemplate(tmplstr) 

211 fields = tmpl.fields() 

212 self.assertEqual(fields, mandatory) 

213 fields = tmpl.fields(optionals=True) 

214 self.assertEqual(fields, mandatory | optional) 

215 fields = tmpl.fields(specials=True) 

216 self.assertEqual(fields, mandatory | special) 

217 fields = tmpl.fields(specials=True, optionals=True) 

218 self.assertEqual(fields, mandatory | special | optional | optionalSpecial) 

219 

220 def testSimpleConfig(self): 

221 """Test reading from config file""" 

222 configRoot = os.path.join(TESTDIR, "config", "templates") 

223 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml")) 

224 templates = FileTemplates(config1, universe=self.universe) 

225 ref = self.makeDatasetRef("calexp") 

226 tmpl = templates.getTemplate(ref) 

227 self.assertIsInstance(tmpl, FileTemplate) 

228 

229 # This config file should not allow defaulting 

230 ref2 = self.makeDatasetRef("unknown") 

231 with self.assertRaises(KeyError): 

232 templates.getTemplate(ref2) 

233 

234 # This should fall through the datasetTypeName check and use 

235 # StorageClass instead 

236 ref3 = self.makeDatasetRef("unknown2", storageClassName="StorageClassX") 

237 tmplSc = templates.getTemplate(ref3) 

238 self.assertIsInstance(tmplSc, FileTemplate) 

239 

240 # Try with a component: one with defined formatter and one without 

241 refWcs = self.makeDatasetRef("calexp.wcs") 

242 refImage = self.makeDatasetRef("calexp.image") 

243 tmplCalexp = templates.getTemplate(ref) 

244 tmplWcs = templates.getTemplate(refWcs) # Should be special 

245 tmpl_image = templates.getTemplate(refImage) 

246 self.assertIsInstance(tmplCalexp, FileTemplate) 

247 self.assertIsInstance(tmpl_image, FileTemplate) 

248 self.assertIsInstance(tmplWcs, FileTemplate) 

249 self.assertEqual(tmplCalexp, tmpl_image) 

250 self.assertNotEqual(tmplCalexp, tmplWcs) 

251 

252 # Check dimensions lookup order. 

253 # The order should be: dataset type name, dimension, storage class 

254 # This one will not match name but might match storage class. 

255 # It should match dimensions 

256 refDims = self.makeDatasetRef( 

257 "nomatch", dataId={"instrument": "LSST", "physical_filter": "z"}, storageClassName="StorageClassX" 

258 ) 

259 tmplDims = templates.getTemplate(refDims) 

260 self.assertIsInstance(tmplDims, FileTemplate) 

261 self.assertNotEqual(tmplDims, tmplSc) 

262 

263 # Test that instrument overrides retrieve specialist templates 

264 refPvi = self.makeDatasetRef("pvi") 

265 refPviHsc = self.makeDatasetRef("pvi", dataId={"instrument": "HSC", "physical_filter": "z"}) 

266 refPviLsst = self.makeDatasetRef("pvi", dataId={"instrument": "LSST", "physical_filter": "z"}) 

267 

268 tmplPvi = templates.getTemplate(refPvi) 

269 tmplPviHsc = templates.getTemplate(refPviHsc) 

270 tmplPviLsst = templates.getTemplate(refPviLsst) 

271 self.assertEqual(tmplPvi, tmplPviLsst) 

272 self.assertNotEqual(tmplPvi, tmplPviHsc) 

273 

274 # Have instrument match and dimensions look up with no name match 

275 refNoPviHsc = self.makeDatasetRef( 

276 "pvix", dataId={"instrument": "HSC", "physical_filter": "z"}, storageClassName="StorageClassX" 

277 ) 

278 tmplNoPviHsc = templates.getTemplate(refNoPviHsc) 

279 self.assertNotEqual(tmplNoPviHsc, tmplDims) 

280 self.assertNotEqual(tmplNoPviHsc, tmplPviHsc) 

281 

282 # Format config file with defaulting 

283 config2 = FileTemplatesConfig(os.path.join(configRoot, "templates-withdefault.yaml")) 

284 templates = FileTemplates(config2, universe=self.universe) 

285 tmpl = templates.getTemplate(ref2) 

286 self.assertIsInstance(tmpl, FileTemplate) 

287 

288 # Format config file with bad format string 

289 with self.assertRaises(FileTemplateValidationError): 

290 FileTemplates(os.path.join(configRoot, "templates-bad.yaml"), universe=self.universe) 

291 

292 # Config file with no defaulting mentioned 

293 config3 = os.path.join(configRoot, "templates-nodefault2.yaml") 

294 templates = FileTemplates(config3, universe=self.universe) 

295 with self.assertRaises(KeyError): 

296 templates.getTemplate(ref2) 

297 

298 # Try again but specify a default in the constructor 

299 default = "{run}/{datasetType}/{physical_filter}" 

300 templates = FileTemplates(config3, default=default, universe=self.universe) 

301 tmpl = templates.getTemplate(ref2) 

302 self.assertEqual(tmpl.template, default) 

303 

304 def testValidation(self): 

305 configRoot = os.path.join(TESTDIR, "config", "templates") 

306 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml")) 

307 templates = FileTemplates(config1, universe=self.universe) 

308 

309 entities = {} 

310 entities["calexp"] = self.makeDatasetRef( 

311 "calexp", 

312 storageClassName="StorageClassX", 

313 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 52}, 

314 ) 

315 

316 with self.assertLogs(level="WARNING") as cm: 

317 templates.validateTemplates(entities.values(), logFailures=True) 

318 self.assertIn("Unchecked keys", cm.output[0]) 

319 self.assertIn("StorageClassX", cm.output[0]) 

320 

321 entities["pvi"] = self.makeDatasetRef( 

322 "pvi", storageClassName="StorageClassX", dataId={"instrument": "dummy", "physical_filter": "i"} 

323 ) 

324 entities["StorageClassX"] = self.makeDatasetRef( 

325 "storageClass", storageClassName="StorageClassX", dataId={"instrument": "dummy", "visit": 2} 

326 ) 

327 entities["calexp.wcs"] = self.makeDatasetRef( 

328 "calexp.wcs", 

329 storageClassName="StorageClassX", 

330 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 23}, 

331 conform=False, 

332 ) 

333 

334 entities["instrument+physical_filter"] = self.makeDatasetRef( 

335 "filter_inst", 

336 storageClassName="StorageClassX", 

337 dataId={"physical_filter": "i", "instrument": "SCUBA"}, 

338 ) 

339 entities["hsc+pvi"] = self.makeDatasetRef( 

340 "pvi", storageClassName="StorageClassX", dataId={"physical_filter": "i", "instrument": "HSC"} 

341 ) 

342 

343 entities["hsc+instrument+physical_filter"] = self.makeDatasetRef( 

344 "filter_inst", 

345 storageClassName="StorageClassX", 

346 dataId={"physical_filter": "i", "instrument": "HSC"}, 

347 ) 

348 

349 templates.validateTemplates(entities.values(), logFailures=True) 

350 

351 # Rerun but with a failure 

352 entities["pvi"] = self.makeDatasetRef("pvi", storageClassName="StorageClassX", dataId={"band": "i"}) 

353 with self.assertRaises(FileTemplateValidationError): 

354 with self.assertLogs(level="FATAL"): 

355 templates.validateTemplates(entities.values(), logFailures=True) 

356 

357 

358if __name__ == "__main__": 358 ↛ 359line 358 didn't jump to line 359, because the condition on line 358 was never true

359 unittest.main()