Debian Codegraph @

tests/unit/parsec/test_config.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 from pathlib import Path
18 import tempfile
19
20 import pytest
21
22 from cylc.flow.parsec.config import (
23 ConfigNode as Conf,
24 ParsecConfig
25 )
26 from cylc.flow.parsec.exceptions import (
27 IllegalItemError,
28 InvalidConfigError,
29 ItemNotFoundError,
30 )
31 from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults
32 from cylc.flow.parsec.upgrade import upgrader
33 from cylc.flow.parsec.validate import (
34 cylc_config_validate,
35 CylcConfigValidator as VDR
36 )
37
38
39 def test_loadcfg(sample_spec):
40 with tempfile.NamedTemporaryFile() as output_file_name:
41 with tempfile.NamedTemporaryFile() as rcfile:
42 parsec_config = ParsecConfig(
43 spec=sample_spec,
44 upgrader=None, # new spec
45 output_fname=output_file_name.name,
46 tvars=None,
47 validator=None # use default
48 )
49 rcfile.write("""
50 [section1]
51 value1 = 'test'
52 value2 = 'test'
53 [section2]
54 enabled = True
55 [section3]
56 title = 'Ohm'
57 [[entries]]
58 key = 'product'
59 value = 1, 2, 3, 4
60 """.encode())
61 rcfile.seek(0)
62 parsec_config.loadcfg(rcfile.name, "File test_loadcfg")
63
64 sparse = parsec_config.sparse
65 value = sparse['section3']['entries']['value']
66 assert [1, 2, 3, 4] == value
67
68 # calling it multiple times should still work
69 parsec_config.loadcfg(rcfile.name, "File test_loadcfg")
70 parsec_config.loadcfg(rcfile.name, "File test_loadcfg")
71
72 sparse = parsec_config.sparse
73 value = sparse['section3']['entries']['value']
74 assert [1, 2, 3, 4] == value
75
76
77 def test_loadcfg_override(sample_spec):
78 """Test that loading a second config file overrides common settings but
79 leaves in settings only present in the first"""
80 with tempfile.NamedTemporaryFile() as output_file_name:
81 parsec_config = ParsecConfig(
82 spec=sample_spec,
83 upgrader=None,
84 output_fname=output_file_name.name,
85 tvars=None,
86 validator=None
87 )
88 with tempfile.NamedTemporaryFile() as conf_file1:
89 conf_file1.write("""
90 [section1]
91 value1 = 'frodo'
92 value2 = 'sam'
93 """.encode())
94 conf_file1.seek(0)
95 parsec_config.loadcfg(conf_file1.name, "File test_loadcfg")
96 sparse = parsec_config.sparse
97 assert sparse['section1']['value1'] == 'frodo'
98 assert sparse['section1']['value2'] == 'sam'
99
100 with tempfile.NamedTemporaryFile() as conf_file2:
101 conf_file2.write("""
102 [section1]
103 value2 = 'pippin'
104 """.encode())
105 conf_file2.seek(0)
106 parsec_config.loadcfg(conf_file2.name, "File test_loadcfg")
107 sparse = parsec_config.sparse
108 assert sparse['section1']['value1'] == 'frodo'
109 assert sparse['section1']['value2'] == 'pippin'
110
111
112 def test_loadcfg_with_upgrade(sample_spec):
113 def upg(cfg, description):
114 u = upgrader(cfg, description)
115 u.obsolete('1.0', ['section3', 'entries'])
116 u.upgrade()
117
118 with tempfile.NamedTemporaryFile() as output_file_name:
119 with tempfile.NamedTemporaryFile() as rcfile:
120 parsec_config = ParsecConfig(
121 spec=sample_spec,
122 upgrader=upg,
123 output_fname=output_file_name.name,
124 tvars=None,
125 validator=None # use default
126 )
127 rcfile.write("""
128 [section1]
129 value1 = 'test'
130 value2 = 'test'
131 [section2]
132 enabled = True
133 [section3]
134 title = 'Ohm'
135 [[entries]]
136 key = 'product'
137 value = 1, 2, 3, 4
138 """.encode())
139 rcfile.seek(0)
140 parsec_config.loadcfg(rcfile.name, "1.1")
141
142 sparse = parsec_config.sparse
143 # removed by the obsolete upgrade
144 assert 'entries' not in sparse['section3']
145
146
147 def test_validate():
148 """
149 An interesting aspect of the ParsecConfig.validate, is that if you
150 have a sparse dict produced by this class, and you call the validate
151 on that dict again, you may have TypeErrors.
152
153 That occurs because the values like 'True' are validated against the
154 spec and converted from Strings with quotes, to bool types. So the
155 next type you run the validation if expects Strings...
156 :return:
157 """
158
159 with Conf('myconf') as spec:
160 with Conf('section'):
161 Conf('name', VDR.V_STRING)
162 Conf('address', VDR.V_STRING)
163
164 parsec_config = ParsecConfig(
165 spec=spec,
166 upgrader=None, # new spec
167 output_fname=None, # not going to call the loadcfg
168 tvars=None,
169 validator=None # use default
170 )
171
172 sparse = OrderedDictWithDefaults()
173 parsec_config.validate(sparse) # empty dict is OK
174
175 with pytest.raises(IllegalItemError):
176 sparse = OrderedDictWithDefaults()
177 sparse['name'] = 'True'
178 parsec_config.validate(sparse) # name is not valid
179
180 sparse = OrderedDictWithDefaults()
181 sparse['section'] = OrderedDictWithDefaults()
182 sparse['section']['name'] = 'Wind'
183 sparse['section']['address'] = 'Corner'
184 parsec_config.validate(sparse)
185
186
187 @pytest.fixture
188 def parsec_config_2(tmp_path: Path):
189 with Conf('myconf') as spec:
190 with Conf('section'):
191 Conf('name', VDR.V_STRING)
192 Conf('address', VDR.V_INTEGER_LIST)
193 with Conf('allow_many'):
194 Conf('<user defined>', VDR.V_STRING, '')
195 with Conf('so_many'):
196 with Conf('<thing>'):
197 Conf('color', VDR.V_STRING)
198 Conf('horsepower', VDR.V_INTEGER)
199 parsec_config = ParsecConfig(spec, validator=cylc_config_validate)
200 conf_file = tmp_path / 'myconf'
201 conf_file.write_text("""
202 [section]
203 name = test
204 [allow_many]
205 anything = yup
206 [so_many]
207 [[legs]]
208 horsepower = 123
209 """)
210 parsec_config.loadcfg(conf_file, "1.0")
211 return parsec_config
212
213
214 def test_expand(parsec_config_2: ParsecConfig):
215 parsec_config_2.expand()
216 sparse = parsec_config_2.sparse
217 assert sparse['allow_many']['anything'] == 'yup'
218 assert '__MANY__' not in sparse['allow_many']
219
220
221 def test_get(parsec_config_2: ParsecConfig):
222 cfg = parsec_config_2.get(keys=None, sparse=False)
223 assert cfg == parsec_config_2.dense
224
225 cfg = parsec_config_2.get(keys=None, sparse=True)
226 assert cfg == parsec_config_2.sparse
227
228 cfg = parsec_config_2.get(keys=['section'], sparse=True)
229 assert cfg == parsec_config_2.sparse['section']
230
231
232 @pytest.mark.parametrize('keys, expected', [
233 (['section', 'name'], 'test'),
234 (['section', 'a'], InvalidConfigError),
235 (['alloy_many', 'anything'], InvalidConfigError),
236 (['allow_many', 'anything'], 'yup'),
237 (['allow_many', 'a'], ItemNotFoundError),
238 (['so_many', 'legs', 'horsepower'], 123),
239 (['so_many', 'legs', 'color'], ItemNotFoundError),
240 (['so_many', 'legs', 'a'], InvalidConfigError),
241 (['so_many', 'teeth', 'horsepower'], ItemNotFoundError),
242 ])
243 def test_get__sparse(parsec_config_2: ParsecConfig, keys, expected):
244 if isinstance(expected, type) and issubclass(expected, Exception):
245 with pytest.raises(expected):
246 parsec_config_2.get(keys, sparse=True)
247 else:
248 assert parsec_config_2.get(keys, sparse=True) == expected
249
250
251 def test_mdump_none(config, sample_spec, capsys):
252 cfg = config(sample_spec, '''
253 [section1]
254 value1 = abc
255 value2 = def
256 ''')
257 cfg.mdump()
258 std = capsys.readouterr()
259 assert std.out == ''
260 assert std.err == ''
261
262
263 def test_mdump_some(config, sample_spec, capsys):
264 cfg = config(sample_spec, '''
265 [section1]
266 value1 = abc
267 value2 = def
268 ''')
269 cfg.mdump(
270 [
271 ['section1', 'value1'],
272 ['section1', 'value2'],
273 ]
274 )
275 std = capsys.readouterr()
276 assert std.out == 'abc\ndef\n'
277 assert std.err == ''
278
279
280 def test_mdump_oneline(config, sample_spec, capsys):
281 cfg = config(sample_spec, '''
282 [section1]
283 value1 = abc
284 value2 = def
285 ''')
286 cfg.mdump(
287 [
288 ['section1', 'value1'],
289 ['section1', 'value2'],
290 ],
291 oneline=True
292 )
293 std = capsys.readouterr()
294 assert std.out == 'abc def\n'
295 assert std.err == ''
296
297
298 def test_get_none(config, sample_spec):
299 cfg = config(sample_spec, '') # blank config
300 assert cfg.get(sparse=True) == {}
301
302
303 def test__get_namespace_parents():
304 """It returns a list of parents and nothing else"""
305 with Conf('myconfig.cylc') as myconf:
306 with Conf('a'):
307 with Conf('b'):
308 with Conf('<c>'):
309 with Conf('d'):
310 Conf('<e>')
311 with Conf('x'):
312 Conf('y')
313
314 cfg = ParsecConfig(myconf)
315 assert cfg.manyparents == [
316 ['a', 'b'],
317 ['a', 'b', '__MANY__', 'd'],
318 ]