Coverage for tests/test_config.py : 14%

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/>.
22import unittest
23import os
24import contextlib
25import collections
26import itertools
27from pathlib import Path
29from lsst.daf.butler import ConfigSubset, Config
30from lsst.daf.butler.tests.utils import makeTestTempDir, removeTestTempDir
32TESTDIR = os.path.abspath(os.path.dirname(__file__))
35@contextlib.contextmanager
36def modified_environment(**environ):
37 """
38 Temporarily set environment variables.
40 >>> with modified_environment(DAF_BUTLER_CONFIG_PATHS="/somewhere"):
41 ... os.environ["DAF_BUTLER_CONFIG_PATHS"] == "/somewhere"
42 True
44 >>> "DAF_BUTLER_CONFIG_PATHS" != "/somewhere"
45 True
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)
61class ExampleWithConfigFileReference:
62 defaultConfigFile = "viacls.yaml"
65class ExampleWithConfigFileReference2:
66 defaultConfigFile = "viacls2.yaml"
69class ConfigTest(ConfigSubset):
70 component = "comp"
71 requiredKeys = ("item1", "item2")
72 defaultConfigFile = "testconfig.yaml"
75class ConfigTestPathlib(ConfigTest):
76 defaultConfigFile = Path("testconfig.yaml")
79class ConfigTestEmpty(ConfigTest):
80 defaultConfigFile = "testconfig_empty.yaml"
81 requiredKeys = ()
84class ConfigTestButlerDir(ConfigTest):
85 defaultConfigFile = "testConfigs/testconfig.yaml"
88class ConfigTestNoDefaults(ConfigTest):
89 defaultConfigFile = None
90 requiredKeys = ()
93class ConfigTestAbsPath(ConfigTest):
94 defaultConfigFile = None
95 requiredKeys = ()
98class ConfigTestCls(ConfigTest):
99 defaultConfigFile = "withcls.yaml"
102class ConfigTestCase(unittest.TestCase):
103 """Tests of simple Config"""
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)
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)
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()])
140 newKeys = ("key4", ".dict.q", ("dict", "r"), "5")
141 oldKeys = ("key3", ".dict.a", ("dict", "b"), "3")
142 remainingKey = "1"
144 # Check get with existing key
145 for k in oldKeys:
146 self.assertEqual(c.get(k, "missing"), c[k])
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")
153 # Check setdefault with existing key
154 for k in oldKeys:
155 c.setdefault(k, 8)
156 self.assertNotEqual(c[k], 8)
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)
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)
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)
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"]
179 # Check popitem (mutates c, removing remainingKey)
180 v = c[remainingKey]
181 self.assertEqual(c.popitem(), (remainingKey, v))
183 # Check that c is now empty
184 self.assertFalse(c)
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"])
194 # Modifying one does not change the other
195 d1["a"]["c"] = 2
196 self.assertNotEqual(d1["a"], c1["a"])
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)
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")
210 answer = ["a", "calexp.wcs", "b"]
211 self.assertSplit(answer, r".a.calexp\.wcs.b", ":a:calexp.wcs:b")
213 self.assertSplit(["a.b.c"])
214 self.assertSplit(["a", r"b\.c"], r"_a_b\.c")
216 # Escaping a backslash before a delimiter currently fails
217 with self.assertRaises(ValueError):
218 Config._splitIntoKeys(r".a.calexp\\.wcs.b")
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")
225 with self.assertRaises(ValueError):
226 Config._splitIntoKeys(".a.cal\rexp\\.wcs.b")
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"]
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)
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)
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)
265 with self.assertRaises(RuntimeError):
266 c.update([1, 2, 3])
268 def testHierarchy(self):
269 c = Config()
271 # Simple dict
272 c["a"] = {"z": 52, "x": "string"}
273 self.assertIn(".a.z", c)
274 self.assertEqual(c[".a.x"], "string")
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)
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")
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)
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)
305 # Test we do get lists back from asArray
306 a = c.asArray(".a.b.c")
307 self.assertIsInstance(a, list)
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)
314 # Test we always get a list
315 for k in c.names():
316 a = c.asArray(k)
317 self.assertIsInstance(a, list)
319 # Check we get the same top level keys
320 self.assertEqual(set(c.names(topLevelOnly=True)), set(c._data.keys()))
322 # Check that we can iterate through items
323 for k, v in c.items():
324 self.assertEqual(c[k], v)
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)
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)
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)
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)
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)
367 top = c.nameTuples(topLevelOnly=True)
368 self.assertIsInstance(top[0], tuple)
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)
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)
383 def testSerializedString(self):
384 """Test that we can create configs from strings"""
386 serialized = {
387 "yaml": """
388testing: hello
389formatters:
390 calexp: 3""",
391 "json": '{"testing": "hello", "formatters": {"calexp": 3}}'
392 }
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")
399 with self.assertRaises(ValueError):
400 Config.fromString("", format="unknown")
402 with self.assertRaises(ValueError):
403 Config.fromString(serialized["yaml"], format="json")
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())
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())
420class ConfigSubsetTestCase(unittest.TestCase):
421 """Tests for ConfigSubset
422 """
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")
430 def testEmpty(self):
431 """Ensure that we can read an empty file."""
432 c = ConfigTestEmpty(searchPaths=(self.configDir,))
433 self.assertIsInstance(c, ConfigSubset)
435 def testPathlib(self):
436 """Ensure that we can read an empty file."""
437 c = ConfigTestPathlib(searchPaths=(self.configDir,))
438 self.assertIsInstance(c, ConfigSubset)
440 def testDefaults(self):
441 """Read of defaults"""
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)
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)
455 # No default so this should fail
456 with self.assertRaises(KeyError):
457 c = ConfigTest()
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")
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")
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")
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)
487 def testNoDefaults(self):
488 """Ensure that defaults can be turned off."""
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)
496 c = ConfigTestNoDefaults()
497 self.assertEqual(len(c.filesRead), 0)
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)
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)
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)
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)
524 # Reset the class
525 ConfigTestAbsPath.defaultConfigFile = None
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")
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")
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")
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")
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)
563 # Test that override delimiter works
564 delimiter = "-"
565 names = c.names(delimiter=delimiter)
566 self.assertIn(delimiter.join(("", "comp3", "1", "comp", "item1")), names)
568 def testStringInclude(self):
569 """Using include directives in strings"""
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)
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))
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)
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)
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)
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"))
623 def testResource(self):
624 c = Config("resource://lsst.daf.butler/configs/datastore.yaml")
625 self.assertIn("datastore", c)
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)
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)
645class FileWriteConfigTestCase(unittest.TestCase):
647 def setUp(self):
648 self.tmpdir = makeTestTempDir(TESTDIR)
650 def tearDown(self):
651 removeTestTempDir(self.tmpdir)
653 def testDump(self):
654 """Test that we can write and read a configuration."""
656 c = Config({"1": 2, "3": 4, "key3": 6, "dict": {"a": 1, "b": 2}})
658 for format in ("yaml", "json"):
659 outpath = os.path.join(self.tmpdir, f"test.{format}")
660 c.dumpToUri(outpath)
662 c2 = Config(outpath)
663 self.assertEqual(c2, c)
665 c.dumpToUri(outpath, overwrite=True)
666 with self.assertRaises(FileExistsError):
667 c.dumpToUri(outpath, overwrite=False)
670if __name__ == "__main__": 670 ↛ 671line 670 didn't jump to line 671, because the condition on line 670 was never true
671 unittest.main()