Coverage for tests/test_configDictField.py: 22%
97 statements
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-23 11:29 +0000
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-23 11:29 +0000
1# This file is part of pex_config.
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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28import os
29import tempfile
30import unittest
32import lsst.pex.config as pexConfig
35class Config1(pexConfig.Config):
36 """First test config."""
38 f = pexConfig.Field("f", float, default=3.0)
40 def _collectImports(self):
41 # Exists to test that imports of dict values are collected
42 self._imports.add("builtins")
45class Config2(pexConfig.Config):
46 """Second test config."""
48 d1 = pexConfig.ConfigDictField("d1", keytype=str, itemtype=Config1, itemCheck=lambda x: x.f > 0) 48 ↛ exitline 48 didn't run the lambda on line 48
51class Config3(pexConfig.Config):
52 """Third test config."""
54 field1 = pexConfig.ConfigDictField(keytype=str, itemtype=pexConfig.Config, default={}, doc="doc")
57class ConfigDictFieldTest(unittest.TestCase):
58 """Test of ConfigDictField."""
60 def testConstructor(self):
61 try:
63 class BadKeytype(pexConfig.Config):
64 d = pexConfig.ConfigDictField("...", keytype=list, itemtype=Config1)
66 except Exception:
67 pass
68 else:
69 raise SyntaxError("Unsupported keytypes should not be allowed")
71 try:
73 class BadItemtype(pexConfig.Config):
74 d = pexConfig.ConfigDictField("...", keytype=int, itemtype=dict)
76 except Exception:
77 pass
78 else:
79 raise SyntaxError("Unsupported itemtypes should not be allowed")
81 try:
83 class BadItemCheck(pexConfig.Config):
84 d = pexConfig.ConfigDictField("...", keytype=str, itemtype=Config1, itemCheck=4)
86 except Exception:
87 pass
88 else:
89 raise SyntaxError("Non-callable itemCheck should not be allowed")
91 try:
93 class BadDictCheck(pexConfig.Config):
94 d = pexConfig.DictField("...", keytype=int, itemtype=Config1, dictCheck=4)
96 except Exception:
97 pass
98 else:
99 raise SyntaxError("Non-callable dictCheck should not be allowed")
101 def testAssignment(self):
102 c = Config2()
103 self.assertRaises(pexConfig.FieldValidationError, setattr, c, "d1", {3: 3})
104 self.assertRaises(pexConfig.FieldValidationError, setattr, c, "d1", {"a": 0})
105 self.assertRaises(pexConfig.FieldValidationError, setattr, c, "d1", [1.2, 3, 4])
106 c.d1 = None
107 c.d1 = {"a": Config1, "b": Config1()}
109 def testValidate(self):
110 c = Config2()
111 self.assertRaises(pexConfig.FieldValidationError, Config2.validate, c)
113 c.d1 = {"a": Config1(f=0)}
114 self.assertRaises(pexConfig.FieldValidationError, Config2.validate, c)
116 c.d1["a"].f = 5
117 c.validate()
119 def testInPlaceModification(self):
120 c = Config2(d1={})
121 self.assertRaises(pexConfig.FieldValidationError, c.d1.__setitem__, 1, 0)
122 self.assertRaises(pexConfig.FieldValidationError, c.d1.__setitem__, "a", 0)
123 c.d1["a"] = Config1(f=4)
124 self.assertEqual(c.d1["a"].f, 4)
126 def testSave(self):
127 c = Config2(d1={"a": Config1(f=4)})
129 # verify _collectImports is called on all the configDictValues
130 stringOutput = c.saveToString()
131 self.assertIn("import builtins", stringOutput)
133 with tempfile.TemporaryDirectory(prefix="config-dictfield-", ignore_cleanup_errors=True) as tmpdir:
134 path = os.path.join(tmpdir, "configDictTest.py")
135 c.save(path)
137 rt = Config2()
138 rt.load(path)
140 self.assertEqual(rt.d1["a"].f, c.d1["a"].f)
142 c = Config2()
143 path = os.path.join(tmpdir, "emptyConfigDictTest.py")
144 c.save(path)
145 rt.load(path)
147 self.assertIsNone(rt.d1)
149 def testToDict(self):
150 c = Config2(d1={"a": Config1(f=4), "b": Config1})
151 dict_ = c.toDict()
152 self.assertEqual(dict_, {"d1": {"a": {"f": 4.0}, "b": {"f": 3.0}}})
154 def testFreeze(self):
155 c = Config2(d1={"a": Config1(f=4), "b": Config1})
156 c.freeze()
158 self.assertRaises(pexConfig.FieldValidationError, setattr, c.d1["a"], "f", 0)
160 def testNoArbitraryAttributes(self):
161 c = Config2(d1={})
162 self.assertRaises(pexConfig.FieldValidationError, setattr, c.d1, "should", "fail")
164 def testEquality(self):
165 """Test ConfigDictField.__eq__.
167 We create two configs, with the keys explicitly added in a different
168 order and test their equality.
169 """
170 keys1 = ["A", "B", "C"]
171 keys2 = ["X", "Y", "Z", "a", "b", "c", "d", "e"]
173 c1 = Config3()
174 c1.field1 = {k: pexConfig.Config() for k in keys1}
175 for k in keys2:
176 c1.field1[k] = pexConfig.Config()
178 c2 = Config3()
179 for k in keys2 + keys1:
180 c2.field1[k] = pexConfig.Config()
182 self.assertTrue(pexConfig.compareConfigs("test", c1, c2))
185if __name__ == "__main__": 185 ↛ 186line 185 didn't jump to line 186, because the condition on line 185 was never true
186 unittest.main()