Hide keyboard shortcuts

Hot-keys 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

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 

22import unittest 

23import os 

24import contextlib 

25import collections 

26import itertools 

27from pathlib import Path 

28 

29from lsst.daf.butler import ConfigSubset, Config 

30from lsst.daf.butler.tests.utils import makeTestTempDir, removeTestTempDir 

31 

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

33 

34 

35@contextlib.contextmanager 

36def modified_environment(**environ): 

37 """ 

38 Temporarily set environment variables. 

39 

40 >>> with modified_environment(DAF_BUTLER_CONFIG_PATHS="/somewhere"): 

41 ... os.environ["DAF_BUTLER_CONFIG_PATHS"] == "/somewhere" 

42 True 

43 

44 >>> "DAF_BUTLER_CONFIG_PATHS" != "/somewhere" 

45 True 

46 

47 Parameters 

48 ---------- 

49 environ : `dict` 

50 Key value pairs of environment variables to temporarily set. 

51 """ 

52 old_environ = dict(os.environ) 

53 os.environ.update(environ) 

54 try: 

55 yield 

56 finally: 

57 os.environ.clear() 

58 os.environ.update(old_environ) 

59 

60 

61class ExampleWithConfigFileReference: 

62 defaultConfigFile = "viacls.yaml" 

63 

64 

65class ExampleWithConfigFileReference2: 

66 defaultConfigFile = "viacls2.yaml" 

67 

68 

69class ConfigTest(ConfigSubset): 

70 component = "comp" 

71 requiredKeys = ("item1", "item2") 

72 defaultConfigFile = "testconfig.yaml" 

73 

74 

75class ConfigTestPathlib(ConfigTest): 

76 defaultConfigFile = Path("testconfig.yaml") 

77 

78 

79class ConfigTestEmpty(ConfigTest): 

80 defaultConfigFile = "testconfig_empty.yaml" 

81 requiredKeys = () 

82 

83 

84class ConfigTestButlerDir(ConfigTest): 

85 defaultConfigFile = "testConfigs/testconfig.yaml" 

86 

87 

88class ConfigTestNoDefaults(ConfigTest): 

89 defaultConfigFile = None 

90 requiredKeys = () 

91 

92 

93class ConfigTestAbsPath(ConfigTest): 

94 defaultConfigFile = None 

95 requiredKeys = () 

96 

97 

98class ConfigTestCls(ConfigTest): 

99 defaultConfigFile = "withcls.yaml" 

100 

101 

102class ConfigTestCase(unittest.TestCase): 

103 """Tests of simple Config""" 

104 

105 def testBadConfig(self): 

106 for badArg in ([], # Bad argument 

107 __file__, # Bad file extension for existing file 

108 ): 

109 with self.assertRaises(RuntimeError): 

110 Config(badArg) 

111 for badArg in ("file.fits", # File that does not exist with bad extension 

112 "b/c/d/", # Directory that does not exist 

113 "file.yaml", # Good extension for missing file 

114 ): 

115 with self.assertRaises(FileNotFoundError): 

116 Config(badArg) 

117 

118 def testBasics(self): 

119 c = Config({"1": 2, "3": 4, "key3": 6, "dict": {"a": 1, "b": 2}}) 

120 pretty = c.ppprint() 

121 self.assertIn("key3", pretty) 

122 r = repr(c) 

123 self.assertIn("key3", r) 

124 regex = r"^Config\(\{.*\}\)$" 

125 self.assertRegex(r, regex) 

126 c2 = eval(r) 

127 self.assertIn("1", c) 

128 for n in c.names(): 

129 self.assertEqual(c2[n], c[n]) 

130 self.assertEqual(c, c2) 

131 s = str(c) 

132 self.assertIn("\n", s) 

133 self.assertNotRegex(s, regex) 

134 

135 self.assertCountEqual(c.keys(), ["1", "3", "key3", "dict"]) 

136 self.assertEqual(list(c), list(c.keys())) 

137 self.assertEqual(list(c.values()), [c[k] for k in c.keys()]) 

138 self.assertEqual(list(c.items()), [(k, c[k]) for k in c.keys()]) 

139 

140 newKeys = ("key4", ".dict.q", ("dict", "r"), "5") 

141 oldKeys = ("key3", ".dict.a", ("dict", "b"), "3") 

142 remainingKey = "1" 

143 

144 # Check get with existing key 

145 for k in oldKeys: 

146 self.assertEqual(c.get(k, "missing"), c[k]) 

147 

148 # Check get, pop with nonexistent key 

149 for k in newKeys: 

150 self.assertEqual(c.get(k, "missing"), "missing") 

151 self.assertEqual(c.pop(k, "missing"), "missing") 

152 

153 # Check setdefault with existing key 

154 for k in oldKeys: 

155 c.setdefault(k, 8) 

156 self.assertNotEqual(c[k], 8) 

157 

158 # Check setdefault with nonexistent key (mutates c, adding newKeys) 

159 for k in newKeys: 

160 c.setdefault(k, 8) 

161 self.assertEqual(c[k], 8) 

162 

163 # Check pop with existing key (mutates c, removing newKeys) 

164 for k in newKeys: 

165 v = c[k] 

166 self.assertEqual(c.pop(k, "missing"), v) 

167 

168 # Check deletion (mutates c, removing oldKeys) 

169 for k in ("key3", ".dict.a", ("dict", "b"), "3"): 

170 self.assertIn(k, c) 

171 del c[k] 

172 self.assertNotIn(k, c) 

173 

174 # Check that `dict` still exists, but is now empty (then remove 

175 # it, mutatic c) 

176 self.assertIn("dict", c) 

177 del c["dict"] 

178 

179 # Check popitem (mutates c, removing remainingKey) 

180 v = c[remainingKey] 

181 self.assertEqual(c.popitem(), (remainingKey, v)) 

182 

183 # Check that c is now empty 

184 self.assertFalse(c) 

185 

186 def testDict(self): 

187 """Test toDict()""" 

188 c1 = Config({"a": {"b": 1}, "c": 2}) 

189 self.assertIsInstance(c1["a"], Config) 

190 d1 = c1.toDict() 

191 self.assertIsInstance(d1["a"], dict) 

192 self.assertEqual(d1["a"], c1["a"]) 

193 

194 # Modifying one does not change the other 

195 d1["a"]["c"] = 2 

196 self.assertNotEqual(d1["a"], c1["a"]) 

197 

198 def assertSplit(self, answer, *args): 

199 """Helper function to compare string splitting""" 

200 for s in (answer, *args): 

201 split = Config._splitIntoKeys(s) 

202 self.assertEqual(split, answer) 

203 

204 def testSplitting(self): 

205 """Test of the internal splitting API.""" 

206 # Try lots of keys that will return the same answer 

207 answer = ["a", "b", "c", "d"] 

208 self.assertSplit(answer, ".a.b.c.d", ":a:b:c:d", "\ta\tb\tc\td", "\ra\rb\rc\rd") 

209 

210 answer = ["a", "calexp.wcs", "b"] 

211 self.assertSplit(answer, r".a.calexp\.wcs.b", ":a:calexp.wcs:b") 

212 

213 self.assertSplit(["a.b.c"]) 

214 self.assertSplit(["a", r"b\.c"], r"_a_b\.c") 

215 

216 # Escaping a backslash before a delimiter currently fails 

217 with self.assertRaises(ValueError): 

218 Config._splitIntoKeys(r".a.calexp\\.wcs.b") 

219 

220 # The next two fail because internally \r is magic when escaping 

221 # a delimiter. 

222 with self.assertRaises(ValueError): 

223 Config._splitIntoKeys("\ra\rcalexp\\\rwcs\rb") 

224 

225 with self.assertRaises(ValueError): 

226 Config._splitIntoKeys(".a.cal\rexp\\.wcs.b") 

227 

228 def testEscape(self): 

229 c = Config({"a": {"foo.bar": 1}, "b😂c": {"bar_baz": 2}}) 

230 self.assertEqual(c[r".a.foo\.bar"], 1) 

231 self.assertEqual(c[":a:foo.bar"], 1) 

232 self.assertEqual(c[".b😂c.bar_baz"], 2) 

233 self.assertEqual(c[r"😂b\😂c😂bar_baz"], 2) 

234 self.assertEqual(c[r"\a\foo.bar"], 1) 

235 self.assertEqual(c["\ra\rfoo.bar"], 1) 

236 with self.assertRaises(ValueError): 

237 c[".a.foo\\.bar\r"] 

238 

239 def testOperators(self): 

240 c1 = Config({"a": {"b": 1}, "c": 2}) 

241 c2 = c1.copy() 

242 self.assertEqual(c1, c2) 

243 self.assertIsInstance(c2, Config) 

244 c2[".a.b"] = 5 

245 self.assertNotEqual(c1, c2) 

246 

247 def testUpdate(self): 

248 c = Config({"a": {"b": 1}}) 

249 c.update({"a": {"c": 2}}) 

250 self.assertEqual(c[".a.b"], 1) 

251 self.assertEqual(c[".a.c"], 2) 

252 c.update({"a": {"d": [3, 4]}}) 

253 self.assertEqual(c[".a.d.0"], 3) 

254 c.update({"z": [5, 6, {"g": 2, "h": 3}]}) 

255 self.assertEqual(c[".z.1"], 6) 

256 

257 # This is detached from parent 

258 c2 = c[".z.2"] 

259 self.assertEqual(c2["g"], 2) 

260 c2.update({"h": 4, "j": 5}) 

261 self.assertEqual(c2["h"], 4) 

262 self.assertNotIn(".z.2.j", c) 

263 self.assertNotEqual(c[".z.2.h"], 4) 

264 

265 with self.assertRaises(RuntimeError): 

266 c.update([1, 2, 3]) 

267 

268 def testHierarchy(self): 

269 c = Config() 

270 

271 # Simple dict 

272 c["a"] = {"z": 52, "x": "string"} 

273 self.assertIn(".a.z", c) 

274 self.assertEqual(c[".a.x"], "string") 

275 

276 # Try different delimiters 

277 self.assertEqual(c["⇛a⇛z"], 52) 

278 self.assertEqual(c[("a", "z")], 52) 

279 self.assertEqual(c["a", "z"], 52) 

280 

281 c[".b.new.thing1"] = "thing1" 

282 c[".b.new.thing2"] = "thing2" 

283 c[".b.new.thing3.supp"] = "supplemental" 

284 self.assertEqual(c[".b.new.thing1"], "thing1") 

285 tmp = c[".b.new"] 

286 self.assertEqual(tmp["thing2"], "thing2") 

287 self.assertEqual(c[".b.new.thing3.supp"], "supplemental") 

288 

289 # Test that we can index into lists 

290 c[".a.b.c"] = [1, "7", 3, {"1": 4, "5": "Five"}, "hello"] 

291 self.assertIn(".a.b.c.3.5", c) 

292 self.assertNotIn(".a.b.c.10", c) 

293 self.assertNotIn(".a.b.c.10.d", c) 

294 self.assertEqual(c[".a.b.c.3.5"], "Five") 

295 # Is the value in the list? 

296 self.assertIn(".a.b.c.hello", c) 

297 self.assertNotIn(".a.b.c.hello.not", c) 

298 

299 # And assign to an element in the list 

300 self.assertEqual(c[".a.b.c.1"], "7") 

301 c[".a.b.c.1"] = 8 

302 self.assertEqual(c[".a.b.c.1"], 8) 

303 self.assertIsInstance(c[".a.b.c"], collections.abc.Sequence) 

304 

305 # Test we do get lists back from asArray 

306 a = c.asArray(".a.b.c") 

307 self.assertIsInstance(a, list) 

308 

309 # Is it the *same* list as in the config 

310 a.append("Sentinel") 

311 self.assertIn("Sentinel", c[".a.b.c"]) 

312 self.assertIn(".a.b.c.Sentinel", c) 

313 

314 # Test we always get a list 

315 for k in c.names(): 

316 a = c.asArray(k) 

317 self.assertIsInstance(a, list) 

318 

319 # Check we get the same top level keys 

320 self.assertEqual(set(c.names(topLevelOnly=True)), set(c._data.keys())) 

321 

322 # Check that we can iterate through items 

323 for k, v in c.items(): 

324 self.assertEqual(c[k], v) 

325 

326 # Check that lists still work even if assigned a dict 

327 c = Config({"cls": "lsst.daf.butler", 

328 "formatters": {"calexp.wcs": "{component}", 

329 "calexp": "{datasetType}"}, 

330 "datastores": [{"datastore": {"cls": "datastore1"}}, 

331 {"datastore": {"cls": "datastore2"}}]}) 

332 c[".datastores.1.datastore"] = {"cls": "datastore2modified"} 

333 self.assertEqual(c[".datastores.0.datastore.cls"], "datastore1") 

334 self.assertEqual(c[".datastores.1.datastore.cls"], "datastore2modified") 

335 self.assertIsInstance(c["datastores"], collections.abc.Sequence) 

336 

337 # Test that we can get all the listed names. 

338 # and also that they are marked as "in" the Config 

339 # Try delimited names and tuples 

340 for n in itertools.chain(c.names(), c.nameTuples()): 

341 val = c[n] 

342 self.assertIsNotNone(val) 

343 self.assertIn(n, c) 

344 

345 names = c.names() 

346 nameTuples = c.nameTuples() 

347 self.assertEqual(len(names), len(nameTuples)) 

348 self.assertEqual(len(names), 11) 

349 self.assertEqual(len(nameTuples), 11) 

350 

351 # Test that delimiter escaping works 

352 names = c.names(delimiter=".") 

353 for n in names: 

354 self.assertIn(n, c) 

355 self.assertIn(".formatters.calexp\\.wcs", names) 

356 

357 # Use a name that includes the internal default delimiter 

358 # to test automatic adjustment of delimiter 

359 strangeKey = f"calexp{c._D}wcs" 

360 c["formatters", strangeKey] = "dynamic" 

361 names = c.names() 

362 self.assertIn(strangeKey, "-".join(names)) 

363 self.assertFalse(names[0].startswith(c._D)) 

364 for n in names: 

365 self.assertIn(n, c) 

366 

367 top = c.nameTuples(topLevelOnly=True) 

368 self.assertIsInstance(top[0], tuple) 

369 

370 # Investigate a possible delimeter in a key 

371 c = Config({"formatters": {"calexp.wcs": 2, "calexp": 3}}) 

372 self.assertEqual(c[":formatters:calexp.wcs"], 2) 

373 self.assertEqual(c[":formatters:calexp"], 3) 

374 for k, v in c["formatters"].items(): 

375 self.assertEqual(c["formatters", k], v) 

376 

377 # Check internal delimiter inheritance 

378 c._D = "." 

379 c2 = c["formatters"] 

380 self.assertEqual(c._D, c2._D) # Check that the child inherits 

381 self.assertNotEqual(c2._D, Config._D) 

382 

383 def testSerializedString(self): 

384 """Test that we can create configs from strings""" 

385 

386 serialized = { 

387 "yaml": """ 

388testing: hello 

389formatters: 

390 calexp: 3""", 

391 "json": '{"testing": "hello", "formatters": {"calexp": 3}}' 

392 } 

393 

394 for format, string in serialized.items(): 

395 c = Config.fromString(string, format=format) 

396 self.assertEqual(c["formatters", "calexp"], 3) 

397 self.assertEqual(c["testing"], "hello") 

398 

399 with self.assertRaises(ValueError): 

400 Config.fromString("", format="unknown") 

401 

402 with self.assertRaises(ValueError): 

403 Config.fromString(serialized["yaml"], format="json") 

404 

405 # This JSON can be parsed by YAML parser 

406 j = Config.fromString(serialized["json"]) 

407 y = Config.fromString(serialized["yaml"]) 

408 self.assertEqual(j["formatters", "calexp"], 3) 

409 self.assertEqual(j.toDict(), y.toDict()) 

410 

411 # Round trip JSON -> Config -> YAML -> Config -> JSON -> Config 

412 c1 = Config.fromString(serialized["json"], format="json") 

413 yaml = c1.dump(format="yaml") 

414 c2 = Config.fromString(yaml, format="yaml") 

415 json = c2.dump(format="json") 

416 c3 = Config.fromString(json, format="json") 

417 self.assertEqual(c3.toDict(), c1.toDict()) 

418 

419 

420class ConfigSubsetTestCase(unittest.TestCase): 

421 """Tests for ConfigSubset 

422 """ 

423 

424 def setUp(self): 

425 self.testDir = os.path.abspath(os.path.dirname(__file__)) 

426 self.configDir = os.path.join(self.testDir, "config", "testConfigs") 

427 self.configDir2 = os.path.join(self.testDir, "config", "testConfigs", "test2") 

428 self.configDir3 = os.path.join(self.testDir, "config", "testConfigs", "test3") 

429 

430 def testEmpty(self): 

431 """Ensure that we can read an empty file.""" 

432 c = ConfigTestEmpty(searchPaths=(self.configDir,)) 

433 self.assertIsInstance(c, ConfigSubset) 

434 

435 def testPathlib(self): 

436 """Ensure that we can read an empty file.""" 

437 c = ConfigTestPathlib(searchPaths=(self.configDir,)) 

438 self.assertIsInstance(c, ConfigSubset) 

439 

440 def testDefaults(self): 

441 """Read of defaults""" 

442 

443 # Supply the search path explicitly 

444 c = ConfigTest(searchPaths=(self.configDir,)) 

445 self.assertIsInstance(c, ConfigSubset) 

446 self.assertIn("item3", c) 

447 self.assertEqual(c["item3"], 3) 

448 

449 # Use environment 

450 with modified_environment(DAF_BUTLER_CONFIG_PATH=self.configDir): 

451 c = ConfigTest() 

452 self.assertIsInstance(c, ConfigSubset) 

453 self.assertEqual(c["item3"], 3) 

454 

455 # No default so this should fail 

456 with self.assertRaises(KeyError): 

457 c = ConfigTest() 

458 

459 def testExternalOverride(self): 

460 """Ensure that external values win""" 

461 c = ConfigTest({"item3": "newval"}, searchPaths=(self.configDir,)) 

462 self.assertIn("item3", c) 

463 self.assertEqual(c["item3"], "newval") 

464 

465 def testSearchPaths(self): 

466 """Two search paths""" 

467 c = ConfigTest(searchPaths=(self.configDir2, self.configDir)) 

468 self.assertIsInstance(c, ConfigSubset) 

469 self.assertIn("item3", c) 

470 self.assertEqual(c["item3"], "override") 

471 self.assertEqual(c["item4"], "new") 

472 

473 c = ConfigTest(searchPaths=(self.configDir, self.configDir2)) 

474 self.assertIsInstance(c, ConfigSubset) 

475 self.assertIn("item3", c) 

476 self.assertEqual(c["item3"], 3) 

477 self.assertEqual(c["item4"], "new") 

478 

479 def testExternalHierarchy(self): 

480 """Test that we can provide external config parameters in hierarchy""" 

481 c = ConfigTest({"comp": {"item1": 6, "item2": "a", "a": "b", 

482 "item3": 7}, "item4": 8}) 

483 self.assertIn("a", c) 

484 self.assertEqual(c["a"], "b") 

485 self.assertNotIn("item4", c) 

486 

487 def testNoDefaults(self): 

488 """Ensure that defaults can be turned off.""" 

489 

490 # Mandatory keys but no defaults 

491 c = ConfigTest({"item1": "a", "item2": "b", "item6": 6}) 

492 self.assertEqual(len(c.filesRead), 0) 

493 self.assertIn("item1", c) 

494 self.assertEqual(c["item6"], 6) 

495 

496 c = ConfigTestNoDefaults() 

497 self.assertEqual(len(c.filesRead), 0) 

498 

499 def testAbsPath(self): 

500 """Read default config from an absolute path""" 

501 # Force the path to be absolute in the class 

502 ConfigTestAbsPath.defaultConfigFile = os.path.join(self.configDir, "abspath.yaml") 

503 c = ConfigTestAbsPath() 

504 self.assertEqual(c["item11"], "eleventh") 

505 self.assertEqual(len(c.filesRead), 1) 

506 

507 # Now specify the normal config file with an absolute path 

508 ConfigTestAbsPath.defaultConfigFile = os.path.join(self.configDir, ConfigTest.defaultConfigFile) 

509 c = ConfigTestAbsPath() 

510 self.assertEqual(c["item11"], 11) 

511 self.assertEqual(len(c.filesRead), 1) 

512 

513 # and a search path that will also include the file 

514 c = ConfigTestAbsPath(searchPaths=(self.configDir, self.configDir2,)) 

515 self.assertEqual(c["item11"], 11) 

516 self.assertEqual(len(c.filesRead), 1) 

517 

518 # Same as above but this time with relative path and two search paths 

519 # to ensure the count changes 

520 ConfigTestAbsPath.defaultConfigFile = ConfigTest.defaultConfigFile 

521 c = ConfigTestAbsPath(searchPaths=(self.configDir, self.configDir2,)) 

522 self.assertEqual(len(c.filesRead), 2) 

523 

524 # Reset the class 

525 ConfigTestAbsPath.defaultConfigFile = None 

526 

527 def testClassDerived(self): 

528 """Read config specified in class determined from config""" 

529 c = ConfigTestCls(searchPaths=(self.configDir,)) 

530 self.assertEqual(c["item50"], 50) 

531 self.assertEqual(c["help"], "derived") 

532 

533 # Same thing but additional search path 

534 c = ConfigTestCls(searchPaths=(self.configDir, self.configDir2)) 

535 self.assertEqual(c["item50"], 50) 

536 self.assertEqual(c["help"], "derived") 

537 self.assertEqual(c["help2"], "second") 

538 

539 # Same thing but reverse the two paths 

540 c = ConfigTestCls(searchPaths=(self.configDir2, self.configDir)) 

541 self.assertEqual(c["item50"], 500) 

542 self.assertEqual(c["help"], "class") 

543 self.assertEqual(c["help2"], "second") 

544 self.assertEqual(c["help3"], "third") 

545 

546 def testInclude(self): 

547 """Read a config that has an include directive""" 

548 c = Config(os.path.join(self.configDir, "testinclude.yaml")) 

549 self.assertEqual(c[".comp1.item1"], 58) 

550 self.assertEqual(c[".comp2.comp.item1"], 1) 

551 self.assertEqual(c[".comp3.1.comp.item1"], "posix") 

552 self.assertEqual(c[".comp4.0.comp.item1"], "posix") 

553 self.assertEqual(c[".comp4.1.comp.item1"], 1) 

554 self.assertEqual(c[".comp5.comp6.comp.item1"], "posix") 

555 

556 # Test a specific name and then test that all 

557 # returned names are "in" the config. 

558 names = c.names() 

559 self.assertIn(c._D.join(("", "comp3", "1", "comp", "item1")), names) 

560 for n in names: 

561 self.assertIn(n, c) 

562 

563 # Test that override delimiter works 

564 delimiter = "-" 

565 names = c.names(delimiter=delimiter) 

566 self.assertIn(delimiter.join(("", "comp3", "1", "comp", "item1")), names) 

567 

568 def testStringInclude(self): 

569 """Using include directives in strings""" 

570 

571 # See if include works for absolute path 

572 c = Config.fromYaml(f"something: !include {os.path.join(self.configDir, 'testconfig.yaml')}") 

573 self.assertEqual(c["something", "comp", "item3"], 3) 

574 

575 with self.assertRaises(FileNotFoundError) as cm: 

576 Config.fromYaml("something: !include /not/here.yaml") 

577 # Test that it really was trying to open the absolute path 

578 self.assertIn("'/not/here.yaml'", str(cm.exception)) 

579 

580 def testIncludeConfigs(self): 

581 """Test the special includeConfigs key for pulling in additional 

582 files.""" 

583 c = Config(os.path.join(self.configDir, "configIncludes.yaml")) 

584 self.assertEqual(c["comp", "item2"], "hello") 

585 self.assertEqual(c["comp", "item50"], 5000) 

586 self.assertEqual(c["comp", "item1"], "first") 

587 self.assertEqual(c["comp", "item10"], "tenth") 

588 self.assertEqual(c["comp", "item11"], "eleventh") 

589 self.assertEqual(c["unrelated"], 1) 

590 self.assertEqual(c["addon", "comp", "item1"], "posix") 

591 self.assertEqual(c["addon", "comp", "item11"], -1) 

592 self.assertEqual(c["addon", "comp", "item50"], 500) 

593 

594 c = Config(os.path.join(self.configDir, "configIncludes.json")) 

595 self.assertEqual(c["comp", "item2"], "hello") 

596 self.assertEqual(c["comp", "item50"], 5000) 

597 self.assertEqual(c["comp", "item1"], "first") 

598 self.assertEqual(c["comp", "item10"], "tenth") 

599 self.assertEqual(c["comp", "item11"], "eleventh") 

600 self.assertEqual(c["unrelated"], 1) 

601 self.assertEqual(c["addon", "comp", "item1"], "posix") 

602 self.assertEqual(c["addon", "comp", "item11"], -1) 

603 self.assertEqual(c["addon", "comp", "item50"], 500) 

604 

605 # Now test with an environment variable in includeConfigs 

606 with modified_environment(SPECIAL_BUTLER_DIR=self.configDir3): 

607 c = Config(os.path.join(self.configDir, "configIncludesEnv.yaml")) 

608 self.assertEqual(c["comp", "item2"], "hello") 

609 self.assertEqual(c["comp", "item50"], 5000) 

610 self.assertEqual(c["comp", "item1"], "first") 

611 self.assertEqual(c["comp", "item10"], "tenth") 

612 self.assertEqual(c["comp", "item11"], "eleventh") 

613 self.assertEqual(c["unrelated"], 1) 

614 self.assertEqual(c["addon", "comp", "item1"], "envvar") 

615 self.assertEqual(c["addon", "comp", "item11"], -1) 

616 self.assertEqual(c["addon", "comp", "item50"], 501) 

617 

618 # This will fail 

619 with modified_environment(SPECIAL_BUTLER_DIR=self.configDir2): 

620 with self.assertRaises(FileNotFoundError): 

621 Config(os.path.join(self.configDir, "configIncludesEnv.yaml")) 

622 

623 def testResource(self): 

624 c = Config("resource://lsst.daf.butler/configs/datastore.yaml") 

625 self.assertIn("datastore", c) 

626 

627 # Test that we can include a resource URI 

628 yaml = """ 

629toplevel: true 

630resource: !include resource://lsst.daf.butler/configs/datastore.yaml 

631""" 

632 c = Config.fromYaml(yaml) 

633 self.assertIn(("resource", "datastore", "cls"), c) 

634 

635 # Test that we can include a resource URI with includeConfigs 

636 yaml = """ 

637toplevel: true 

638resource: 

639 includeConfigs: resource://lsst.daf.butler/configs/datastore.yaml 

640""" 

641 c = Config.fromYaml(yaml) 

642 self.assertIn(("resource", "datastore", "cls"), c) 

643 

644 

645class FileWriteConfigTestCase(unittest.TestCase): 

646 

647 def setUp(self): 

648 self.tmpdir = makeTestTempDir(TESTDIR) 

649 

650 def tearDown(self): 

651 removeTestTempDir(self.tmpdir) 

652 

653 def testDump(self): 

654 """Test that we can write and read a configuration.""" 

655 

656 c = Config({"1": 2, "3": 4, "key3": 6, "dict": {"a": 1, "b": 2}}) 

657 

658 for format in ("yaml", "json"): 

659 outpath = os.path.join(self.tmpdir, f"test.{format}") 

660 c.dumpToUri(outpath) 

661 

662 c2 = Config(outpath) 

663 self.assertEqual(c2, c) 

664 

665 c.dumpToUri(outpath, overwrite=True) 

666 with self.assertRaises(FileExistsError): 

667 c.dumpToUri(outpath, overwrite=False) 

668 

669 

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

671 unittest.main()