Debian Codegraph @

tests/config.py

raw
1 import pickle
2 import os
3 from os.path import join
4
5 from unittest.mock import patch, call, Mock
6 import pytest
7 from pytest_relaxed import raises
8
9 from invoke import config as config_mod # for accessing mocks
10 from invoke.runners import Local
11 from invoke.config import Config
12 from invoke.exceptions import (
13 AmbiguousEnvVar,
14 UncastableEnvVar,
15 UnknownFileType,
16 UnpicklableConfigMember,
17 )
18
19 from _util import skip_if_windows, support
20
21
22 pytestmark = pytest.mark.usefixtures("integration")
23
24
25 CONFIGS_PATH = "configs"
26 TYPES = ("yaml", "yml", "json", "python")
27
28
29 def _load(kwarg, type_, **kwargs):
30 path = join(CONFIGS_PATH, type_ + "/")
31 kwargs[kwarg] = path
32 return Config(**kwargs)
33
34
35 class Config_:
36 class class_attrs:
37 # TODO: move all other non-data-bearing kwargs to this mode
38 class prefix:
39 def defaults_to_invoke(self):
40 assert Config().prefix == "invoke"
41
42 @patch.object(Config, "_load_yaml")
43 def informs_config_filenames(self, load_yaml):
44 class MyConf(Config):
45 prefix = "other"
46
47 MyConf(system_prefix="dir/")
48 load_yaml.assert_any_call("dir/other.yaml")
49
50 def informs_env_var_prefix(self):
51 os.environ["OTHER_FOO"] = "bar"
52
53 class MyConf(Config):
54 prefix = "other"
55
56 c = MyConf(defaults={"foo": "notbar"})
57 c.load_shell_env()
58 assert c.foo == "bar"
59
60 class file_prefix:
61 def defaults_to_None(self):
62 assert Config().file_prefix is None
63
64 @patch.object(Config, "_load_yaml")
65 def informs_config_filenames(self, load_yaml):
66 class MyConf(Config):
67 file_prefix = "other"
68
69 MyConf(system_prefix="dir/")
70 load_yaml.assert_any_call("dir/other.yaml")
71
72 class env_prefix:
73 def defaults_to_None(self):
74 assert Config().env_prefix is None
75
76 def informs_env_vars_loaded(self):
77 os.environ["OTHER_FOO"] = "bar"
78
79 class MyConf(Config):
80 env_prefix = "other"
81
82 c = MyConf(defaults={"foo": "notbar"})
83 c.load_shell_env()
84 assert c.foo == "bar"
85
86 class global_defaults:
87 @skip_if_windows
88 def basic_settings(self):
89 # Just a catchall for what the baseline config settings should
90 # be...for some reason we're not actually capturing all of these
91 # reliably (even if their defaults are often implied by the tests
92 # which override them, e.g. runner tests around warn=True, etc).
93 expected = {
94 "run": {
95 "asynchronous": False,
96 "disown": False,
97 "dry": False,
98 "echo": False,
99 "echo_format": "\033[1;37m{command}\033[0m",
100 "echo_stdin": None,
101 "encoding": None,
102 "env": {},
103 "err_stream": None,
104 "fallback": True,
105 "hide": None,
106 "in_stream": None,
107 "out_stream": None,
108 "pty": False,
109 "replace_env": False,
110 "shell": "bash",
111 "warn": False,
112 "watchers": [],
113 },
114 "runners": {"local": Local},
115 "sudo": {
116 "password": None,
117 "prompt": "[sudo] password: ",
118 "user": None,
119 },
120 "tasks": {
121 "auto_dash_names": True,
122 "collection_name": "tasks",
123 "dedupe": True,
124 "executor_class": None,
125 "ignore_unknown_help": False,
126 "search_root": None,
127 },
128 "timeouts": {"command": None},
129 }
130 assert Config.global_defaults() == expected
131
132 class init:
133 "__init__"
134
135 def can_be_empty(self):
136 assert Config().__class__ == Config # derp
137
138 @patch.object(Config, "_load_yaml")
139 def configure_global_location_prefix(self, load_yaml):
140 # This is a bit funky but more useful than just replicating the
141 # same test farther down?
142 Config(system_prefix="meh/")
143 load_yaml.assert_any_call("meh/invoke.yaml")
144
145 @skip_if_windows
146 @patch.object(Config, "_load_yaml")
147 def default_system_prefix_is_etc(self, load_yaml):
148 # TODO: make this work on Windows somehow without being a total
149 # tautology? heh.
150 Config()
151 load_yaml.assert_any_call("/etc/invoke.yaml")
152
153 @patch.object(Config, "_load_yaml")
154 def configure_user_location_prefix(self, load_yaml):
155 Config(user_prefix="whatever/")
156 load_yaml.assert_any_call("whatever/invoke.yaml")
157
158 @patch.object(Config, "_load_yaml")
159 def default_user_prefix_is_homedir_plus_dot(self, load_yaml):
160 Config()
161 # NOTE: expects autouse fixture which patches expanduser
162 # Make sure we called expanduser() with tilde syntax
163 config_mod.expanduser.assert_any_call("~/.invoke.yaml")
164 # Make sure result of that call was passed into load_yaml
165 load_yaml.assert_any_call(config_mod.expanduser("~/.invoke.yaml"))
166
167 @patch.object(Config, "_load_yaml")
168 def configure_project_location(self, load_yaml):
169 Config(project_location="someproject").load_project()
170 load_yaml.assert_any_call(join("someproject", "invoke.yaml"))
171
172 @patch.object(Config, "_load_yaml")
173 def configure_runtime_path(self, load_yaml):
174 Config(runtime_path="some/path.yaml").load_runtime()
175 load_yaml.assert_any_call("some/path.yaml")
176
177 def accepts_defaults_dict_kwarg(self):
178 c = Config(defaults={"super": "low level"})
179 assert c.super == "low level"
180
181 def overrides_dict_is_first_posarg(self):
182 c = Config({"new": "data", "run": {"hide": True}})
183 assert c.run.hide is True # default is False
184 assert c.run.warn is False # in global defaults, untouched
185 assert c.new == "data" # data only present at overrides layer
186
187 def overrides_dict_is_also_a_kwarg(self):
188 c = Config(overrides={"run": {"hide": True}})
189 assert c.run.hide is True
190
191 @patch.object(Config, "load_system")
192 @patch.object(Config, "load_user")
193 @patch.object(Config, "merge")
194 def system_and_user_files_loaded_automatically(
195 self, merge, load_u, load_s
196 ):
197 Config()
198 load_s.assert_called_once_with(merge=False)
199 load_u.assert_called_once_with(merge=False)
200 merge.assert_called_once_with()
201
202 @patch.object(Config, "load_system")
203 @patch.object(Config, "load_user")
204 def can_defer_loading_system_and_user_files(self, load_u, load_s):
205 config = Config(lazy=True)
206 assert not load_s.called
207 assert not load_u.called
208 # Make sure default levels are still in place! (When bug present,
209 # i.e. merge() never called, config appears effectively empty.)
210 assert config.run.echo is False
211
212 class basic_API:
213 "Basic API components"
214
215 def can_be_used_directly_after_init(self):
216 # No load() here...
217 c = Config({"lots of these": "tests look similar"})
218 assert c["lots of these"] == "tests look similar"
219
220 def allows_dict_and_attr_access(self):
221 # TODO: combine with tests for Context probably
222 c = Config({"foo": "bar"})
223 assert c.foo == "bar"
224 assert c["foo"] == "bar"
225
226 def nested_dict_values_also_allow_dual_access(self):
227 # TODO: ditto
228 c = Config({"foo": "bar", "biz": {"baz": "boz"}})
229 # Sanity check - nested doesn't somehow kill simple top level
230 assert c.foo == "bar"
231 assert c["foo"] == "bar"
232 # Actual check
233 assert c.biz.baz == "boz"
234 assert c["biz"]["baz"] == "boz"
235 assert c.biz["baz"] == "boz"
236 assert c["biz"].baz == "boz"
237
238 def attr_access_has_useful_error_msg(self):
239 c = Config()
240 try:
241 c.nope
242 except AttributeError as e:
243 expected = """
244 No attribute or config key found for 'nope'
245
246 Valid keys: ['run', 'runners', 'sudo', 'tasks', 'timeouts']
247
248 Valid real attributes: ['clear', 'clone', 'env_prefix', 'file_prefix', 'from_data', 'global_defaults', 'load_base_conf_files', 'load_collection', 'load_defaults', 'load_overrides', 'load_project', 'load_runtime', 'load_shell_env', 'load_system', 'load_user', 'merge', 'pop', 'popitem', 'prefix', 'set_project_location', 'set_runtime_path', 'setdefault', 'update']
249 """.strip() # noqa
250 assert str(e) == expected
251 else:
252 assert False, "Didn't get an AttributeError on bad key!"
253
254 def subkeys_get_merged_not_overwritten(self):
255 # Ensures nested keys merge deeply instead of shallowly.
256 defaults = {"foo": {"bar": "baz"}}
257 overrides = {"foo": {"notbar": "notbaz"}}
258 c = Config(defaults=defaults, overrides=overrides)
259 assert c.foo.notbar == "notbaz"
260 assert c.foo.bar == "baz"
261
262 def is_iterable_like_dict(self):
263 c = Config(defaults={"a": 1, "b": 2})
264 assert set(c.keys()) == {"a", "b"}
265 assert set(list(c)) == {"a", "b"}
266
267 def supports_readonly_dict_protocols(self):
268 # Use single-keypair dict to avoid sorting problems in tests.
269 c = Config(defaults={"foo": "bar"})
270 c2 = Config(defaults={"foo": "bar"})
271 assert "foo" in c
272 assert "foo" in c2 # mostly just to trigger loading :x
273 assert c == c2
274 assert len(c) == 1
275 assert c.get("foo") == "bar"
276 assert list(c.items()) == [("foo", "bar")]
277 assert list(c.keys()) == ["foo"]
278 assert list(c.values()) == ["bar"]
279
280 class runtime_loading_of_defaults_and_overrides:
281 def defaults_can_be_given_via_method(self):
282 c = Config()
283 assert "foo" not in c
284 c.load_defaults({"foo": "bar"})
285 assert c.foo == "bar"
286
287 def defaults_can_skip_merging(self):
288 c = Config()
289 c.load_defaults({"foo": "bar"}, merge=False)
290 assert "foo" not in c
291 c.merge()
292 assert c.foo == "bar"
293
294 def overrides_can_be_given_via_method(self):
295 c = Config(defaults={"foo": "bar"})
296 assert c.foo == "bar" # defaults level
297 c.load_overrides({"foo": "notbar"})
298 assert c.foo == "notbar" # overrides level
299
300 def overrides_can_skip_merging(self):
301 c = Config()
302 c.load_overrides({"foo": "bar"}, merge=False)
303 assert "foo" not in c
304 c.merge()
305 assert c.foo == "bar"
306
307 class deletion_methods:
308 def pop(self):
309 # Root
310 c = Config(defaults={"foo": "bar"})
311 assert c.pop("foo") == "bar"
312 assert c == {}
313 # With the default arg
314 assert c.pop("wut", "fine then") == "fine then"
315 # Leaf (different key to avoid AmbiguousMergeError)
316 c.nested = {"leafkey": "leafval"}
317 assert c.nested.pop("leafkey") == "leafval"
318 assert c == {"nested": {}}
319
320 def delitem(self):
321 "__delitem__"
322 c = Config(defaults={"foo": "bar"})
323 del c["foo"]
324 assert c == {}
325 c.nested = {"leafkey": "leafval"}
326 del c.nested["leafkey"]
327 assert c == {"nested": {}}
328
329 def delattr(self):
330 "__delattr__"
331 c = Config(defaults={"foo": "bar"})
332 del c.foo
333 assert c == {}
334 c.nested = {"leafkey": "leafval"}
335 del c.nested.leafkey
336 assert c == {"nested": {}}
337
338 def clear(self):
339 c = Config(defaults={"foo": "bar"})
340 c.clear()
341 assert c == {}
342 c.nested = {"leafkey": "leafval"}
343 c.nested.clear()
344 assert c == {"nested": {}}
345
346 def popitem(self):
347 c = Config(defaults={"foo": "bar"})
348 assert c.popitem() == ("foo", "bar")
349 assert c == {}
350 c.nested = {"leafkey": "leafval"}
351 assert c.nested.popitem() == ("leafkey", "leafval")
352 assert c == {"nested": {}}
353
354 class modification_methods:
355 def setitem(self):
356 c = Config(defaults={"foo": "bar"})
357 c["foo"] = "notbar"
358 assert c.foo == "notbar"
359 del c["foo"]
360 c["nested"] = {"leafkey": "leafval"}
361 assert c == {"nested": {"leafkey": "leafval"}}
362
363 def setdefault(self):
364 c = Config({"foo": "bar", "nested": {"leafkey": "leafval"}})
365 assert c.setdefault("foo") == "bar"
366 assert c.nested.setdefault("leafkey") == "leafval"
367 assert c.setdefault("notfoo", "notbar") == "notbar"
368 assert c.notfoo == "notbar"
369 nested = c.nested.setdefault("otherleaf", "otherval")
370 assert nested == "otherval"
371 assert c.nested.otherleaf == "otherval"
372
373 def update(self):
374 c = Config(
375 defaults={"foo": "bar", "nested": {"leafkey": "leafval"}}
376 )
377 # Regular update(dict)
378 c.update({"foo": "notbar"})
379 assert c.foo == "notbar"
380 c.nested.update({"leafkey": "otherval"})
381 assert c.nested.leafkey == "otherval"
382 # Apparently allowed but wholly useless
383 c.update()
384 expected = {"foo": "notbar", "nested": {"leafkey": "otherval"}}
385 assert c == expected
386 # Kwarg edition
387 c.update(foo="otherbar")
388 assert c.foo == "otherbar"
389 # Iterator of 2-tuples edition
390 c.nested.update(
391 [("leafkey", "yetanotherval"), ("newleaf", "turnt")]
392 )
393 assert c.nested.leafkey == "yetanotherval"
394 assert c.nested.newleaf == "turnt"
395
396 def reinstatement_of_deleted_values_works_ok(self):
397 # Sounds like a stupid thing to test, but when we have to track
398 # deletions and mutations manually...it's an easy thing to overlook
399 c = Config(defaults={"foo": "bar"})
400 assert c.foo == "bar"
401 del c["foo"]
402 # Sanity checks
403 assert "foo" not in c
404 assert len(c) == 0
405 # Put it back again...as a different value, for funsies
406 c.foo = "formerly bar"
407 # And make sure it stuck
408 assert c.foo == "formerly bar"
409
410 def deleting_parent_keys_of_deleted_keys_subsumes_them(self):
411 c = Config({"foo": {"bar": "biz"}})
412 del c.foo["bar"]
413 del c.foo
414 # Make sure we didn't somehow still end up with {'foo': {'bar':
415 # None}}
416 assert c._deletions == {"foo": None}
417
418 def supports_mutation_via_attribute_access(self):
419 c = Config({"foo": "bar"})
420 assert c.foo == "bar"
421 c.foo = "notbar"
422 assert c.foo == "notbar"
423 assert c["foo"] == "notbar"
424
425 def supports_nested_mutation_via_attribute_access(self):
426 c = Config({"foo": {"bar": "biz"}})
427 assert c.foo.bar == "biz"
428 c.foo.bar = "notbiz"
429 assert c.foo.bar == "notbiz"
430 assert c["foo"]["bar"] == "notbiz"
431
432 def real_attrs_and_methods_win_over_attr_proxying(self):
433 # Setup
434 class MyConfig(Config):
435 myattr = None
436
437 def mymethod(self):
438 return 7
439
440 c = MyConfig({"myattr": "foo", "mymethod": "bar"})
441 # By default, attr and config value separate
442 assert c.myattr is None
443 assert c["myattr"] == "foo"
444 # After a setattr, same holds true
445 c.myattr = "notfoo"
446 assert c.myattr == "notfoo"
447 assert c["myattr"] == "foo"
448 # Method and config value separate
449 assert callable(c.mymethod)
450 assert c.mymethod() == 7
451 assert c["mymethod"] == "bar"
452
453 # And same after setattr
454 def monkeys():
455 return 13
456
457 c.mymethod = monkeys
458 assert c.mymethod() == 13
459 assert c["mymethod"] == "bar"
460
461 def config_itself_stored_as_private_name(self):
462 # I.e. one can refer to a key called 'config', which is relatively
463 # commonplace (e.g. <Config>.myservice.config -> a config file
464 # contents or path or etc)
465 c = Config()
466 c["foo"] = {"bar": "baz"}
467 c["whatever"] = {"config": "myconfig"}
468 assert c.foo.bar == "baz"
469 assert c.whatever.config == "myconfig"
470
471 def inherited_real_attrs_also_win_over_config_keys(self):
472 class MyConfigParent(Config):
473 parent_attr = 17
474
475 class MyConfig(MyConfigParent):
476 pass
477
478 c = MyConfig()
479 assert c.parent_attr == 17
480 c.parent_attr = 33
481 oops = "Oops! Looks like config won over real attr!"
482 assert "parent_attr" not in c, oops
483 assert c.parent_attr == 33
484 c["parent_attr"] = "fifteen"
485 assert c.parent_attr == 33
486 assert c["parent_attr"] == "fifteen"
487
488 def nonexistent_attrs_can_be_set_to_create_new_top_level_configs(self):
489 # I.e. some_config.foo = 'bar' is like some_config['foo'] = 'bar'.
490 # When this test breaks it usually means some_config.foo = 'bar'
491 # sets a regular attribute - and the configuration itself is never
492 # touched!
493 c = Config()
494 c.some_setting = "some_value"
495 assert c["some_setting"] == "some_value"
496
497 def nonexistent_attr_setting_works_nested_too(self):
498 c = Config()
499 c.a_nest = {}
500 assert c["a_nest"] == {}
501 c.a_nest.an_egg = True
502 assert c["a_nest"]["an_egg"]
503
504 def string_display(self):
505 "__str__ and friends"
506 config = Config(defaults={"foo": "bar"})
507 assert repr(config) == "<Config: {'foo': 'bar'}>"
508
509 def merging_does_not_wipe_user_modifications_or_deletions(self):
510 c = Config({"foo": {"bar": "biz"}, "error": True})
511 c.foo.bar = "notbiz"
512 del c["error"]
513 assert c["foo"]["bar"] == "notbiz"
514 assert "error" not in c
515 c.merge()
516 # Will be back to 'biz' if user changes don't get saved on their
517 # own (previously they are just mutations on the cached central
518 # config)
519 assert c["foo"]["bar"] == "notbiz"
520 # And this would still be here, too
521 assert "error" not in c
522
523 class config_file_loading:
524 "Configuration file loading"
525
526 def system_global(self):
527 "Systemwide conf files"
528 # NOTE: using lazy=True to avoid autoloading so we can prove
529 # load_system() works.
530 for type_ in TYPES:
531 config = _load("system_prefix", type_, lazy=True)
532 assert "outer" not in config
533 config.load_system()
534 assert config.outer.inner.hooray == type_
535
536 def system_can_skip_merging(self):
537 config = _load("system_prefix", "yml", lazy=True)
538 assert "outer" not in config._system
539 assert "outer" not in config
540 config.load_system(merge=False)
541 # Test that we loaded into the per-level dict, but not the
542 # central/merged config.
543 assert "outer" in config._system
544 assert "outer" not in config
545
546 def user_specific(self):
547 "User-specific conf files"
548 # NOTE: using lazy=True to avoid autoloading so we can prove
549 # load_user() works.
550 for type_ in TYPES:
551 config = _load("user_prefix", type_, lazy=True)
552 assert "outer" not in config
553 config.load_user()
554 assert config.outer.inner.hooray == type_
555
556 def user_can_skip_merging(self):
557 config = _load("user_prefix", "yml", lazy=True)
558 assert "outer" not in config._user
559 assert "outer" not in config
560 config.load_user(merge=False)
561 # Test that we loaded into the per-level dict, but not the
562 # central/merged config.
563 assert "outer" in config._user
564 assert "outer" not in config
565
566 def project_specific(self):
567 "Local-to-project conf files"
568 for type_ in TYPES:
569 c = Config(project_location=join(CONFIGS_PATH, type_))
570 assert "outer" not in c
571 c.load_project()
572 assert c.outer.inner.hooray == type_
573
574 def project_can_skip_merging(self):
575 config = Config(
576 project_location=join(CONFIGS_PATH, "yml"), lazy=True
577 )
578 assert "outer" not in config._project
579 assert "outer" not in config
580 config.load_project(merge=False)
581 # Test that we loaded into the per-level dict, but not the
582 # central/merged config.
583 assert "outer" in config._project
584 assert "outer" not in config
585
586 def loads_no_project_specific_file_if_no_project_location_given(self):
587 c = Config()
588 assert c._project_path is None
589 c.load_project()
590 assert list(c._project.keys()) == []
591 defaults = ["tasks", "run", "runners", "sudo", "timeouts"]
592 assert set(c.keys()) == set(defaults)
593
594 def project_location_can_be_set_after_init(self):
595 c = Config()
596 assert "outer" not in c
597 c.set_project_location(join(CONFIGS_PATH, "yml"))
598 c.load_project()
599 assert c.outer.inner.hooray == "yml"
600
601 def runtime_conf_via_cli_flag(self):
602 c = Config(runtime_path=join(CONFIGS_PATH, "yaml", "invoke.yaml"))
603 c.load_runtime()
604 assert c.outer.inner.hooray == "yaml"
605
606 def runtime_can_skip_merging(self):
607 path = join(CONFIGS_PATH, "yaml", "invoke.yaml")
608 config = Config(runtime_path=path, lazy=True)
609 assert "outer" not in config._runtime
610 assert "outer" not in config
611 config.load_runtime(merge=False)
612 # Test that we loaded into the per-level dict, but not the
613 # central/merged config.
614 assert "outer" in config._runtime
615 assert "outer" not in config
616
617 @raises(UnknownFileType)
618 def unknown_suffix_in_runtime_path_raises_useful_error(self):
619 c = Config(runtime_path=join(CONFIGS_PATH, "screw.ini"))
620 c.load_runtime()
621
622 def python_modules_dont_load_special_vars(self):
623 "Python modules don't load special vars"
624 # Borrow another test's Python module.
625 c = _load("system_prefix", "python")
626 # Sanity test that lowercase works
627 assert c.outer.inner.hooray == "python"
628 # Real test that builtins, etc are stripped out
629 for special in ("builtins", "file", "package", "name", "doc"):
630 assert "__{}__".format(special) not in c
631
632 def python_modules_except_usefully_on_unpicklable_modules(self):
633 # Re: #556; when bug present, a TypeError pops up instead (granted,
634 # at merge time, but we want it to raise ASAP, so we're testing the
635 # intended new behavior: raising at config load time.
636 c = Config()
637 c.set_runtime_path(join(support, "has_modules.py"))
638 expected = r"'os' is a module.*giving a tasks file.*mistake"
639 with pytest.raises(UnpicklableConfigMember, match=expected):
640 c.load_runtime(merge=False)
641
642 @patch("invoke.config.debug")
643 def nonexistent_files_are_skipped_and_logged(self, mock_debug):
644 c = Config()
645 c._load_yml = Mock(side_effect=IOError(2, "aw nuts"))
646 c.set_runtime_path("is-a.yml") # Triggers use of _load_yml
647 c.load_runtime()
648 mock_debug.assert_any_call("Didn't see any is-a.yml, skipping.")
649
650 @raises(IOError)
651 def non_missing_file_IOErrors_are_raised(self):
652 c = Config()
653 c._load_yml = Mock(side_effect=IOError(17, "uh, what?"))
654 c.set_runtime_path("is-a.yml") # Triggers use of _load_yml
655 c.load_runtime()
656
657 class collection_level_config_loading:
658 def performed_explicitly_and_directly(self):
659 # TODO: do we want to update the other levels to allow 'direct'
660 # loading like this, now that they all have explicit methods?
661 c = Config()
662 assert "foo" not in c
663 c.load_collection({"foo": "bar"})
664 assert c.foo == "bar"
665
666 def merging_can_be_deferred(self):
667 c = Config()
668 assert "foo" not in c._collection
669 assert "foo" not in c
670 c.load_collection({"foo": "bar"}, merge=False)
671 assert "foo" in c._collection
672 assert "foo" not in c
673
674 class comparison_and_hashing:
675 def comparison_looks_at_merged_config(self):
676 c1 = Config(defaults={"foo": {"bar": "biz"}})
677 # Empty defaults to suppress global_defaults
678 c2 = Config(defaults={}, overrides={"foo": {"bar": "biz"}})
679 assert c1 is not c2
680 assert c1._defaults != c2._defaults
681 assert c1 == c2
682
683 def allows_comparison_with_real_dicts(self):
684 c = Config({"foo": {"bar": "biz"}})
685 assert c["foo"] == {"bar": "biz"}
686
687 @raises(TypeError)
688 def is_explicitly_not_hashable(self):
689 hash(Config())
690
691 class env_vars:
692 "Environment variables"
693
694 def base_case_defaults_to_INVOKE_prefix(self):
695 os.environ["INVOKE_FOO"] = "bar"
696 c = Config(defaults={"foo": "notbar"})
697 c.load_shell_env()
698 assert c.foo == "bar"
699
700 def non_predeclared_settings_do_not_get_consumed(self):
701 os.environ["INVOKE_HELLO"] = "is it me you're looking for?"
702 c = Config()
703 c.load_shell_env()
704 assert "HELLO" not in c
705 assert "hello" not in c
706
707 def underscores_top_level(self):
708 os.environ["INVOKE_FOO_BAR"] = "biz"
709 c = Config(defaults={"foo_bar": "notbiz"})
710 c.load_shell_env()
711 assert c.foo_bar == "biz"
712
713 def underscores_nested(self):
714 os.environ["INVOKE_FOO_BAR"] = "biz"
715 c = Config(defaults={"foo": {"bar": "notbiz"}})
716 c.load_shell_env()
717 assert c.foo.bar == "biz"
718
719 def both_types_of_underscores_mixed(self):
720 os.environ["INVOKE_FOO_BAR_BIZ"] = "baz"
721 c = Config(defaults={"foo_bar": {"biz": "notbaz"}})
722 c.load_shell_env()
723 assert c.foo_bar.biz == "baz"
724
725 @raises(AmbiguousEnvVar)
726 def ambiguous_underscores_dont_guess(self):
727 os.environ["INVOKE_FOO_BAR"] = "biz"
728 c = Config(defaults={"foo_bar": "wat", "foo": {"bar": "huh"}})
729 c.load_shell_env()
730
731 class type_casting:
732 def strings_replaced_with_env_value(self):
733 os.environ["INVOKE_FOO"] = "myvalue"
734 c = Config(defaults={"foo": "myoldvalue"})
735 c.load_shell_env()
736 assert c.foo == "myvalue"
737 assert isinstance(c.foo, str)
738
739 def None_replaced(self):
740 os.environ["INVOKE_FOO"] = "something"
741 c = Config(defaults={"foo": None})
742 c.load_shell_env()
743 assert c.foo == "something"
744
745 def booleans(self):
746 for input_, result in (
747 ("0", False),
748 ("1", True),
749 ("", False),
750 ("meh", True),
751 ("false", True),
752 ):
753 os.environ["INVOKE_FOO"] = input_
754 c = Config(defaults={"foo": bool()})
755 c.load_shell_env()
756 assert c.foo == result
757
758 def boolean_type_inputs_with_non_boolean_defaults(self):
759 for input_ in ("0", "1", "", "meh", "false"):
760 os.environ["INVOKE_FOO"] = input_
761 c = Config(defaults={"foo": "bar"})
762 c.load_shell_env()
763 assert c.foo == input_
764
765 def numeric_types_become_casted(self):
766 tests = [
767 (int, "5", 5),
768 (float, "5.5", 5.5),
769 ]
770 for old, new_, result in tests:
771 os.environ["INVOKE_FOO"] = new_
772 c = Config(defaults={"foo": old()})
773 c.load_shell_env()
774 assert c.foo == result
775
776 def arbitrary_types_work_too(self):
777 os.environ["INVOKE_FOO"] = "whatever"
778
779 class Meh:
780 def __init__(self, thing=None):
781 pass
782
783 old_obj = Meh()
784 c = Config(defaults={"foo": old_obj})
785 c.load_shell_env()
786 assert isinstance(c.foo, Meh)
787 assert c.foo is not old_obj
788
789 class uncastable_types:
790 @raises(UncastableEnvVar)
791 def _uncastable_type(self, default):
792 os.environ["INVOKE_FOO"] = "stuff"
793 c = Config(defaults={"foo": default})
794 c.load_shell_env()
795
796 def lists(self):
797 self._uncastable_type(["a", "list"])
798
799 def tuples(self):
800 self._uncastable_type(("a", "tuple"))
801
802 class hierarchy:
803 "Config hierarchy in effect"
804
805 #
806 # NOTE: most of these just leverage existing test fixtures (which live
807 # in their own directories & have differing values for the 'hooray'
808 # key), since we normally don't need more than 2-3 different file
809 # locations for any one test.
810 #
811
812 def collection_overrides_defaults(self):
813 c = Config(defaults={"nested": {"setting": "default"}})
814 c.load_collection({"nested": {"setting": "collection"}})
815 assert c.nested.setting == "collection"
816
817 def systemwide_overrides_collection(self):
818 c = Config(system_prefix=join(CONFIGS_PATH, "yaml/"))
819 c.load_collection({"outer": {"inner": {"hooray": "defaults"}}})
820 assert c.outer.inner.hooray == "yaml"
821
822 def user_overrides_systemwide(self):
823 c = Config(
824 system_prefix=join(CONFIGS_PATH, "yaml/"),
825 user_prefix=join(CONFIGS_PATH, "json/"),
826 )
827 assert c.outer.inner.hooray == "json"
828
829 def user_overrides_collection(self):
830 c = Config(user_prefix=join(CONFIGS_PATH, "json/"))
831 c.load_collection({"outer": {"inner": {"hooray": "defaults"}}})
832 assert c.outer.inner.hooray == "json"
833
834 def project_overrides_user(self):
835 c = Config(
836 user_prefix=join(CONFIGS_PATH, "json/"),
837 project_location=join(CONFIGS_PATH, "yaml"),
838 )
839 c.load_project()
840 assert c.outer.inner.hooray == "yaml"
841
842 def project_overrides_systemwide(self):
843 c = Config(
844 system_prefix=join(CONFIGS_PATH, "json/"),
845 project_location=join(CONFIGS_PATH, "yaml"),
846 )
847 c.load_project()
848 assert c.outer.inner.hooray == "yaml"
849
850 def project_overrides_collection(self):
851 c = Config(project_location=join(CONFIGS_PATH, "yaml"))
852 c.load_project()
853 c.load_collection({"outer": {"inner": {"hooray": "defaults"}}})
854 assert c.outer.inner.hooray == "yaml"
855
856 def env_vars_override_project(self):
857 os.environ["INVOKE_OUTER_INNER_HOORAY"] = "env"
858 c = Config(project_location=join(CONFIGS_PATH, "yaml"))
859 c.load_project()
860 c.load_shell_env()
861 assert c.outer.inner.hooray == "env"
862
863 def env_vars_override_user(self):
864 os.environ["INVOKE_OUTER_INNER_HOORAY"] = "env"
865 c = Config(user_prefix=join(CONFIGS_PATH, "yaml/"))
866 c.load_shell_env()
867 assert c.outer.inner.hooray == "env"
868
869 def env_vars_override_systemwide(self):
870 os.environ["INVOKE_OUTER_INNER_HOORAY"] = "env"
871 c = Config(system_prefix=join(CONFIGS_PATH, "yaml/"))
872 c.load_shell_env()
873 assert c.outer.inner.hooray == "env"
874
875 def env_vars_override_collection(self):
876 os.environ["INVOKE_OUTER_INNER_HOORAY"] = "env"
877 c = Config()
878 c.load_collection({"outer": {"inner": {"hooray": "defaults"}}})
879 c.load_shell_env()
880 assert c.outer.inner.hooray == "env"
881
882 def runtime_overrides_env_vars(self):
883 os.environ["INVOKE_OUTER_INNER_HOORAY"] = "env"
884 c = Config(runtime_path=join(CONFIGS_PATH, "json", "invoke.json"))
885 c.load_runtime()
886 c.load_shell_env()
887 assert c.outer.inner.hooray == "json"
888
889 def runtime_overrides_project(self):
890 c = Config(
891 runtime_path=join(CONFIGS_PATH, "json", "invoke.json"),
892 project_location=join(CONFIGS_PATH, "yaml"),
893 )
894 c.load_runtime()
895 c.load_project()
896 assert c.outer.inner.hooray == "json"
897
898 def runtime_overrides_user(self):
899 c = Config(
900 runtime_path=join(CONFIGS_PATH, "json", "invoke.json"),
901 user_prefix=join(CONFIGS_PATH, "yaml/"),
902 )
903 c.load_runtime()
904 assert c.outer.inner.hooray == "json"
905
906 def runtime_overrides_systemwide(self):
907 c = Config(
908 runtime_path=join(CONFIGS_PATH, "json", "invoke.json"),
909 system_prefix=join(CONFIGS_PATH, "yaml/"),
910 )
911 c.load_runtime()
912 assert c.outer.inner.hooray == "json"
913
914 def runtime_overrides_collection(self):
915 c = Config(runtime_path=join(CONFIGS_PATH, "json", "invoke.json"))
916 c.load_collection({"outer": {"inner": {"hooray": "defaults"}}})
917 c.load_runtime()
918 assert c.outer.inner.hooray == "json"
919
920 def cli_overrides_override_all(self):
921 "CLI-driven overrides win vs all other layers"
922 # TODO: expand into more explicit tests like the above? meh
923 c = Config(
924 overrides={"outer": {"inner": {"hooray": "overrides"}}},
925 runtime_path=join(CONFIGS_PATH, "json", "invoke.json"),
926 )
927 c.load_runtime()
928 assert c.outer.inner.hooray == "overrides"
929
930 def yaml_prevents_yml_json_or_python(self):
931 c = Config(system_prefix=join(CONFIGS_PATH, "all-four/"))
932 assert "json-only" not in c
933 assert "python_only" not in c
934 assert "yml-only" not in c
935 assert "yaml-only" in c
936 assert c.shared == "yaml-value"
937
938 def yml_prevents_json_or_python(self):
939 c = Config(system_prefix=join(CONFIGS_PATH, "three-of-em/"))
940 assert "json-only" not in c
941 assert "python_only" not in c
942 assert "yml-only" in c
943 assert c.shared == "yml-value"
944
945 def json_prevents_python(self):
946 c = Config(system_prefix=join(CONFIGS_PATH, "json-and-python/"))
947 assert "python_only" not in c
948 assert "json-only" in c
949 assert c.shared == "json-value"
950
951 class clone:
952 def preserves_basic_members(self):
953 c1 = Config(
954 defaults={"key": "default"},
955 overrides={"key": "override"},
956 system_prefix="global",
957 user_prefix="user",
958 project_location="project",
959 runtime_path="runtime.yaml",
960 )
961 c2 = c1.clone()
962 # NOTE: expecting identical defaults also implicitly tests that
963 # clone() passes in defaults= instead of doing an empty init +
964 # copy. (When that is not the case, we end up with
965 # global_defaults() being rerun and re-added to _defaults...)
966 assert c2._defaults == c1._defaults
967 assert c2._defaults is not c1._defaults
968 assert c2._overrides == c1._overrides
969 assert c2._overrides is not c1._overrides
970 assert c2._system_prefix == c1._system_prefix
971 assert c2._user_prefix == c1._user_prefix
972 assert c2._project_prefix == c1._project_prefix
973 assert c2.prefix == c1.prefix
974 assert c2.file_prefix == c1.file_prefix
975 assert c2.env_prefix == c1.env_prefix
976 assert c2._runtime_path == c1._runtime_path
977
978 def preserves_merged_config(self):
979 c = Config(
980 defaults={"key": "default"}, overrides={"key": "override"}
981 )
982 assert c.key == "override"
983 assert c._defaults["key"] == "default"
984 c2 = c.clone()
985 assert c2.key == "override"
986 assert c2._defaults["key"] == "default"
987 assert c2._overrides["key"] == "override"
988
989 def preserves_file_data(self):
990 c = Config(system_prefix=join(CONFIGS_PATH, "yaml/"))
991 assert c.outer.inner.hooray == "yaml"
992 c2 = c.clone()
993 assert c2.outer.inner.hooray == "yaml"
994 assert c2._system == {"outer": {"inner": {"hooray": "yaml"}}}
995
996 @patch.object(
997 Config,
998 "_load_yaml",
999 return_value={"outer": {"inner": {"hooray": "yaml"}}},
1000 )
1001 def does_not_reload_file_data(self, load_yaml):
1002 path = join(CONFIGS_PATH, "yaml/")
1003 c = Config(system_prefix=path)
1004 c2 = c.clone()
1005 assert c2.outer.inner.hooray == "yaml"
1006 # Crummy way to say "only got called with this specific invocation
1007 # one time" (since assert_calls_with gets mad about other
1008 # invocations w/ different args)
1009 calls = load_yaml.call_args_list
1010 my_call = call("{}invoke.yaml".format(path))
1011 try:
1012 calls.remove(my_call)
1013 assert my_call not in calls
1014 except ValueError:
1015 err = "{} not found in {} even once!"
1016 assert False, err.format(my_call, calls)
1017
1018 def preserves_env_data(self):
1019 os.environ["INVOKE_FOO"] = "bar"
1020 c = Config(defaults={"foo": "notbar"})
1021 c.load_shell_env()
1022 c2 = c.clone()
1023 assert c2.foo == "bar"
1024
1025 def works_correctly_when_subclassed(self):
1026 # Because sometimes, implementation #1 is really naive!
1027 class MyConfig(Config):
1028 pass
1029
1030 c = MyConfig()
1031 assert isinstance(c, MyConfig) # sanity
1032 c2 = c.clone()
1033 assert isinstance(c2, MyConfig) # actual test
1034
1035 class into_kwarg:
1036 "'into' kwarg"
1037
1038 def is_not_required(self):
1039 c = Config(defaults={"meh": "okay"})
1040 c2 = c.clone()
1041 assert c2.meh == "okay"
1042
1043 def resulting_clones_are_typed_as_new_class(self):
1044 class MyConfig(Config):
1045 pass
1046
1047 c = Config()
1048 c2 = c.clone(into=MyConfig)
1049 assert type(c2) is MyConfig
1050
1051 def non_conflicting_values_are_merged(self):
1052 # NOTE: this is really just basic clone behavior.
1053 class MyConfig(Config):
1054 @staticmethod
1055 def global_defaults():
1056 orig = Config.global_defaults()
1057 orig["new"] = {"data": "ohai"}
1058 return orig
1059
1060 c = Config(defaults={"other": {"data": "hello"}})
1061 c["runtime"] = {"modification": "sup"}
1062 c2 = c.clone(into=MyConfig)
1063 # New default data from MyConfig present
1064 assert c2.new.data == "ohai"
1065 # As well as old default data from the cloned instance
1066 assert c2.other.data == "hello"
1067 # And runtime user mods from the cloned instance
1068 assert c2.runtime.modification == "sup"
1069
1070 def does_not_deepcopy(self):
1071 c = Config(
1072 defaults={
1073 # Will merge_dicts happily
1074 "oh": {"dear": {"god": object()}},
1075 # And shallow-copy compound values
1076 "shallow": {"objects": ["copy", "okay"]},
1077 # Will preserve refrences to the innermost dict, sadly. Not
1078 # much we can do without incurring deepcopy problems (or
1079 # reimplementing it entirely)
1080 "welp": {"cannot": ["have", {"everything": "we want"}]},
1081 }
1082 )
1083 c2 = c.clone()
1084 # Basic identity
1085 assert c is not c2, "Clone had same identity as original!"
1086 # Dicts get recreated
1087 assert c.oh is not c2.oh, "Top level key had same identity!"
1088 assert (
1089 c.oh.dear is not c2.oh.dear
1090 ), "Midlevel key had same identity!" # noqa
1091 # Basic values get copied
1092 err = "Leaf object() had same identity!"
1093 assert c.oh.dear.god is not c2.oh.dear.god, err
1094 assert c.shallow.objects == c2.shallow.objects
1095 err = "Shallow list had same identity!"
1096 assert c.shallow.objects is not c2.shallow.objects, err
1097 # Deeply nested non-dict objects are stil problematic, oh well
1098 err = "Huh, a deeply nested dict-in-a-list had different identity?"
1099 assert c.welp.cannot[1] is c2.welp.cannot[1], err
1100 err = "Huh, a deeply nested dict-in-a-list value had different identity?" # noqa
1101 assert (
1102 c.welp.cannot[1]["everything"]
1103 is c2.welp.cannot[1]["everything"]
1104 ), err # noqa
1105
1106 def can_be_pickled(self):
1107 c = Config(overrides={"foo": {"bar": {"biz": ["baz", "buzz"]}}})
1108 c2 = pickle.loads(pickle.dumps(c))
1109 assert c == c2
1110 assert c is not c2
1111 assert c.foo.bar.biz is not c2.foo.bar.biz
1112
1113
1114 # NOTE: merge_dicts has its own very low level unit tests in its own file