Debian Codegraph @

gavo/utils/fancyconfig.py

raw
1 # -*- coding: utf-8 -*-
2 r"""
3 A wrapper around configparser that defines syntax and types within
4 the configuration options.
5
6 This tries to do for configuration processing what optparse did for
7 command line option processing: A declarative way of handling the main
8 chores.
9
10 The idea is that, in a client program, you say something like::
11
12 from pftf.fancyconfig import (Configuration, Section, ConfigError,
13 ...(items you want)...)
14
15 _config = Config(
16 Section(...
17 XYConfigItem(...)
18 ),
19 Section(...
20 ...
21 )
22 )
23
24 get = _config.get
25 set = _config.set
26
27 if __name__=="__main__":
28 print fancyconfig.makeTxtDocs(_config)
29 else:
30 try:
31 fancyconfig.readConfiguration(_config, None,
32 os.path.join(dataDir, "config"))
33 except ConfigError, msg:
34 import sys
35 sys.stderr.write("%s: %s\n"%(
36 sys.argv[0], unicode(msg)))
37 sys.exit(0)
38
39 and be done with most of it.
40
41 For examples of how this is used, see pftf (http://www.tfiu.de/pftf)
42 or DaCHS (http://soft.g-vo.org/dachs)
43 """
44
45 #c Copyright 2008-2025, the GAVO project <[email protected]>
46 #c
47 #c This program is free software, covered by the GNU GPL. See the
48 #c COPYING file in the source distribution.
49
50
51 import configparser
52 import re
53 import os
54 import pathlib
55 import tempfile
56 import warnings
57 import weakref
58
59 from gavo.utils.dachstypes import (
60 Any, Dict, Filename, IO, Iterator, List, Optional, Match, Set, Type, Tuple)
61
62
63 defaultSection = "general" # must be all lowercase
64
65 # Set to true if avoid making a bad config item bomb out
66 BAD_CONFIG_ITEM_JUST_WARNS = True
67
68
69 class ConfigError(Exception):
70 """is the base class of the user visible exceptions from this module.
71 """
72 fileName = "<internal>"
73
74 class ParseError(ConfigError):
75 """is raised by ConfigItem's parse methods if there is a problem with
76 the input.
77
78 These should only escape to users of this module unless they call
79 ConfigItem.set themselves (which they shouldn't).
80 """
81
82 class NoConfigItem(ConfigError):
83 """is raised by Configuration if a non-existing configuration
84 item is set or requested.
85 """
86
87 class BadConfigValue(ConfigError):
88 """is raised by getConfiguration when there is a syntax error or the
89 like in a value.
90
91 The error message gives a hint at the reason of the error and is intended
92 for human consumption.
93 """
94
95 class SyntaxError(ConfigError):
96 """is raised when the input file syntax is bad (i.e., on
97 configparser.ParsingErrors)
98 """
99
100
101 class ConfigItem:
102 """A description of a configuration item including methods
103 to parse and unparse them.
104
105 This class is an abstract base class for options with real syntax
106 (_parse and _unparse methods).
107
108 ConfigItems have a section and a name (as in configparser), a
109 value (that defaults to default), an origin (which is "default",
110 if the value has not been changed and otherwise can be freely
111 used by clients), and a description. The origin is important
112 for distinguishing what to save.
113
114 You need to define the _parse and _unparse methods when deriving
115 subclasses. The _parse methods must take a string and return anything or
116 raise ParseErrors (with
117 a sensible description of the problem) if there is a problem
118 with the input; they must not raise other exceptions when passed a
119 string (but may do anything when passed something else). _unparse
120 methods must not raise exceptions, take a value as returned
121 by parse (nothing else must be passed in) and return a
122 string that _parse would parse into this value.
123
124 Thus, the set method *only* takes strings as values. To set
125 parsed values, assign to the value attribute directly. However, _unparse
126 methods are not required to cope with any crazy stuff you enter
127 in this way, and thus you suddenly may receive all kinds of
128 funny exceptions when serializing a Configuration.
129
130 Inheriting classes need to specify a class attribute default that
131 kicks in when no default has been specified during construction.
132 These must be strings parseable by _parse.
133
134 Finally, you should provide a typedesc class attribute, a description
135 of the type intended for human consumption. See the documentation
136 functions below to get an idea how the would be shown.
137 """
138
139 typedesc = "unspecified value"
140
141 def __init__(self,
142 name: str,
143 default: Optional[str] = None,
144 description: str = "Undocumented") -> None:
145 self.name = name
146 if default is None:
147 default = self.default
148 self.default: str = default
149 self.set(default, "default")
150 self.description = description
151 # parent will be set on adoption by a Configuration
152 self.parent: Optional["Configuration"] = None
153
154 def set(self, value: str, origin: str = "user") -> None:
155 self.value, self.origin = self._parse(value), origin
156
157 def getAsString(self) -> str:
158 return self._unparse(self.value)
159
160 def _parse(self, value: str) -> Any:
161 raise ParseError("Internal error: Base config item used.")
162
163 def _unparse(self, value: Any) -> str:
164 return value
165
166
167 class NullableConfigItem(ConfigItem):
168 """a config item that accepts "None" as a null literal.
169 """
170 def _parse(self, value: str) -> Any:
171 if value=="None":
172 return None
173 return value
174
175 def _unparse(self, value: Any) -> str:
176 if value is None:
177 return "None"
178 return value
179
180 def _parseList(self, value: str) -> List[str]:
181 res = [s.strip()
182 for s in NullableConfigItem._parse(self, value).split(",")]
183 if not res[-1]:
184 del res[-1]
185 return res
186
187 def _unparseList(self, value=List[str]) -> str:
188 return ", ".join(
189 [NullableConfigItem._unparse(self, v) for v in value]+[""])
190
191
192 class StringConfigItem(NullableConfigItem):
193 """A config item containing unicode strings.
194
195 The serialization of the config file is supposed to be utf-8.
196
197 The special value None is used as a Null value literal.
198
199 Tests are below.
200 """
201
202 typedesc = "string"
203 default = ""
204
205
206 class IntConfigItem(ConfigItem):
207 """A config item containing an integer.
208
209 It supports a Null value through the special None literal.
210
211 >>> ci = IntConfigItem("foo"); print(ci.value)
212 None
213 >>> ci = IntConfigItem("foo", default="23"); ci.value
214 23
215 >>> ci.set("42"); ci.value
216 42
217 >>> ci.getAsString()
218 '42'
219 """
220
221 typedesc = "integer"
222 default = "None"
223
224 def _parse(self, value: str) -> Optional[int]:
225 if value=="None":
226 return None
227 try:
228 return int(value)
229 except ValueError:
230 raise ParseError(f"{value} is not an integer literal")
231
232 def _unparse(self, value: int) -> str:
233 return str(value)
234
235
236 class FloatConfigItem(ConfigItem):
237 """A config item containing a float.
238
239 It supports a Null value through the special None literal.
240
241 >>> ci = FloatConfigItem("foo"); print(ci.value)
242 None
243 >>> ci = FloatConfigItem("foo", default="23"); ci.value
244 23.0
245 >>> ci.set("42.25"); ci.value
246 42.25
247 >>> ci.getAsString()
248 '42.25'
249 """
250
251 typedesc = "floating point value"
252 default = "None"
253
254 def _parse(self, value: str) -> Optional[float]:
255 if value=="None":
256 return None
257 try:
258 return float(value)
259 except ValueError:
260 raise ParseError("%s is not a floating point literal"%value
261 )
262
263 def _unparse(self, value: float) -> str:
264 return repr(value)
265
266
267 class ListConfigItem(NullableConfigItem):
268 r"""A ConfigItem containing a list of strings, comma separated.
269
270 The values are space-normalized. Trailing whitespace-only items are
271 discarded, so "" is an empty list, "," is a list containing one
272 empty string.
273
274 There is currently no way to embed commas in the values. If that
275 should become necessary, I'd probably go for backslash escaping.
276
277 >>> ci = ListConfigItem("foo"); ci.value, ci.getAsString()
278 ([], '')
279 >>> ci.set(ci.getAsString());ci.value
280 []
281 >>> ci.set("3, 2, 1, Zündung"); ci.value, ci.getAsString()
282 (['3', '2', '1', 'Zündung'], '3, 2, 1, Zündung, ')
283 >>> ci.set(",");ci.value
284 ['']
285 >>> ci.set(ci.getAsString());ci.value
286 ['']
287 """
288
289 typedesc = "list of strings"
290 default = ""
291
292 def _parse(self, value: str) -> List[str]:
293 return self._parseList(value)
294
295 def _unparse(self, value: List[str]) -> str:
296 return self._unparseList(value)
297
298
299 class SetConfigItem(NullableConfigItem):
300 """A set-valued ListConfigItem for quick existence lookups.
301 """
302 typedesc = "set of strings"
303
304 def _parse(self, value: str) -> Set[str]:
305 return set(self._parseList(value))
306
307 def _unparse(self, value: Set[str]) -> str:
308 return self._unparseList(list(sorted(value)))
309
310
311 class IntListConfigItem(NullableConfigItem):
312 """A ConfigItem containing a comma separated list of ints.
313
314 Literal handling is analoguos to ListConfigItem.
315
316 >>> ci = IntListConfigItem("foo"); ci.value, ci.getAsString()
317 ([], '')
318 >>> ci.set("3,2, 1"); ci.value, ci.getAsString()
319 ([3, 2, 1], '3, 2, 1, ')
320 >>> ci.set(ci.getAsString()); ci.value
321 [3, 2, 1]
322 >>> ci.set("1, 2, 3, rubbish")
323 Traceback (most recent call last):
324 ...
325 fancyconfig.ParseError: Non-integer in integer list
326 """
327
328 typedesc = "list of integers"
329 default = ""
330
331 def _parse(self, value: str) -> List[int]:
332 try:
333 return [int(s) for s in NullableConfigItem._parseList(self, value)]
334 except ValueError:
335 raise ParseError("Non-integer in integer list") from None
336
337 def _unparse(self, value: List[int]) -> str:
338 return self._unparseList([str(n) for n in value])
339
340
341 class DictConfigItem(NullableConfigItem):
342 r"""A config item that contains a concise representation of
343 a string-string mapping.
344
345 The literal format is {<key>:<value>,}, where whitespace is ignored
346 between tokens and the last comma may be omitted.
347
348 No commas and colons are allowed within keys and values. To lift this,
349 I'd probably go for backslash escaping.
350
351 >>> ci = DictConfigItem("foo"); ci.value
352 {}
353 >>> ci.set("ab:cd, foo:Fuß"); ci.value
354 {'ab': 'cd', 'foo': 'Fuß'}
355 >>> ci.getAsString();ci.set(ci.getAsString()); ci.value
356 'ab:cd, foo:Fuß, '
357 {'ab': 'cd', 'foo': 'Fuß'}
358 >>> ci.set("ab:cd, rubbish")
359 Traceback (most recent call last):
360 ...
361 fancyconfig.ParseError: 'rubbish' is not a valid mapping literal element
362 """
363
364 typedesc = "mapping"
365 default = ""
366
367 def _parse(self, value: str) -> Dict[str, str]:
368 res = {}
369 for item in self._parseList(value):
370 try:
371 k, v = item.split(":")
372 res[k.strip()] = v.strip()
373 except ValueError:
374 raise ParseError(f"'{item}' is not a valid mapping literal element"
375 ) from None
376 return res
377
378 def _unparse(self, value: Dict[str, str]) -> str:
379 return self._unparseList(
380 ["%s:%s"%(k, v) for k, v in value.items()])
381
382
383 class BooleanConfigItem(ConfigItem):
384 """A config item that contains a boolean and can be parsed from
385 many fancy representations.
386 """
387
388 typedesc = "boolean"
389 default = "False"
390
391 trueLiterals = set(["true", "yes", "t", "on", "enabled", "1"])
392 falseLiterals = set(["false", "no", "f", "off", "disabled", "0"])
393
394 def _parse(self, value: str) -> bool:
395 value = value.lower()
396 if value in self.trueLiterals:
397 return True
398 elif value in self.falseLiterals:
399 return False
400 else:
401 raise ParseError(
402 f"'{value}' is no recognized boolean literal.")
403
404 def _unparse(self, value: bool) -> str:
405 return {True: "True", False: "False"}[value]
406
407
408 class EnumeratedConfigItem(StringConfigItem):
409 """A ConfigItem taking string values out of a set of possible strings.
410
411 Use the keyword argument options to pass in the possible strings.
412 The first item becomes the default unless you give a default.
413 You must give a non-empty list of strings as options.
414 """
415
416 typedesc = "value from a defined set"
417
418 def __init__(self,
419 name: str,
420 default: Optional[str] = None,
421 description: str = "Undocumented",
422 options: List[str] = []) -> None:
423 if default is None:
424 default = options[0]
425 self.options = set(options)
426 self.typedesc = "value from the list %s"%(", ".join(
427 sorted(self.options)))
428 StringConfigItem.__init__(self, name, default, description)
429
430 def _parse(self, value: str) -> str:
431 encVal = StringConfigItem._parse(self, value)
432 if encVal not in self.options:
433 raise ParseError("%s is not an allowed value. Choose one of"
434 " %s"%(value, ", ".join([o for o in self.options])))
435 return encVal
436
437
438 class PathConfigItem(NullableConfigItem):
439 """A ConfigItem for a unix shell-type path.
440
441 The individual items are separated by colons, ~ is replaced by the
442 current value of $HOME (or "/", if unset), and $<key> substitutions
443 are supported, with key having to point to a key in the defaultSection.
444
445 To embed a real $ sign, double it.
446
447 This is parented ConfigItem, i.e., it needs a Configuration parent
448 before its value can be accessed.
449 """
450
451 typedesc = "shell-type path"
452
453 def _parse(self, value: str) -> List[Filename]:
454 self._unparsed = NullableConfigItem._parse(self, value)
455 if self._unparsed is None:
456 return []
457 else:
458 return [s.strip() for s in str(self._unparsed).split(":")]
459
460 def _unparse(self, value: List[Filename]) -> str:
461 return NullableConfigItem._unparse(self, self._unparsed)
462
463 def _getValue(self) -> List[Filename]:
464 def resolveReference(mat: Match) -> str:
465 if mat.group(1)=='$':
466 return '$'
467 else:
468 if self.parent is None:
469 raise TypeError("Cannot use unparented PathConfigItem")
470 else:
471 return str(self.parent.get(mat.group(1)))
472
473 res: List[Filename] = []
474 for p in self._value:
475 if isinstance(p, pathlib.Path):
476 p = str(p)
477
478 if p.startswith("~"):
479 p = os.environ.get("HOME", "")+p[1:]
480
481 if '$' in p:
482 p = re.sub(r"\$(\w+)", resolveReference, p)
483
484 res.append(p)
485 return res
486
487 def _setValue(self, val: List[Filename]) -> None:
488 self._value = val
489
490 value = property(_getValue, _setValue)
491
492
493 class PathRelativeConfigItem(StringConfigItem):
494 """A configuration item interpreted relative to a path
495 given in the general section.
496
497 Basically, this is a replacement for configparser's %(x)s interpolation.
498 In addition, we expand ~ in front of a value to the current value of
499 $HOME.
500
501 To enable general-type interpolation, override the baseKey class Attribute.
502 """
503 baseKey: Optional[str] = None
504 _value: Optional[Filename] = ""
505
506 def _getValue(self) -> Optional[Filename]:
507 if self._value is None:
508 return None
509 if str(self._value).startswith("~"):
510 return pathlib.Path(
511 os.environ.get("HOME", "/no_home")+str(self._value)[1:])
512 if self.baseKey:
513 if self.parent is None:
514 raise TypeError("No value of unparented PathRelative item")
515 else:
516 return pathlib.Path(
517 os.path.join(self.parent.get(self.baseKey), self._value))
518 return pathlib.Path(self._value)
519
520 def _setValue(self, val: Optional[Filename]) -> None:
521 self._value = val
522
523 value = property(_getValue, _setValue)
524
525
526 class ExpandedPathConfigItem(StringConfigItem):
527 """A configuration item in that returns its value expandusered.
528 """
529 def _parse(self, value: str) -> Filename:
530 val = StringConfigItem._parse(self, value)
531 if val is not None:
532 val = os.path.expanduser(val)
533 return pathlib.Path(val)
534
535
536 class _Undefined(object):
537 """A sentinel for section.get.
538 """
539
540
541 class Section:
542 """A section within the configuration.
543
544 It is constructed with a name, a documentation, and the configuration
545 items.
546
547 They double as proxies between the configuration and their items
548 via the setParent method.
549 """
550 def __init__(self, name: str, documentation: str, *items: ConfigItem):
551 self.name, self.documentation = name, documentation
552 self.items = {}
553 for item in items:
554 self.items[item.name.lower()] = item
555
556 def __iter__(self) -> Iterator[ConfigItem]:
557 for name in sorted(self.items):
558 yield self.items[name]
559
560 def getitem(self, name: str) -> ConfigItem:
561 if name.lower() in self.items:
562 return self.items[name.lower()]
563 else:
564 raise NoConfigItem("No such configuration item: [%s] %s"%(
565 self.name, name))
566
567 def get(self, name: str) -> Any:
568 """returns the value of the configuration item name.
569
570 If it does not exist, a NoConfigItem exception will be raised.
571 """
572 return self.getitem(name).value
573
574 def set(self, name: str, value: Any, origin: str="user"):
575 """set the value of the configuration item name.
576
577 value must always be a string, regardless of the item's actual type.
578 """
579 try:
580 self.getitem(name).set(value, origin)
581 except NoConfigItem:
582 if BAD_CONFIG_ITEM_JUST_WARNS:
583 warnings.warn("Unknown configuration item [%s] %s ignored."%(
584 self.name, name))
585 else:
586 raise
587
588 def setParent(self, parent: "Configuration") -> None:
589 for item in list(self.items.values()):
590 item.parent = parent
591
592
593 class DefaultSection(Section):
594 """The default section, named by defaultSection above.
595
596 The only difference to Section is that you leave out the name.
597 """
598 def __init__(self, documentation: str, *items: ConfigItem):
599 Section.__init__(self, defaultSection, documentation, *items)
600
601
602 class MagicSection(Section):
603 """A section that creates new keys on the fly.
604
605 Use this a dictionary-like thing when successive edits are
606 necessary or the DictConfigItem becomes too unwieldy.
607
608 A MagicSection is constructed with the section name, an item
609 factory, which has to be a subclass of ConfigItem (you may
610 want to write a special constructor to provide documentation,
611 etc.), and defaults as a sequence of pairs of keys and values.
612 And there should be documentation, too, of course.
613 """
614 def __init__(self,
615 name: str,
616 documentation: str="Undocumented",
617 itemFactory: Type[ConfigItem] = StringConfigItem,
618 defaults: List[Tuple[str, str]]=[]):
619 self.itemFactory = itemFactory
620 items = []
621 for key, value in defaults:
622 items.append(self.itemFactory(key))
623 items[-1].set(value, origin="defaults")
624 Section.__init__(self, name, documentation, *items)
625
626 def set(self, name:str, value:str, origin: str = "user"):
627 if name not in self.items:
628 self.items[name.lower()] = self.itemFactory(name)
629 Section.set(self, name, value, origin)
630
631
632 class Configuration:
633 """A collection of config Sections and provides an interface to access
634 them and their items.
635
636 You construct it with the Sections you want and then use the get
637 method to access their content. You can either use get(section, name)
638 or just get(name), which implies the defaultSection section defined
639 at the top (right now, "general").
640
641 To read configuration items, use addFromFp. addFromFp should only
642 raise subclasses of ConfigError.
643
644 You can also set individual items using set.
645
646 The class follows the default behaviour of configparser in that section
647 and item names are lowercased.
648
649 Note that direct access to sections is not forbidden, but you have to
650 keep case mangling of keys into account when doing so.
651 """
652 def __init__(self, *sections: Section) -> None:
653 self.sections = {}
654 for section in sections:
655 self.sections[section.name.lower()] = section
656 section.setParent(weakref.proxy(self))
657
658 def __iter__(self) -> Iterator[Section]:
659 sectHeads = list(self.sections.keys())
660 if defaultSection in sectHeads:
661 sectHeads.remove(defaultSection)
662 yield self.sections[defaultSection]
663 for h in sorted(sectHeads):
664 yield self.sections[h]
665
666 def getitem(self, arg1: str, arg2: Optional[str] = None):
667 """returns the *item* described by section, name or just name.
668 """
669 if arg2 is None:
670 section, name = defaultSection, arg1
671 else:
672 section, name = arg1, arg2
673
674 if section.lower() in self.sections:
675 return self.sections[section.lower()].getitem(name)
676
677 raise NoConfigItem("No such configuration item: [%s] %s"%(
678 section, name))
679
680 def get(self, arg1: str, arg2: Optional[str] = None, default: Any=_Undefined
681 ) -> Any:
682 try:
683 return self.getitem(arg1, arg2).value
684 except NoConfigItem:
685 if default is _Undefined:
686 raise
687 return default
688
689 def set(self,
690 arg1: str,
691 arg2: Any,
692 arg3: Optional[Any] = None,
693 origin: str="user"):
694 """sets a configuration item to a value.
695
696 arg1 can be a section, in which case arg2 is a key and arg3 is a
697 value; alternatively, if arg3 is not given, arg1 is a key in
698 the defaultSection, and arg2 is the value.
699
700 All arguments are strings that must be parseable by the referenced
701 item's _parse method.
702
703 Origin is a tag you can use to, e.g., determine what to save.
704 """
705 if arg3 is None:
706 section, name, value = defaultSection, arg1, arg2
707 else:
708 section, name, value = arg1, arg2, arg3
709
710 if section.lower() in self.sections:
711 return self.sections[section.lower()].set(name, value, origin)
712 else:
713 raise NoConfigItem("No such configuration item: [%s] %s"%(
714 section, name))
715
716 def addFromFp(self, fp: IO, origin: str = "user", fName:str = "<internal>"
717 ) -> None:
718 """adds the config items in the file fp to self.
719 """
720 p = configparser.ConfigParser()
721 try:
722 p.read_file(fp, fName)
723 except configparser.ParsingError as msg:
724 raise SyntaxError("Config syntax error in %s: %s"%(fName,
725 str(msg)))
726 sections = p.sections()
727 for section in sections:
728 for name, value in p.items(section):
729 try:
730 self.set(section, name, value, origin)
731 except ParseError as msg:
732 raise BadConfigValue("While parsing value of %s in section %s,"
733 " file %s:\n%s"%
734 (name, section, fName, str(msg)))
735
736 def getUserConfig(self) -> configparser.ConfigParser:
737 """returns a configparser containing the user set config items.
738 """
739 userConf = configparser.ConfigParser()
740 for section in list(self.sections.values()):
741 for item in section:
742 if item.origin=="user":
743 if not userConf.has_section(section.name):
744 userConf.add_section(section.name)
745 userConf.set(section.name, item.name, item.getAsString())
746 return userConf
747
748 def saveUserConfig(self, destName: str) -> None:
749 """writes the config items changed by the user to destName.
750 """
751 uc = self.getUserConfig()
752 fd, tmpName = tempfile.mkstemp("temp", "", dir=os.path.dirname(destName))
753 f = os.fdopen(fd, "w")
754 uc.write(f)
755 f.flush()
756 os.fsync(fd)
757 f.close()
758 os.rename(tmpName, destName)
759
760
761 def _addToConfig(config, fName: Filename, origin: str):
762 """adds the config items in the file named in fName to the Configuration,
763 tagging them with origin.
764
765 fName can be None or point to a non-exisiting file. In both cases,
766 the function does nothing.
767 """
768 if not fName or not os.path.exists(fName):
769 return
770 with open(fName, "r", encoding="utf8") as f:
771 config.addFromFp(f, origin=origin, fName=fName)
772
773
774 def readConfiguration(
775 config: Configuration,
776 systemFName: Filename,
777 userFName: Filename):
778 """fills the Configuration config with values from the the two locations.
779
780 File names that are none or point to non-existing locations are
781 ignored.
782 """
783 try:
784 _addToConfig(config, systemFName, "system")
785 except ConfigError as ex:
786 ex.fileName = str(systemFName)
787 raise
788 try:
789 _addToConfig(config, userFName, "user")
790 except ConfigError as ex:
791 ex.fileName = str(userFName)
792 raise
793
794
795 def makeTxtDocs(config: Configuration, underlineChar: str=".") -> str:
796 import textwrap
797 docs = []
798 for section in config:
799 if isinstance(section, MagicSection):
800 hdr = "Magic Section [%s]"%(section.name)
801 body = (section.documentation+
802 "\n\nThe items in this section are all of type %s. You can add keys"
803 " as required.\n"%
804 section.itemFactory.typedesc)
805 else:
806 hdr = "Section [%s]"%(section.name)
807 body = section.documentation
808 docs.append("\n%s\n%s\n\n%s\n"%(hdr, underlineChar*len(hdr),
809 textwrap.fill(body, width=72)))
810 for ci in section:
811 docs.append("* %s: %s; "%(ci.name, ci.typedesc))
812 if ci.default is not None:
813 docs.append(" defaults to '%s' --"%ci.default)
814 docs.append(textwrap.fill(ci.description, width=72, initial_indent=" ",
815 subsequent_indent=" "))
816 return "\n".join(docs)
817
818
819 def _getTestSuite() -> Tuple["unittest.TestSuite", List[Any]]:
820 """returns a unittest suite for this module.
821
822 It's in-file since I want to keep the thing in a single file.
823 """
824 import unittest
825 from io import StringIO
826
827 class TestConfigItems(unittest.TestCase):
828 """tests for individual config items.
829 """
830 def testStringConfigItemDefaultArgs(self):
831 ci = StringConfigItem("foo")
832 self.assertEqual(ci.name, "foo")
833 self.assertEqual(ci.value, "")
834 self.assertEqual(ci.description, "Undocumented")
835 self.assertEqual(ci.origin, "default")
836 ci.set("bar", "user")
837 self.assertEqual(ci.value, "bar")
838 self.assertEqual(ci.origin, "user")
839 self.assertEqual(ci.name, "foo")
840 self.assertEqual(ci.getAsString(), "bar")
841
842 def testStringConfigItemNoDefaults(self):
843 ci = StringConfigItem("foo", default="quux",
844 description="An expressionist config item")
845 self.assertEqual(ci.name, "foo")
846 self.assertEqual(ci.value, "quux")
847 self.assertEqual(ci.description, "An expressionist config item")
848 self.assertEqual(ci.origin, "default")
849 ci.set("None", "user")
850 self.assertEqual(ci.value, None)
851 self.assertEqual(ci.origin, "user")
852 self.assertEqual(ci.getAsString(), "None")
853
854 def testStringConfigItemEncoding(self):
855 ci = StringConfigItem("foo", default='Füße')
856 self.assertEqual(ci.value.encode("iso-8859-1"), b'F\xfc\xdfe')
857 self.assertEqual(ci.getAsString(), 'Füße')
858
859 def testIntConfigItem(self):
860 ci = IntConfigItem("foo")
861 self.assertEqual(ci.value, None)
862 ci = IntConfigItem("foo", default="0")
863 self.assertEqual(ci.value, 0)
864 ci.set("42")
865 self.assertEqual(ci.value, 42)
866 self.assertEqual(ci.getAsString(), "42")
867
868 def testBooleanConfigItem(self):
869 ci = BooleanConfigItem("foo", default="0")
870 self.assertEqual(ci.value, False)
871 self.assertEqual(ci.getAsString(), "False")
872 ci.set("true")
873 self.assertEqual(ci.value, True)
874 ci.set("on")
875 self.assertEqual(ci.value, True)
876 self.assertEqual(ci.getAsString(), "True")
877 self.assertRaises(ParseError, ci.set, "undecided")
878
879 def testEnumeratedConfigItem(self):
880 ci = EnumeratedConfigItem("foo", options=["bar", "foo", "Fuß"])
881 self.assertEqual(ci.value, "bar")
882 self.assertRaises(ParseError, ci.set, "quux")
883 ci.set('Fuß')
884 self.assertEqual(ci.value, "Fuß")
885 self.assertEqual(ci.getAsString(), 'Fuß')
886
887
888 def getSampleConfig():
889 return Configuration(
890 DefaultSection("General Settings",
891 StringConfigItem("emptyDefault", description="is empty by default"),
892 StringConfigItem("fooDefault", default="foo",
893 description="is foo by default"),),
894 Section("types", "Various Types",
895 IntConfigItem("count", default="0", description=
896 "is an integer"),
897 ListConfigItem("enum", description="is a list",
898 default="foo, bar"),
899 IntListConfigItem("intenum", description="is a list of ints",
900 default="1,2,3"),
901 DictConfigItem("map", description="is a mapping",
902 default="intLit:1, floatLit:0.1, bla: wurg"),))
903
904
905 class ReadConfigTest(unittest.TestCase):
906 """tests for reading complete configurations.
907 """
908 def testDefaults(self):
909 config = getSampleConfig()
910 self.assertEqual(config.get("emptyDefault"), "")
911 self.assertEqual(config.get("fooDefault"), "foo")
912 self.assertEqual(config.get("types", "count"), 0)
913 self.assertEqual(config.get("types", "enum"), ["foo", "bar"])
914 self.assertEqual(config.get("types", "intenum"), [1,2,3])
915 self.assertEqual(config.get("types", "map"), {"intLit": "1",
916 "floatLit": "0.1", "bla": "wurg"})
917
918 def testSetting(self):
919 config = getSampleConfig()
920 config.set("emptyDefault", "foo")
921 self.assertEqual(config.get("emptyDefault"), "foo")
922 self.assertEqual(config.getitem("emptydefault").origin, "user")
923 self.assertEqual(config.getitem("foodefault").origin, "default")
924
925 def testReading(self):
926 config = getSampleConfig()
927 config.addFromFp(StringIO("[general]\n"
928 "emptyDefault: bar\n"
929 "fooDefault: quux\n"
930 "[types]\n"
931 "count: 7\n"
932 "enum: one, two,three:3\n"
933 "intenum: 1, 1,3,3\n"
934 "map: Fuß: y, x:Fuß\n"))
935 self.assertEqual(config.get("emptyDefault"), "bar")
936 self.assertEqual(config.get("fooDefault"), "quux")
937 self.assertEqual(config.get("types", "count"), 7)
938 self.assertEqual(config.get("types", "enum"), ["one", "two", "three:3"])
939 self.assertEqual(config.get("types", "intenum"), [1,1,3,3])
940 self.assertEqual(config.get("types", "map"), {'Fuß': "y",
941 "x": 'Fuß'})
942 self.assertEqual(config.getitem("types", "map").origin, "user")
943
944 def testRaising(self):
945 config = getSampleConfig()
946 self.assertRaises(BadConfigValue, config.addFromFp,
947 StringIO("[types]\nintenum: brasel\n"))
948 self.assertRaises(SyntaxError, config.addFromFp,
949 StringIO("intenum: brasel\n"))
950 self.assertRaises(ParseError, config.getitem("types", "count").set,
951 "abc")
952
953 def testWarning(self):
954 config = getSampleConfig()
955 with warnings.catch_warnings(record=True) as w:
956 config.addFromFp(StringIO("[types]\nnonexisting: True\n"))
957 self.assertEqual(len(w), 1)
958 self.assertEqual(str(w[0].message),
959 "Unknown configuration item [types] nonexisting ignored.")
960
961
962 class MagicFactoryTest(unittest.TestCase):
963 """tests for function of MagicFactories.
964 """
965 def testMagic(self):
966 config = Configuration(
967 MagicSection("profiles", "Some magic Section",
968 defaults=(('a', 'b'), ('c', 'd'))))
969 self.assertEqual(config.get('profiles', 'c'), 'd')
970 self.assertRaises(NoConfigItem, config.get, 'profiles', 'd')
971 config.set('profiles', 'new', 'shining', origin="user")
972 item = config.getitem('profiles', 'new')
973 self.assertEqual(item.value, 'shining')
974 self.assertEqual(item.origin, 'user')
975
976
977 class UserConfigTest(unittest.TestCase):
978 """tests for extraction of user-supplied config items.
979 """
980 def testNoUserConfig(self):
981 config = getSampleConfig()
982 cp = config.getUserConfig()
983 self.assertEqual(cp.sections(), [])
984
985 def testSomeUserConfig(self):
986 config = getSampleConfig()
987 config.set("emptyDefault", "not empty any more")
988 config.set("types", "count", "4")
989 config.set("types", "intenum", "3,2,1")
990 cp = config.getUserConfig()
991 self.assertEqual([s for s in sorted(cp.sections())],
992 ["general", "types"])
993 self.assertEqual(len(cp.items("general")), 1)
994 self.assertEqual(len(cp.items("types")), 2)
995 self.assertEqual(cp.get("general", "emptyDefault"), "not empty any more")
996 self.assertEqual(cp.get("types", "count"), "4")
997 self.assertEqual(cp.get("types", "intenum"), "3, 2, 1, ")
998
999 l = locals()
1000 tests = [l[name] for name in l
1001 if isinstance(l[name], type) and issubclass(l[name], unittest.TestCase)]
1002 loader = unittest.TestLoader()
1003 suite = unittest.TestSuite([loader.loadTestsFromTestCase(t)
1004 for t in tests])
1005 return suite, tests
1006
1007
1008 def load_tests(
1009 loader: None,
1010 tests: "unittest.TestSuite",
1011 ignore: None) -> "unittest.TestSuite":
1012 import doctest
1013 import fancyconfig # type: ignore
1014 suite, _ = _getTestSuite()
1015 tests.addTest(suite)
1016 tests.addTest(doctest.DocTestSuite(fancyconfig))
1017 return tests
1018
1019
1020 if __name__=="__main__": # pragma: no-cover
1021 import unittest
1022 suite = unittest.TestSuite()
1023 unittest.TextTestRunner().run(load_tests(None, suite, None))