Debian Codegraph @

tests/u/parsec/test_util.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 io import StringIO
18
19 import pytest
20
21 from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults
22 from cylc.flow.parsec.util import (
23 SECTION_EXPAND_PATTERN,
24 expand_many_section,
25 itemstr,
26 listjoin,
27 m_override,
28 pdeepcopy,
29 poverride,
30 printcfg,
31 replicate,
32 un_many,
33 )
34
35
36 def test_listjoin():
37 assert listjoin(None) == ''
38 assert listjoin(None, 'test') == 'test'
39 assert listjoin([], 'test') == 'test'
40 assert listjoin([None], 'test') == 'test'
41 assert listjoin(['test', 'test']) == 'test, test'
42 assert listjoin(['test,', 'test']) == '\'test,\', test'
43
44
45 # --- printcfg
46
47 def test_printcfg():
48 cfg = OrderedDictWithDefaults()
49 cfg['root'] = OrderedDictWithDefaults()
50 cfg['root']['special'] = 1
51 cfg['root']['normal'] = 0
52 cfg['root'][None] = None
53 cfg[None] = None
54
55 myhandle = StringIO()
56 printcfg(cfg, handle=myhandle)
57 expected = "\n[root]\n special = 1\n normal = 0\n \n"
58 actual = myhandle.getvalue()
59 assert actual == expected
60
61
62 def test_printcfg_none_str_is_none():
63 cfg = OrderedDictWithDefaults()
64 cfg['root'] = OrderedDictWithDefaults()
65 cfg['root']['special'] = 1
66 cfg['root']['normal'] = 0
67 cfg['root'][None] = None
68 cfg[None] = None
69
70 myhandle = StringIO()
71 printcfg(cfg, handle=myhandle, none_str=None)
72 expected = "[root]\n special = 1\n normal = 0\n"
73 actual = myhandle.getvalue()
74 assert actual == expected
75
76
77 def test_printcfg_list_values():
78 cfg = OrderedDictWithDefaults()
79 cfg['root'] = OrderedDictWithDefaults()
80 cfg['root']['special'] = ['a', 'b', 'c', None]
81 cfg['root']['normal'] = 0
82
83 myhandle = StringIO()
84 printcfg(cfg, handle=myhandle, none_str='d')
85 expected = "[root]\n special = a, b, c, d\n normal = 0\n"
86 actual = myhandle.getvalue()
87 assert actual == expected
88
89
90 def test_printcfg_break_lines():
91 cfg = OrderedDictWithDefaults()
92 cfg['root'] = OrderedDictWithDefaults()
93 cfg['root']['special'] = "\nthis is\nvalid"
94 cfg['root']['normal'] = 0
95
96 myhandle = StringIO()
97 printcfg(cfg, handle=myhandle)
98 expected = (
99 "[root]\n special = \"\"\"\n \n "
100 " this is\n valid\n \"\"\"\n normal = 0\n"
101 )
102 actual = myhandle.getvalue()
103 assert actual == expected
104
105
106 # --- replicate
107
108 def test_replicate():
109 replicate('Name', None) # does nothing, no exception/error
110 source_1 = OrderedDictWithDefaults()
111 source_1["name"] = "sea"
112 source_1["origin"] = "kitchen"
113 source_1.defaults_ = {"brewery": False}
114 source_2 = OrderedDictWithDefaults()
115 source_2["name"] = ["sea", "legume"]
116 source_2["origin"] = "fridge"
117 source_3 = OrderedDictWithDefaults()
118 source_3["name"] = OrderedDictWithDefaults()
119 source_3["name"]["value"] = "oil"
120 source_3["name"]["key"] = 1
121 source_3["name"].defaults_ = {"value": 1}
122
123 target_1 = OrderedDictWithDefaults()
124 target_2 = OrderedDictWithDefaults()
125 target_3 = OrderedDictWithDefaults()
126
127 replicate(target_1, source_1)
128 replicate(target_2, source_2)
129 replicate(target_3, source_3)
130
131 # Note: assertDictEqual not available for Python 2.6
132 assert str(target_1) == str(source_1)
133 assert str(target_2) == str(source_2)
134 assert str(target_3) == str(source_3)
135
136
137 # --- pdeepcopy
138
139 def test_pdeepcopy():
140 """This is tested entirely by the tests in replicate as well"""
141 source = OrderedDictWithDefaults()
142 source["name"] = OrderedDictWithDefaults()
143 source["name"]["value"] = "oil"
144 source["name"]["key"] = 1
145 source["name"].defaults_ = {"value": 1}
146
147 target = pdeepcopy(source)
148
149 assert target == source
150
151
152 # --- poverride
153
154 def test_poverride_append():
155 source = OrderedDictWithDefaults()
156 source["name"] = OrderedDictWithDefaults()
157 source["name"]["value"] = "oil"
158 source["name"]["key"] = [1, 2, 3, 4]
159
160 target = OrderedDictWithDefaults()
161 target["name"] = OrderedDictWithDefaults()
162 target["name"]["index"] = 0
163 poverride(target, None) # harmless, and no error/exception
164
165 poverride(target, source)
166
167 expected = OrderedDictWithDefaults()
168 expected["index"] = 0
169 expected["value"] = "oil"
170 expected["key"] = [1, 2, 3, 4]
171
172 assert target["name"] == expected
173
174
175 def test_poverride_prepend():
176 source = OrderedDictWithDefaults()
177 source["name"] = OrderedDictWithDefaults()
178 source["name"]["value"] = "oil"
179 source["name"]["key"] = [1, 2, 3, 4]
180
181 target = OrderedDictWithDefaults()
182 target["name"] = OrderedDictWithDefaults()
183 target["name"]["index"] = 0
184 poverride(target, None) # harmless, and no error/exception
185
186 poverride(target, source, prepend=True)
187
188 expected = OrderedDictWithDefaults()
189 expected["key"] = [1, 2, 3, 4]
190 expected["value"] = "oil"
191 expected["index"] = 0
192
193 assert target["name"] == expected
194
195
196 # -- m_override
197
198 def test_m_override():
199 source = OrderedDictWithDefaults()
200 source["name"] = OrderedDictWithDefaults()
201 source["name"]["index"] = "oil"
202 source["name2"] = OrderedDictWithDefaults()
203 source["name2"]["key"] = [1, 2, 3, 4]
204 source["name2"]["text"] = ""
205 source["name2"]["subdict"] = OrderedDictWithDefaults()
206 source["name2"]["subdict"]['family'] = 'ALL'
207
208 target = OrderedDictWithDefaults()
209 target["name"] = OrderedDictWithDefaults()
210 target["name"]["index"] = 0
211 target['__MANY__'] = OrderedDictWithDefaults()
212 target['__MANY__']['name2'] = OrderedDictWithDefaults()
213 target['__MANY__']['subdict'] = OrderedDictWithDefaults()
214 target['__MANY__']['subdict']['__MANY__'] = OrderedDictWithDefaults()
215 target['__MANY__']['subdict']['__MANY__']['family'] = 'LATIN'
216 target['__MANY__']['key'] = []
217 target['__MANY__']['text'] = "Ad infinitum"
218
219 assert target["name"]["index"] == 0
220 m_override(target, source)
221 assert target["name"]["index"] == "oil"
222
223
224 def test_m_override_many_with_many():
225 source = OrderedDictWithDefaults()
226 source["name"] = OrderedDictWithDefaults()
227 source["name"]["index"] = "oil"
228 source["name2"] = OrderedDictWithDefaults()
229 source["name2"]["key"] = [1, 2, 3, 4]
230 source["name2"]["text"] = ""
231 source["name2"]["subdict"] = OrderedDictWithDefaults()
232 source["name2"]["subdict"]['family'] = 'ALL'
233
234 target = OrderedDictWithDefaults()
235 target["name"] = OrderedDictWithDefaults()
236 target["name"]["index"] = 0
237 target['__MANY__'] = OrderedDictWithDefaults()
238 target['__MANY__']['name2'] = OrderedDictWithDefaults()
239 target['__MANY__']['subdict'] = OrderedDictWithDefaults()
240 target['__MANY__']['subdict']['__MANY__'] = OrderedDictWithDefaults()
241 target['__MANY__']['subdict']['__MANY__']['family'] = 'LATIN'
242 target['__MANY__']['key'] = []
243 target['__MANY__']['text'] = "Ad infinitum"
244
245 # code is OK until here
246
247 # It appears this is valid for now, but may change later
248 target['__MANY__']['__MANY__'] = OrderedDictWithDefaults()
249
250 with pytest.raises(Exception):
251 m_override(target, source)
252
253
254 def test_m_override_without_many_1():
255 source = OrderedDictWithDefaults()
256 source["name"] = OrderedDictWithDefaults()
257 source["name"]["value"] = "oil"
258 source["name"]["key"] = [1, 2, 3, 4]
259
260 target = OrderedDictWithDefaults()
261 target["name"] = OrderedDictWithDefaults()
262 target["name"]["index"] = 0
263
264 with pytest.raises(Exception):
265 m_override(target, source)
266
267
268 def test_m_override_without_many_2():
269 source = OrderedDictWithDefaults()
270 source["name"] = OrderedDictWithDefaults()
271 source["name"]["index"] = "oil"
272 source["name2"] = OrderedDictWithDefaults()
273 source["name2"]["key"] = [1, 2, 3, 4]
274
275 target = OrderedDictWithDefaults()
276 target["name"] = OrderedDictWithDefaults()
277 target["name"]["index"] = 0
278 target['__MANY__'] = OrderedDictWithDefaults()
279 target['__MANY__']['name2'] = OrderedDictWithDefaults()
280 # target['__MANY__']['key'] = []
281
282 with pytest.raises(Exception):
283 m_override(target, source)
284
285
286 def test_m_override_without_many_3():
287 source = OrderedDictWithDefaults()
288 source["name"] = OrderedDictWithDefaults()
289 source["name"]["index"] = "oil"
290 source["name2"] = OrderedDictWithDefaults()
291 source["name2"]["key"] = [1, 2, 3, 4]
292 source["name2"]["text"] = ""
293 source["name2"]["subdict"] = OrderedDictWithDefaults()
294 source["name2"]["subdict"]['family'] = 'ALL'
295
296 target = OrderedDictWithDefaults()
297 target["name"] = OrderedDictWithDefaults()
298 target["name"]["index"] = 0
299 target['__MANY__'] = OrderedDictWithDefaults()
300 target['__MANY__']['name2'] = OrderedDictWithDefaults()
301 target['__MANY__']['subdict'] = OrderedDictWithDefaults()
302 target['__MANY__']['key'] = []
303 target['__MANY__']['text'] = "Ad infinitum"
304
305 with pytest.raises(Exception):
306 m_override(target, source)
307
308
309 def test_m_override_without_many_4():
310 source = OrderedDictWithDefaults()
311 source["name"] = OrderedDictWithDefaults()
312 source["name"]["index"] = "oil"
313 source["name2"] = OrderedDictWithDefaults()
314 source["name2"]["key"] = [1, 2, 3, 4]
315 source["name2"]["text"] = ""
316 source["name2"]["subdict"] = OrderedDictWithDefaults()
317 source["name2"]["subdict"]['family'] = 'ALL'
318
319 target = OrderedDictWithDefaults()
320 target["name"] = OrderedDictWithDefaults()
321 target["name"]["index"] = 0
322 target['__MANY__'] = OrderedDictWithDefaults()
323 target['__MANY__']['name2'] = OrderedDictWithDefaults()
324 target['__MANY__']['key'] = []
325 target['__MANY__']['text'] = "Ad infinitum"
326
327 with pytest.raises(Exception):
328 m_override(target, source)
329
330
331 # --- un_many
332
333 def test_un_many():
334 target = OrderedDictWithDefaults()
335 target["name"] = OrderedDictWithDefaults()
336 target["name"]["index"] = 0
337 target['__MANY__'] = OrderedDictWithDefaults()
338 target['__MANY__']['name2'] = OrderedDictWithDefaults()
339 target['__MANY__']['subdict'] = OrderedDictWithDefaults()
340 target['__MANY__']['key'] = []
341 target['__MANY__']['text'] = "Ad infinitum"
342
343 un_many(None) # harmless, no error/exception
344
345 un_many(target)
346
347 assert '__MANY__' not in list(target)
348
349
350 def test_un_many_keyerror():
351 """
352 Only way that this may happen is if dict is updated elsewhere.
353 """
354 class MyODWD(OrderedDictWithDefaults):
355 def __delitem__(self, _):
356 raise KeyError()
357
358 target = MyODWD()
359 target["name"] = "Anything"
360 target.defaults_ = {}
361 target.defaults_["name"] = True
362 target.defaults_["__MANY__"] = True
363 target['__MANY__'] = MyODWD()
364 target['__MANY__']['name2'] = MyODWD()
365 target['__MANY__']['subdict'] = MyODWD()
366 target['__MANY__']['key'] = []
367 target['__MANY__']['text'] = "Ad infinitum"
368
369 un_many(None) # harmless, no error/exception
370 un_many(target)
371
372 assert target
373 assert '__MANY__' in target
374
375
376 def test_un_many_keyerror_no_default():
377 """
378 Only way that this may happen is if dict is updated elsewhere.
379
380 And in this case, when there is no defaults_, the API raises the
381 current KeyError.
382 """
383 class MyODWD(OrderedDictWithDefaults):
384 def __delitem__(self, _):
385 raise KeyError()
386
387 target = MyODWD()
388 target["name"] = "Anything"
389 target['__MANY__'] = MyODWD()
390 target['__MANY__']['name2'] = MyODWD()
391 target['__MANY__']['subdict'] = MyODWD()
392 target['__MANY__']['key'] = []
393 target['__MANY__']['text'] = "Ad infinitum"
394
395 un_many(None) # harmless, no error/exception
396
397 with pytest.raises(KeyError):
398 un_many(target)
399
400 # --- itemstr
401
402
403 def test_itemstr():
404 parents = ["parent1", "parent2"]
405 text = itemstr(parents=parents, item="Value", value="Anything")
406 assert text == '[parent1][parent2]Value = Anything'
407
408
409 def test_itemstr_no_item():
410 parents = ["parent1", "parent2", "Value"]
411 text = itemstr(parents=parents, item=None, value="Anything")
412 assert text == '[parent1][parent2]Value = Anything'
413
414
415 def test_itemstr_no_parents_no_item():
416 text = itemstr(parents=None, item=None, value='Anything')
417 assert text == 'Anything'
418
419
420 def test_itemstr_no_parents():
421 text = itemstr(parents=None, item="Value", value='Anything')
422 assert text == 'Value = Anything'
423
424
425 def test_itemstr_no_parents_no_value():
426 text = itemstr(parents=None, item="Value", value=None)
427 assert text == 'Value'
428
429
430 # --- expand_many_section
431
432 @pytest.mark.parametrize(
433 'in_,out',
434 [
435 # basically a fancy version of string.split(',')
436 ('foo', ['foo']),
437 ('foo,bar', ['foo', 'bar']),
438 ('foo, bar', ['foo', ' bar']), # doesn't remove whitespace
439 # except that it doesn't split quoted things
440 ('"foo", "bar"', ['"foo"', ' "bar"']),
441 ('"foo,", "b,ar"', ['"foo,"', ' "b,ar"']), # doesn't split in " quotes
442 ("'foo', 'bar'", ["'foo'", " 'bar'"]),
443 ("'foo,', 'b,ar'", ["'foo,'", " 'b,ar'"]), # doesn"t split in ' quotes
444 ]
445 )
446 def test_SECTION_EXPAND_PATTERN(in_, out):
447 """It should split sections which contain commas.
448
449 This is used in order to expand [foo, bar] into [foo] and [bar].
450 """
451 assert SECTION_EXPAND_PATTERN.findall(in_) == out
452
453
454 @pytest.mark.parametrize(
455 'in_,out',
456 [
457 ('foo,bar', ['foo', 'bar']),
458 ('foo , bar', ['foo', 'bar']),
459 ('"foo", "bar"', ['foo', 'bar']),
460 ('"foo,", "b,ar"', ['foo,', 'b,ar']),
461 ]
462 )
463 def test_expand_many_section_expand(in_, out):
464 """It should expand sections which contain commas.
465
466 E.G. it should expand [foo, bar] into [foo] and [bar].
467 """
468 config = {in_: {'whatever': True}}
469 assert list(expand_many_section(config)) == out
470
471
472 def test_expand_many_section_order():
473 """It should maintain order when expanding sections."""
474 assert list(expand_many_section({
475 'a': {},
476 'b, a': {},
477 'c, b, a, d': {},
478 'e': {},
479 'a, e': {},
480 'f, e': {},
481 'g, h': {},
482 })) == ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
483
484
485 def test_expand_many_section_merge():
486 """It should merge sections together in definition order."""
487 config = expand_many_section({
488 'b': {'x': 1},
489 'b, a, c, d': {'x': 2},
490 'c': {'x': 3},
491 })
492 assert config == {
493 'b': {'x': 2},
494 'a': {'x': 2},
495 'c': {'x': 3},
496 'd': {'x': 2},
497 }
498 # bonus marks: ensure all values copied rather than referenced
499 config['a']['x'] = 4
500 assert config['b']['x'] == 2
501
502
503 def test_expand_many_section_merge_deep():
504 """It should deep-merge nested sections - see replicate()."""
505 config = expand_many_section({
506 'b': {'x': {'y': 1}},
507 'b, a, c, d': {'x': {'y': 2}},
508 'c': {'x': {'y': 3}},
509 })
510 assert config == {
511 'b': {'x': {'y': 2}},
512 'a': {'x': {'y': 2}},
513 'c': {'x': {'y': 3}},
514 'd': {'x': {'y': 2}},
515 }
516 # bonus marks: ensure all values are unique objects
517 # (i.e. they have been copied rather than referenced)
518 config['a']['x']['y'] = 4
519 assert config['b']['x']['y'] == 2