Debian Codegraph @

lib-python/3/test/test_configparser.py

raw symbols SCIP
1 import collections
2 import configparser
3 import io
4 import os
5 import pathlib
6 import textwrap
7 import unittest
8 import warnings
9
10 from test import support
11 from test.support import os_helper
12
13
14 class SortedDict(collections.UserDict):
15
16 def items(self):
17 return sorted(self.data.items())
18
19 def keys(self):
20 return sorted(self.data.keys())
21
22 def values(self):
23 return [i[1] for i in self.items()]
24
25 def iteritems(self):
26 return iter(self.items())
27
28 def iterkeys(self):
29 return iter(self.keys())
30
31 def itervalues(self):
32 return iter(self.values())
33
34 __iter__ = iterkeys
35
36
37 class CfgParserTestCaseClass:
38 allow_no_value = False
39 delimiters = ('=', ':')
40 comment_prefixes = (';', '#')
41 inline_comment_prefixes = (';', '#')
42 empty_lines_in_values = True
43 dict_type = configparser._default_dict
44 strict = False
45 default_section = configparser.DEFAULTSECT
46 interpolation = configparser._UNSET
47
48 def newconfig(self, defaults=None):
49 arguments = dict(
50 defaults=defaults,
51 allow_no_value=self.allow_no_value,
52 delimiters=self.delimiters,
53 comment_prefixes=self.comment_prefixes,
54 inline_comment_prefixes=self.inline_comment_prefixes,
55 empty_lines_in_values=self.empty_lines_in_values,
56 dict_type=self.dict_type,
57 strict=self.strict,
58 default_section=self.default_section,
59 interpolation=self.interpolation,
60 )
61 instance = self.config_class(**arguments)
62 return instance
63
64 def fromstring(self, string, defaults=None):
65 cf = self.newconfig(defaults)
66 cf.read_string(string)
67 return cf
68
69
70 class BasicTestCase(CfgParserTestCaseClass):
71
72 def basic_test(self, cf):
73 E = ['Commented Bar',
74 'Foo Bar',
75 'Internationalized Stuff',
76 'Long Line',
77 'Section\\with$weird%characters[\t',
78 'Spaces',
79 'Spacey Bar',
80 'Spacey Bar From The Beginning',
81 'Types',
82 'This One Has A ] In It',
83 ]
84
85 if self.allow_no_value:
86 E.append('NoValue')
87 E.sort()
88 F = [('baz', 'qwe'), ('foo', 'bar3')]
89
90 # API access
91 L = cf.sections()
92 L.sort()
93 eq = self.assertEqual
94 eq(L, E)
95 L = cf.items('Spacey Bar From The Beginning')
96 L.sort()
97 eq(L, F)
98
99 # mapping access
100 L = [section for section in cf]
101 L.sort()
102 E.append(self.default_section)
103 E.sort()
104 eq(L, E)
105 L = cf['Spacey Bar From The Beginning'].items()
106 L = sorted(list(L))
107 eq(L, F)
108 L = cf.items()
109 L = sorted(list(L))
110 self.assertEqual(len(L), len(E))
111 for name, section in L:
112 eq(name, section.name)
113 eq(cf.defaults(), cf[self.default_section])
114
115 # The use of spaces in the section names serves as a
116 # regression test for SourceForge bug #583248:
117 # http://www.python.org/sf/583248
118
119 # API access
120 eq(cf.get('Foo Bar', 'foo'), 'bar1')
121 eq(cf.get('Spacey Bar', 'foo'), 'bar2')
122 eq(cf.get('Spacey Bar From The Beginning', 'foo'), 'bar3')
123 eq(cf.get('Spacey Bar From The Beginning', 'baz'), 'qwe')
124 eq(cf.get('Commented Bar', 'foo'), 'bar4')
125 eq(cf.get('Commented Bar', 'baz'), 'qwe')
126 eq(cf.get('Spaces', 'key with spaces'), 'value')
127 eq(cf.get('Spaces', 'another with spaces'), 'splat!')
128 eq(cf.getint('Types', 'int'), 42)
129 eq(cf.get('Types', 'int'), "42")
130 self.assertAlmostEqual(cf.getfloat('Types', 'float'), 0.44)
131 eq(cf.get('Types', 'float'), "0.44")
132 eq(cf.getboolean('Types', 'boolean'), False)
133 eq(cf.get('Types', '123'), 'strange but acceptable')
134 eq(cf.get('This One Has A ] In It', 'forks'), 'spoons')
135 if self.allow_no_value:
136 eq(cf.get('NoValue', 'option-without-value'), None)
137
138 # test vars= and fallback=
139 eq(cf.get('Foo Bar', 'foo', fallback='baz'), 'bar1')
140 eq(cf.get('Foo Bar', 'foo', vars={'foo': 'baz'}), 'baz')
141 with self.assertRaises(configparser.NoSectionError):
142 cf.get('No Such Foo Bar', 'foo')
143 with self.assertRaises(configparser.NoOptionError):
144 cf.get('Foo Bar', 'no-such-foo')
145 eq(cf.get('No Such Foo Bar', 'foo', fallback='baz'), 'baz')
146 eq(cf.get('Foo Bar', 'no-such-foo', fallback='baz'), 'baz')
147 eq(cf.get('Spacey Bar', 'foo', fallback=None), 'bar2')
148 eq(cf.get('No Such Spacey Bar', 'foo', fallback=None), None)
149 eq(cf.getint('Types', 'int', fallback=18), 42)
150 eq(cf.getint('Types', 'no-such-int', fallback=18), 18)
151 eq(cf.getint('Types', 'no-such-int', fallback="18"), "18") # sic!
152 with self.assertRaises(configparser.NoOptionError):
153 cf.getint('Types', 'no-such-int')
154 self.assertAlmostEqual(cf.getfloat('Types', 'float',
155 fallback=0.0), 0.44)
156 self.assertAlmostEqual(cf.getfloat('Types', 'no-such-float',
157 fallback=0.0), 0.0)
158 eq(cf.getfloat('Types', 'no-such-float', fallback="0.0"), "0.0") # sic!
159 with self.assertRaises(configparser.NoOptionError):
160 cf.getfloat('Types', 'no-such-float')
161 eq(cf.getboolean('Types', 'boolean', fallback=True), False)
162 eq(cf.getboolean('Types', 'no-such-boolean', fallback="yes"),
163 "yes") # sic!
164 eq(cf.getboolean('Types', 'no-such-boolean', fallback=True), True)
165 with self.assertRaises(configparser.NoOptionError):
166 cf.getboolean('Types', 'no-such-boolean')
167 eq(cf.getboolean('No Such Types', 'boolean', fallback=True), True)
168 if self.allow_no_value:
169 eq(cf.get('NoValue', 'option-without-value', fallback=False), None)
170 eq(cf.get('NoValue', 'no-such-option-without-value',
171 fallback=False), False)
172
173 # mapping access
174 eq(cf['Foo Bar']['foo'], 'bar1')
175 eq(cf['Spacey Bar']['foo'], 'bar2')
176 section = cf['Spacey Bar From The Beginning']
177 eq(section.name, 'Spacey Bar From The Beginning')
178 self.assertIs(section.parser, cf)
179 with self.assertRaises(AttributeError):
180 section.name = 'Name is read-only'
181 with self.assertRaises(AttributeError):
182 section.parser = 'Parser is read-only'
183 eq(section['foo'], 'bar3')
184 eq(section['baz'], 'qwe')
185 eq(cf['Commented Bar']['foo'], 'bar4')
186 eq(cf['Commented Bar']['baz'], 'qwe')
187 eq(cf['Spaces']['key with spaces'], 'value')
188 eq(cf['Spaces']['another with spaces'], 'splat!')
189 eq(cf['Long Line']['foo'],
190 'this line is much, much longer than my editor\nlikes it.')
191 if self.allow_no_value:
192 eq(cf['NoValue']['option-without-value'], None)
193 # test vars= and fallback=
194 eq(cf['Foo Bar'].get('foo', 'baz'), 'bar1')
195 eq(cf['Foo Bar'].get('foo', fallback='baz'), 'bar1')
196 eq(cf['Foo Bar'].get('foo', vars={'foo': 'baz'}), 'baz')
197 with self.assertRaises(KeyError):
198 cf['No Such Foo Bar']['foo']
199 with self.assertRaises(KeyError):
200 cf['Foo Bar']['no-such-foo']
201 with self.assertRaises(KeyError):
202 cf['No Such Foo Bar'].get('foo', fallback='baz')
203 eq(cf['Foo Bar'].get('no-such-foo', 'baz'), 'baz')
204 eq(cf['Foo Bar'].get('no-such-foo', fallback='baz'), 'baz')
205 eq(cf['Foo Bar'].get('no-such-foo'), None)
206 eq(cf['Spacey Bar'].get('foo', None), 'bar2')
207 eq(cf['Spacey Bar'].get('foo', fallback=None), 'bar2')
208 with self.assertRaises(KeyError):
209 cf['No Such Spacey Bar'].get('foo', None)
210 eq(cf['Types'].getint('int', 18), 42)
211 eq(cf['Types'].getint('int', fallback=18), 42)
212 eq(cf['Types'].getint('no-such-int', 18), 18)
213 eq(cf['Types'].getint('no-such-int', fallback=18), 18)
214 eq(cf['Types'].getint('no-such-int', "18"), "18") # sic!
215 eq(cf['Types'].getint('no-such-int', fallback="18"), "18") # sic!
216 eq(cf['Types'].getint('no-such-int'), None)
217 self.assertAlmostEqual(cf['Types'].getfloat('float', 0.0), 0.44)
218 self.assertAlmostEqual(cf['Types'].getfloat('float',
219 fallback=0.0), 0.44)
220 self.assertAlmostEqual(cf['Types'].getfloat('no-such-float', 0.0), 0.0)
221 self.assertAlmostEqual(cf['Types'].getfloat('no-such-float',
222 fallback=0.0), 0.0)
223 eq(cf['Types'].getfloat('no-such-float', "0.0"), "0.0") # sic!
224 eq(cf['Types'].getfloat('no-such-float', fallback="0.0"), "0.0") # sic!
225 eq(cf['Types'].getfloat('no-such-float'), None)
226 eq(cf['Types'].getboolean('boolean', True), False)
227 eq(cf['Types'].getboolean('boolean', fallback=True), False)
228 eq(cf['Types'].getboolean('no-such-boolean', "yes"), "yes") # sic!
229 eq(cf['Types'].getboolean('no-such-boolean', fallback="yes"),
230 "yes") # sic!
231 eq(cf['Types'].getboolean('no-such-boolean', True), True)
232 eq(cf['Types'].getboolean('no-such-boolean', fallback=True), True)
233 eq(cf['Types'].getboolean('no-such-boolean'), None)
234 if self.allow_no_value:
235 eq(cf['NoValue'].get('option-without-value', False), None)
236 eq(cf['NoValue'].get('option-without-value', fallback=False), None)
237 eq(cf['NoValue'].get('no-such-option-without-value', False), False)
238 eq(cf['NoValue'].get('no-such-option-without-value',
239 fallback=False), False)
240
241 # Make sure the right things happen for remove_section() and
242 # remove_option(); added to include check for SourceForge bug #123324.
243
244 cf[self.default_section]['this_value'] = '1'
245 cf[self.default_section]['that_value'] = '2'
246
247 # API access
248 self.assertTrue(cf.remove_section('Spaces'))
249 self.assertFalse(cf.has_option('Spaces', 'key with spaces'))
250 self.assertFalse(cf.remove_section('Spaces'))
251 self.assertFalse(cf.remove_section(self.default_section))
252 self.assertTrue(cf.remove_option('Foo Bar', 'foo'),
253 "remove_option() failed to report existence of option")
254 self.assertFalse(cf.has_option('Foo Bar', 'foo'),
255 "remove_option() failed to remove option")
256 self.assertFalse(cf.remove_option('Foo Bar', 'foo'),
257 "remove_option() failed to report non-existence of option"
258 " that was removed")
259 self.assertTrue(cf.has_option('Foo Bar', 'this_value'))
260 self.assertFalse(cf.remove_option('Foo Bar', 'this_value'))
261 self.assertTrue(cf.remove_option(self.default_section, 'this_value'))
262 self.assertFalse(cf.has_option('Foo Bar', 'this_value'))
263 self.assertFalse(cf.remove_option(self.default_section, 'this_value'))
264
265 with self.assertRaises(configparser.NoSectionError) as cm:
266 cf.remove_option('No Such Section', 'foo')
267 self.assertEqual(cm.exception.args, ('No Such Section',))
268
269 eq(cf.get('Long Line', 'foo'),
270 'this line is much, much longer than my editor\nlikes it.')
271
272 # mapping access
273 del cf['Types']
274 self.assertFalse('Types' in cf)
275 with self.assertRaises(KeyError):
276 del cf['Types']
277 with self.assertRaises(ValueError):
278 del cf[self.default_section]
279 del cf['Spacey Bar']['foo']
280 self.assertFalse('foo' in cf['Spacey Bar'])
281 with self.assertRaises(KeyError):
282 del cf['Spacey Bar']['foo']
283 self.assertTrue('that_value' in cf['Spacey Bar'])
284 with self.assertRaises(KeyError):
285 del cf['Spacey Bar']['that_value']
286 del cf[self.default_section]['that_value']
287 self.assertFalse('that_value' in cf['Spacey Bar'])
288 with self.assertRaises(KeyError):
289 del cf[self.default_section]['that_value']
290 with self.assertRaises(KeyError):
291 del cf['No Such Section']['foo']
292
293 # Don't add new asserts below in this method as most of the options
294 # and sections are now removed.
295
296 def test_basic(self):
297 config_string = """\
298 [Foo Bar]
299 foo{0[0]}bar1
300 [Spacey Bar]
301 foo {0[0]} bar2
302 [Spacey Bar From The Beginning]
303 foo {0[0]} bar3
304 baz {0[0]} qwe
305 [Commented Bar]
306 foo{0[1]} bar4 {1[1]} comment
307 baz{0[0]}qwe {1[0]}another one
308 [Long Line]
309 foo{0[1]} this line is much, much longer than my editor
310 likes it.
311 [Section\\with$weird%characters[\t]
312 [Internationalized Stuff]
313 foo[bg]{0[1]} Bulgarian
314 foo{0[0]}Default
315 foo[en]{0[0]}English
316 foo[de]{0[0]}Deutsch
317 [Spaces]
318 key with spaces {0[1]} value
319 another with spaces {0[0]} splat!
320 [Types]
321 int {0[1]} 42
322 float {0[0]} 0.44
323 boolean {0[0]} NO
324 123 {0[1]} strange but acceptable
325 [This One Has A ] In It]
326 forks {0[0]} spoons
327 """.format(self.delimiters, self.comment_prefixes)
328 if self.allow_no_value:
329 config_string += (
330 "[NoValue]\n"
331 "option-without-value\n"
332 )
333 cf = self.fromstring(config_string)
334 self.basic_test(cf)
335 if self.strict:
336 with self.assertRaises(configparser.DuplicateOptionError):
337 cf.read_string(textwrap.dedent("""\
338 [Duplicate Options Here]
339 option {0[0]} with a value
340 option {0[1]} with another value
341 """.format(self.delimiters)))
342 with self.assertRaises(configparser.DuplicateSectionError):
343 cf.read_string(textwrap.dedent("""\
344 [And Now For Something]
345 completely different {0[0]} True
346 [And Now For Something]
347 the larch {0[1]} 1
348 """.format(self.delimiters)))
349 else:
350 cf.read_string(textwrap.dedent("""\
351 [Duplicate Options Here]
352 option {0[0]} with a value
353 option {0[1]} with another value
354 """.format(self.delimiters)))
355
356 cf.read_string(textwrap.dedent("""\
357 [And Now For Something]
358 completely different {0[0]} True
359 [And Now For Something]
360 the larch {0[1]} 1
361 """.format(self.delimiters)))
362
363 def test_basic_from_dict(self):
364 config = {
365 "Foo Bar": {
366 "foo": "bar1",
367 },
368 "Spacey Bar": {
369 "foo": "bar2",
370 },
371 "Spacey Bar From The Beginning": {
372 "foo": "bar3",
373 "baz": "qwe",
374 },
375 "Commented Bar": {
376 "foo": "bar4",
377 "baz": "qwe",
378 },
379 "Long Line": {
380 "foo": "this line is much, much longer than my editor\nlikes "
381 "it.",
382 },
383 "Section\\with$weird%characters[\t": {
384 },
385 "Internationalized Stuff": {
386 "foo[bg]": "Bulgarian",
387 "foo": "Default",
388 "foo[en]": "English",
389 "foo[de]": "Deutsch",
390 },
391 "Spaces": {
392 "key with spaces": "value",
393 "another with spaces": "splat!",
394 },
395 "Types": {
396 "int": 42,
397 "float": 0.44,
398 "boolean": False,
399 123: "strange but acceptable",
400 },
401 "This One Has A ] In It": {
402 "forks": "spoons"
403 },
404 }
405 if self.allow_no_value:
406 config.update({
407 "NoValue": {
408 "option-without-value": None,
409 }
410 })
411 cf = self.newconfig()
412 cf.read_dict(config)
413 self.basic_test(cf)
414 if self.strict:
415 with self.assertRaises(configparser.DuplicateSectionError):
416 cf.read_dict({
417 '1': {'key': 'value'},
418 1: {'key2': 'value2'},
419 })
420 with self.assertRaises(configparser.DuplicateOptionError):
421 cf.read_dict({
422 "Duplicate Options Here": {
423 'option': 'with a value',
424 'OPTION': 'with another value',
425 },
426 })
427 else:
428 cf.read_dict({
429 'section': {'key': 'value'},
430 'SECTION': {'key2': 'value2'},
431 })
432 cf.read_dict({
433 "Duplicate Options Here": {
434 'option': 'with a value',
435 'OPTION': 'with another value',
436 },
437 })
438
439 def test_case_sensitivity(self):
440 cf = self.newconfig()
441 cf.add_section("A")
442 cf.add_section("a")
443 cf.add_section("B")
444 L = cf.sections()
445 L.sort()
446 eq = self.assertEqual
447 eq(L, ["A", "B", "a"])
448 cf.set("a", "B", "value")
449 eq(cf.options("a"), ["b"])
450 eq(cf.get("a", "b"), "value",
451 "could not locate option, expecting case-insensitive option names")
452 with self.assertRaises(configparser.NoSectionError):
453 # section names are case-sensitive
454 cf.set("b", "A", "value")
455 self.assertTrue(cf.has_option("a", "b"))
456 self.assertFalse(cf.has_option("b", "b"))
457 cf.set("A", "A-B", "A-B value")
458 for opt in ("a-b", "A-b", "a-B", "A-B"):
459 self.assertTrue(
460 cf.has_option("A", opt),
461 "has_option() returned false for option which should exist")
462 eq(cf.options("A"), ["a-b"])
463 eq(cf.options("a"), ["b"])
464 cf.remove_option("a", "B")
465 eq(cf.options("a"), [])
466
467 # SF bug #432369:
468 cf = self.fromstring(
469 "[MySection]\nOption{} first line \n\tsecond line \n".format(
470 self.delimiters[0]))
471 eq(cf.options("MySection"), ["option"])
472 eq(cf.get("MySection", "Option"), "first line\nsecond line")
473
474 # SF bug #561822:
475 cf = self.fromstring("[section]\n"
476 "nekey{}nevalue\n".format(self.delimiters[0]),
477 defaults={"key":"value"})
478 self.assertTrue(cf.has_option("section", "Key"))
479
480
481 def test_case_sensitivity_mapping_access(self):
482 cf = self.newconfig()
483 cf["A"] = {}
484 cf["a"] = {"B": "value"}
485 cf["B"] = {}
486 L = [section for section in cf]
487 L.sort()
488 eq = self.assertEqual
489 elem_eq = self.assertCountEqual
490 eq(L, sorted(["A", "B", self.default_section, "a"]))
491 eq(cf["a"].keys(), {"b"})
492 eq(cf["a"]["b"], "value",
493 "could not locate option, expecting case-insensitive option names")
494 with self.assertRaises(KeyError):
495 # section names are case-sensitive
496 cf["b"]["A"] = "value"
497 self.assertTrue("b" in cf["a"])
498 cf["A"]["A-B"] = "A-B value"
499 for opt in ("a-b", "A-b", "a-B", "A-B"):
500 self.assertTrue(
501 opt in cf["A"],
502 "has_option() returned false for option which should exist")
503 eq(cf["A"].keys(), {"a-b"})
504 eq(cf["a"].keys(), {"b"})
505 del cf["a"]["B"]
506 elem_eq(cf["a"].keys(), {})
507
508 # SF bug #432369:
509 cf = self.fromstring(
510 "[MySection]\nOption{} first line \n\tsecond line \n".format(
511 self.delimiters[0]))
512 eq(cf["MySection"].keys(), {"option"})
513 eq(cf["MySection"]["Option"], "first line\nsecond line")
514
515 # SF bug #561822:
516 cf = self.fromstring("[section]\n"
517 "nekey{}nevalue\n".format(self.delimiters[0]),
518 defaults={"key":"value"})
519 self.assertTrue("Key" in cf["section"])
520
521 def test_default_case_sensitivity(self):
522 cf = self.newconfig({"foo": "Bar"})
523 self.assertEqual(
524 cf.get(self.default_section, "Foo"), "Bar",
525 "could not locate option, expecting case-insensitive option names")
526 cf = self.newconfig({"Foo": "Bar"})
527 self.assertEqual(
528 cf.get(self.default_section, "Foo"), "Bar",
529 "could not locate option, expecting case-insensitive defaults")
530
531 def test_parse_errors(self):
532 cf = self.newconfig()
533 self.parse_error(cf, configparser.ParsingError,
534 "[Foo]\n"
535 "{}val-without-opt-name\n".format(self.delimiters[0]))
536 self.parse_error(cf, configparser.ParsingError,
537 "[Foo]\n"
538 "{}val-without-opt-name\n".format(self.delimiters[1]))
539 e = self.parse_error(cf, configparser.MissingSectionHeaderError,
540 "No Section!\n")
541 self.assertEqual(e.args, ('<???>', 1, "No Section!\n"))
542 if not self.allow_no_value:
543 e = self.parse_error(cf, configparser.ParsingError,
544 "[Foo]\n wrong-indent\n")
545 self.assertEqual(e.args, ('<???>',))
546 # read_file on a real file
547 tricky = support.findfile("cfgparser.3", subdir="configdata")
548 if self.delimiters[0] == '=':
549 error = configparser.ParsingError
550 expected = (tricky,)
551 else:
552 error = configparser.MissingSectionHeaderError
553 expected = (tricky, 1,
554 ' # INI with as many tricky parts as possible\n')
555 with open(tricky, encoding='utf-8') as f:
556 e = self.parse_error(cf, error, f)
557 self.assertEqual(e.args, expected)
558
559 def parse_error(self, cf, exc, src):
560 if hasattr(src, 'readline'):
561 sio = src
562 else:
563 sio = io.StringIO(src)
564 with self.assertRaises(exc) as cm:
565 cf.read_file(sio)
566 return cm.exception
567
568 def test_query_errors(self):
569 cf = self.newconfig()
570 self.assertEqual(cf.sections(), [],
571 "new ConfigParser should have no defined sections")
572 self.assertFalse(cf.has_section("Foo"),
573 "new ConfigParser should have no acknowledged "
574 "sections")
575 with self.assertRaises(configparser.NoSectionError):
576 cf.options("Foo")
577 with self.assertRaises(configparser.NoSectionError):
578 cf.set("foo", "bar", "value")
579 e = self.get_error(cf, configparser.NoSectionError, "foo", "bar")
580 self.assertEqual(e.args, ("foo",))
581 cf.add_section("foo")
582 e = self.get_error(cf, configparser.NoOptionError, "foo", "bar")
583 self.assertEqual(e.args, ("bar", "foo"))
584
585 def get_error(self, cf, exc, section, option):
586 try:
587 cf.get(section, option)
588 except exc as e:
589 return e
590 else:
591 self.fail("expected exception type %s.%s"
592 % (exc.__module__, exc.__qualname__))
593
594 def test_boolean(self):
595 cf = self.fromstring(
596 "[BOOLTEST]\n"
597 "T1{equals}1\n"
598 "T2{equals}TRUE\n"
599 "T3{equals}True\n"
600 "T4{equals}oN\n"
601 "T5{equals}yes\n"
602 "F1{equals}0\n"
603 "F2{equals}FALSE\n"
604 "F3{equals}False\n"
605 "F4{equals}oFF\n"
606 "F5{equals}nO\n"
607 "E1{equals}2\n"
608 "E2{equals}foo\n"
609 "E3{equals}-1\n"
610 "E4{equals}0.1\n"
611 "E5{equals}FALSE AND MORE".format(equals=self.delimiters[0])
612 )
613 for x in range(1, 5):
614 self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))
615 self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x))
616 self.assertRaises(ValueError,
617 cf.getboolean, 'BOOLTEST', 'e%d' % x)
618
619 def test_weird_errors(self):
620 cf = self.newconfig()
621 cf.add_section("Foo")
622 with self.assertRaises(configparser.DuplicateSectionError) as cm:
623 cf.add_section("Foo")
624 e = cm.exception
625 self.assertEqual(str(e), "Section 'Foo' already exists")
626 self.assertEqual(e.args, ("Foo", None, None))
627
628 if self.strict:
629 with self.assertRaises(configparser.DuplicateSectionError) as cm:
630 cf.read_string(textwrap.dedent("""\
631 [Foo]
632 will this be added{equals}True
633 [Bar]
634 what about this{equals}True
635 [Foo]
636 oops{equals}this won't
637 """.format(equals=self.delimiters[0])), source='<foo-bar>')
638 e = cm.exception
639 self.assertEqual(str(e), "While reading from '<foo-bar>' "
640 "[line 5]: section 'Foo' already exists")
641 self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))
642
643 with self.assertRaises(configparser.DuplicateOptionError) as cm:
644 cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
645 e = cm.exception
646 self.assertEqual(str(e), "While reading from '<dict>': option "
647 "'opt' in section 'Bar' already exists")
648 self.assertEqual(e.args, ("Bar", "opt", "<dict>", None))
649
650 def test_get_after_duplicate_option_error(self):
651 cf = self.newconfig()
652 ini = textwrap.dedent("""\
653 [Foo]
654 x{equals}1
655 y{equals}2
656 y{equals}3
657 """.format(equals=self.delimiters[0]))
658 if self.strict:
659 with self.assertRaises(configparser.DuplicateOptionError):
660 cf.read_string(ini)
661 else:
662 cf.read_string(ini)
663 self.assertEqual(cf.get('Foo', 'x'), '1')
664
665 def test_write(self):
666 config_string = (
667 "[Long Line]\n"
668 "foo{0[0]} this line is much, much longer than my editor\n"
669 " likes it.\n"
670 "[{default_section}]\n"
671 "foo{0[1]} another very\n"
672 " long line\n"
673 "[Long Line - With Comments!]\n"
674 "test {0[1]} we {comment} can\n"
675 " also {comment} place\n"
676 " comments {comment} in\n"
677 " multiline {comment} values"
678 "\n".format(self.delimiters, comment=self.comment_prefixes[0],
679 default_section=self.default_section)
680 )
681 if self.allow_no_value:
682 config_string += (
683 "[Valueless]\n"
684 "option-without-value\n"
685 )
686
687 cf = self.fromstring(config_string)
688 for space_around_delimiters in (True, False):
689 output = io.StringIO()
690 cf.write(output, space_around_delimiters=space_around_delimiters)
691 delimiter = self.delimiters[0]
692 if space_around_delimiters:
693 delimiter = " {} ".format(delimiter)
694 expect_string = (
695 "[{default_section}]\n"
696 "foo{equals}another very\n"
697 "\tlong line\n"
698 "\n"
699 "[Long Line]\n"
700 "foo{equals}this line is much, much longer than my editor\n"
701 "\tlikes it.\n"
702 "\n"
703 "[Long Line - With Comments!]\n"
704 "test{equals}we\n"
705 "\talso\n"
706 "\tcomments\n"
707 "\tmultiline\n"
708 "\n".format(equals=delimiter,
709 default_section=self.default_section)
710 )
711 if self.allow_no_value:
712 expect_string += (
713 "[Valueless]\n"
714 "option-without-value\n"
715 "\n"
716 )
717 self.assertEqual(output.getvalue(), expect_string)
718
719 def test_set_string_types(self):
720 cf = self.fromstring("[sect]\n"
721 "option1{eq}foo\n".format(eq=self.delimiters[0]))
722 # Check that we don't get an exception when setting values in
723 # an existing section using strings:
724 class mystr(str):
725 pass
726 cf.set("sect", "option1", "splat")
727 cf.set("sect", "option1", mystr("splat"))
728 cf.set("sect", "option2", "splat")
729 cf.set("sect", "option2", mystr("splat"))
730 cf.set("sect", "option1", "splat")
731 cf.set("sect", "option2", "splat")
732
733 def test_read_returns_file_list(self):
734 if self.delimiters[0] != '=':
735 self.skipTest('incompatible format')
736 file1 = support.findfile("cfgparser.1", subdir="configdata")
737 # check when we pass a mix of readable and non-readable files:
738 cf = self.newconfig()
739 parsed_files = cf.read([file1, "nonexistent-file"], encoding="utf-8")
740 self.assertEqual(parsed_files, [file1])
741 self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
742 # check when we pass only a filename:
743 cf = self.newconfig()
744 parsed_files = cf.read(file1, encoding="utf-8")
745 self.assertEqual(parsed_files, [file1])
746 self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
747 # check when we pass only a Path object:
748 cf = self.newconfig()
749 parsed_files = cf.read(pathlib.Path(file1), encoding="utf-8")
750 self.assertEqual(parsed_files, [file1])
751 self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
752 # check when we passed both a filename and a Path object:
753 cf = self.newconfig()
754 parsed_files = cf.read([pathlib.Path(file1), file1], encoding="utf-8")
755 self.assertEqual(parsed_files, [file1, file1])
756 self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
757 # check when we pass only missing files:
758 cf = self.newconfig()
759 parsed_files = cf.read(["nonexistent-file"], encoding="utf-8")
760 self.assertEqual(parsed_files, [])
761 # check when we pass no files:
762 cf = self.newconfig()
763 parsed_files = cf.read([], encoding="utf-8")
764 self.assertEqual(parsed_files, [])
765
766 def test_read_returns_file_list_with_bytestring_path(self):
767 if self.delimiters[0] != '=':
768 self.skipTest('incompatible format')
769 file1_bytestring = support.findfile("cfgparser.1", subdir="configdata").encode()
770 # check when passing an existing bytestring path
771 cf = self.newconfig()
772 parsed_files = cf.read(file1_bytestring, encoding="utf-8")
773 self.assertEqual(parsed_files, [file1_bytestring])
774 # check when passing an non-existing bytestring path
775 cf = self.newconfig()
776 parsed_files = cf.read(b'nonexistent-file', encoding="utf-8")
777 self.assertEqual(parsed_files, [])
778 # check when passing both an existing and non-existing bytestring path
779 cf = self.newconfig()
780 parsed_files = cf.read([file1_bytestring, b'nonexistent-file'], encoding="utf-8")
781 self.assertEqual(parsed_files, [file1_bytestring])
782
783 # shared by subclasses
784 def get_interpolation_config(self):
785 return self.fromstring(
786 "[Foo]\n"
787 "bar{equals}something %(with1)s interpolation (1 step)\n"
788 "bar9{equals}something %(with9)s lots of interpolation (9 steps)\n"
789 "bar10{equals}something %(with10)s lots of interpolation (10 steps)\n"
790 "bar11{equals}something %(with11)s lots of interpolation (11 steps)\n"
791 "with11{equals}%(with10)s\n"
792 "with10{equals}%(with9)s\n"
793 "with9{equals}%(with8)s\n"
794 "with8{equals}%(With7)s\n"
795 "with7{equals}%(WITH6)s\n"
796 "with6{equals}%(with5)s\n"
797 "With5{equals}%(with4)s\n"
798 "WITH4{equals}%(with3)s\n"
799 "with3{equals}%(with2)s\n"
800 "with2{equals}%(with1)s\n"
801 "with1{equals}with\n"
802 "\n"
803 "[Mutual Recursion]\n"
804 "foo{equals}%(bar)s\n"
805 "bar{equals}%(foo)s\n"
806 "\n"
807 "[Interpolation Error]\n"
808 # no definition for 'reference'
809 "name{equals}%(reference)s\n".format(equals=self.delimiters[0]))
810
811 def check_items_config(self, expected):
812 cf = self.fromstring("""
813 [section]
814 name {0[0]} %(value)s
815 key{0[1]} |%(name)s|
816 getdefault{0[1]} |%(default)s|
817 """.format(self.delimiters), defaults={"default": "<default>"})
818 L = list(cf.items("section", vars={'value': 'value'}))
819 L.sort()
820 self.assertEqual(L, expected)
821 with self.assertRaises(configparser.NoSectionError):
822 cf.items("no such section")
823
824 def test_popitem(self):
825 cf = self.fromstring("""
826 [section1]
827 name1 {0[0]} value1
828 [section2]
829 name2 {0[0]} value2
830 [section3]
831 name3 {0[0]} value3
832 """.format(self.delimiters), defaults={"default": "<default>"})
833 self.assertEqual(cf.popitem()[0], 'section1')
834 self.assertEqual(cf.popitem()[0], 'section2')
835 self.assertEqual(cf.popitem()[0], 'section3')
836 with self.assertRaises(KeyError):
837 cf.popitem()
838
839 def test_clear(self):
840 cf = self.newconfig({"foo": "Bar"})
841 self.assertEqual(
842 cf.get(self.default_section, "Foo"), "Bar",
843 "could not locate option, expecting case-insensitive option names")
844 cf['zing'] = {'option1': 'value1', 'option2': 'value2'}
845 self.assertEqual(cf.sections(), ['zing'])
846 self.assertEqual(set(cf['zing'].keys()), {'option1', 'option2', 'foo'})
847 cf.clear()
848 self.assertEqual(set(cf.sections()), set())
849 self.assertEqual(set(cf[self.default_section].keys()), {'foo'})
850
851 def test_setitem(self):
852 cf = self.fromstring("""
853 [section1]
854 name1 {0[0]} value1
855 [section2]
856 name2 {0[0]} value2
857 [section3]
858 name3 {0[0]} value3
859 """.format(self.delimiters), defaults={"nameD": "valueD"})
860 self.assertEqual(set(cf['section1'].keys()), {'name1', 'named'})
861 self.assertEqual(set(cf['section2'].keys()), {'name2', 'named'})
862 self.assertEqual(set(cf['section3'].keys()), {'name3', 'named'})
863 self.assertEqual(cf['section1']['name1'], 'value1')
864 self.assertEqual(cf['section2']['name2'], 'value2')
865 self.assertEqual(cf['section3']['name3'], 'value3')
866 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
867 cf['section2'] = {'name22': 'value22'}
868 self.assertEqual(set(cf['section2'].keys()), {'name22', 'named'})
869 self.assertEqual(cf['section2']['name22'], 'value22')
870 self.assertNotIn('name2', cf['section2'])
871 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
872 cf['section3'] = {}
873 self.assertEqual(set(cf['section3'].keys()), {'named'})
874 self.assertNotIn('name3', cf['section3'])
875 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
876 # For bpo-32108, assigning default_section to itself.
877 cf[self.default_section] = cf[self.default_section]
878 self.assertNotEqual(set(cf[self.default_section].keys()), set())
879 cf[self.default_section] = {}
880 self.assertEqual(set(cf[self.default_section].keys()), set())
881 self.assertEqual(set(cf['section1'].keys()), {'name1'})
882 self.assertEqual(set(cf['section2'].keys()), {'name22'})
883 self.assertEqual(set(cf['section3'].keys()), set())
884 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
885 # For bpo-32108, assigning section to itself.
886 cf['section2'] = cf['section2']
887 self.assertEqual(set(cf['section2'].keys()), {'name22'})
888
889 def test_invalid_multiline_value(self):
890 if self.allow_no_value:
891 self.skipTest('if no_value is allowed, ParsingError is not raised')
892
893 invalid = textwrap.dedent("""\
894 [DEFAULT]
895 test {0} test
896 invalid""".format(self.delimiters[0])
897 )
898 cf = self.newconfig()
899 with self.assertRaises(configparser.ParsingError):
900 cf.read_string(invalid)
901 self.assertEqual(cf.get('DEFAULT', 'test'), 'test')
902 self.assertEqual(cf['DEFAULT']['test'], 'test')
903
904
905 class StrictTestCase(BasicTestCase, unittest.TestCase):
906 config_class = configparser.RawConfigParser
907 strict = True
908
909
910 class ConfigParserTestCase(BasicTestCase, unittest.TestCase):
911 config_class = configparser.ConfigParser
912
913 def test_interpolation(self):
914 cf = self.get_interpolation_config()
915 eq = self.assertEqual
916 eq(cf.get("Foo", "bar"), "something with interpolation (1 step)")
917 eq(cf.get("Foo", "bar9"),
918 "something with lots of interpolation (9 steps)")
919 eq(cf.get("Foo", "bar10"),
920 "something with lots of interpolation (10 steps)")
921 e = self.get_error(cf, configparser.InterpolationDepthError, "Foo", "bar11")
922 if self.interpolation == configparser._UNSET:
923 self.assertEqual(e.args, ("bar11", "Foo",
924 "something %(with11)s lots of interpolation (11 steps)"))
925 elif isinstance(self.interpolation, configparser.LegacyInterpolation):
926 self.assertEqual(e.args, ("bar11", "Foo",
927 "something %(with11)s lots of interpolation (11 steps)"))
928
929 def test_interpolation_missing_value(self):
930 cf = self.get_interpolation_config()
931 e = self.get_error(cf, configparser.InterpolationMissingOptionError,
932 "Interpolation Error", "name")
933 self.assertEqual(e.reference, "reference")
934 self.assertEqual(e.section, "Interpolation Error")
935 self.assertEqual(e.option, "name")
936 if self.interpolation == configparser._UNSET:
937 self.assertEqual(e.args, ('name', 'Interpolation Error',
938 '%(reference)s', 'reference'))
939 elif isinstance(self.interpolation, configparser.LegacyInterpolation):
940 self.assertEqual(e.args, ('name', 'Interpolation Error',
941 '%(reference)s', 'reference'))
942
943 def test_items(self):
944 self.check_items_config([('default', '<default>'),
945 ('getdefault', '|<default>|'),
946 ('key', '|value|'),
947 ('name', 'value')])
948
949 def test_safe_interpolation(self):
950 # See http://www.python.org/sf/511737
951 cf = self.fromstring("[section]\n"
952 "option1{eq}xxx\n"
953 "option2{eq}%(option1)s/xxx\n"
954 "ok{eq}%(option1)s/%%s\n"
955 "not_ok{eq}%(option2)s/%%s".format(
956 eq=self.delimiters[0]))
957 self.assertEqual(cf.get("section", "ok"), "xxx/%s")
958 if self.interpolation == configparser._UNSET:
959 self.assertEqual(cf.get("section", "not_ok"), "xxx/xxx/%s")
960 elif isinstance(self.interpolation, configparser.LegacyInterpolation):
961 with self.assertRaises(TypeError):
962 cf.get("section", "not_ok")
963
964 def test_set_malformatted_interpolation(self):
965 cf = self.fromstring("[sect]\n"
966 "option1{eq}foo\n".format(eq=self.delimiters[0]))
967
968 self.assertEqual(cf.get('sect', "option1"), "foo")
969
970 self.assertRaises(ValueError, cf.set, "sect", "option1", "%foo")
971 self.assertRaises(ValueError, cf.set, "sect", "option1", "foo%")
972 self.assertRaises(ValueError, cf.set, "sect", "option1", "f%oo")
973
974 self.assertEqual(cf.get('sect', "option1"), "foo")
975
976 # bug #5741: double percents are *not* malformed
977 cf.set("sect", "option2", "foo%%bar")
978 self.assertEqual(cf.get("sect", "option2"), "foo%bar")
979
980 def test_set_nonstring_types(self):
981 cf = self.fromstring("[sect]\n"
982 "option1{eq}foo\n".format(eq=self.delimiters[0]))
983 # Check that we get a TypeError when setting non-string values
984 # in an existing section:
985 self.assertRaises(TypeError, cf.set, "sect", "option1", 1)
986 self.assertRaises(TypeError, cf.set, "sect", "option1", 1.0)
987 self.assertRaises(TypeError, cf.set, "sect", "option1", object())
988 self.assertRaises(TypeError, cf.set, "sect", "option2", 1)
989 self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0)
990 self.assertRaises(TypeError, cf.set, "sect", "option2", object())
991 self.assertRaises(TypeError, cf.set, "sect", 123, "invalid opt name!")
992 self.assertRaises(TypeError, cf.add_section, 123)
993
994 def test_add_section_default(self):
995 cf = self.newconfig()
996 self.assertRaises(ValueError, cf.add_section, self.default_section)
997
998 def test_defaults_keyword(self):
999 """bpo-23835 fix for ConfigParser"""
1000 cf = self.newconfig(defaults={1: 2.4})
1001 self.assertEqual(cf[self.default_section]['1'], '2.4')
1002 self.assertAlmostEqual(cf[self.default_section].getfloat('1'), 2.4)
1003 cf = self.newconfig(defaults={"A": 5.2})
1004 self.assertEqual(cf[self.default_section]['a'], '5.2')
1005 self.assertAlmostEqual(cf[self.default_section].getfloat('a'), 5.2)
1006
1007
1008 class ConfigParserTestCaseNoInterpolation(BasicTestCase, unittest.TestCase):
1009 config_class = configparser.ConfigParser
1010 interpolation = None
1011 ini = textwrap.dedent("""
1012 [numbers]
1013 one = 1
1014 two = %(one)s * 2
1015 three = ${common:one} * 3
1016
1017 [hexen]
1018 sixteen = ${numbers:two} * 8
1019 """).strip()
1020
1021 def assertMatchesIni(self, cf):
1022 self.assertEqual(cf['numbers']['one'], '1')
1023 self.assertEqual(cf['numbers']['two'], '%(one)s * 2')
1024 self.assertEqual(cf['numbers']['three'], '${common:one} * 3')
1025 self.assertEqual(cf['hexen']['sixteen'], '${numbers:two} * 8')
1026
1027 def test_no_interpolation(self):
1028 cf = self.fromstring(self.ini)
1029 self.assertMatchesIni(cf)
1030
1031 def test_empty_case(self):
1032 cf = self.newconfig()
1033 self.assertIsNone(cf.read_string(""))
1034
1035 def test_none_as_default_interpolation(self):
1036 class CustomConfigParser(configparser.ConfigParser):
1037 _DEFAULT_INTERPOLATION = None
1038
1039 cf = CustomConfigParser()
1040 cf.read_string(self.ini)
1041 self.assertMatchesIni(cf)
1042
1043
1044 class ConfigParserTestCaseLegacyInterpolation(ConfigParserTestCase):
1045 config_class = configparser.ConfigParser
1046 with warnings.catch_warnings():
1047 warnings.simplefilter("ignore", DeprecationWarning)
1048 interpolation = configparser.LegacyInterpolation()
1049
1050 def test_set_malformatted_interpolation(self):
1051 cf = self.fromstring("[sect]\n"
1052 "option1{eq}foo\n".format(eq=self.delimiters[0]))
1053
1054 self.assertEqual(cf.get('sect', "option1"), "foo")
1055
1056 cf.set("sect", "option1", "%foo")
1057 self.assertEqual(cf.get('sect', "option1"), "%foo")
1058 cf.set("sect", "option1", "foo%")
1059 self.assertEqual(cf.get('sect', "option1"), "foo%")
1060 cf.set("sect", "option1", "f%oo")
1061 self.assertEqual(cf.get('sect', "option1"), "f%oo")
1062
1063 # bug #5741: double percents are *not* malformed
1064 cf.set("sect", "option2", "foo%%bar")
1065 self.assertEqual(cf.get("sect", "option2"), "foo%%bar")
1066
1067
1068 class ConfigParserTestCaseInvalidInterpolationType(unittest.TestCase):
1069 def test_error_on_wrong_type_for_interpolation(self):
1070 for value in [configparser.ExtendedInterpolation, 42, "a string"]:
1071 with self.subTest(value=value):
1072 with self.assertRaises(TypeError):
1073 configparser.ConfigParser(interpolation=value)
1074
1075
1076 class ConfigParserTestCaseNonStandardDelimiters(ConfigParserTestCase):
1077 delimiters = (':=', '$')
1078 comment_prefixes = ('//', '"')
1079 inline_comment_prefixes = ('//', '"')
1080
1081
1082 class ConfigParserTestCaseNonStandardDefaultSection(ConfigParserTestCase):
1083 default_section = 'general'
1084
1085
1086 class MultilineValuesTestCase(BasicTestCase, unittest.TestCase):
1087 config_class = configparser.ConfigParser
1088 wonderful_spam = ("I'm having spam spam spam spam "
1089 "spam spam spam beaked beans spam "
1090 "spam spam and spam!").replace(' ', '\t\n')
1091
1092 def setUp(self):
1093 cf = self.newconfig()
1094 for i in range(100):
1095 s = 'section{}'.format(i)
1096 cf.add_section(s)
1097 for j in range(10):
1098 cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)
1099 with open(os_helper.TESTFN, 'w', encoding="utf-8") as f:
1100 cf.write(f)
1101
1102 def tearDown(self):
1103 os.unlink(os_helper.TESTFN)
1104
1105 def test_dominating_multiline_values(self):
1106 # We're reading from file because this is where the code changed
1107 # during performance updates in Python 3.2
1108 cf_from_file = self.newconfig()
1109 with open(os_helper.TESTFN, encoding="utf-8") as f:
1110 cf_from_file.read_file(f)
1111 self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
1112 self.wonderful_spam.replace('\t\n', '\n'))
1113
1114
1115 class RawConfigParserTestCase(BasicTestCase, unittest.TestCase):
1116 config_class = configparser.RawConfigParser
1117
1118 def test_interpolation(self):
1119 cf = self.get_interpolation_config()
1120 eq = self.assertEqual
1121 eq(cf.get("Foo", "bar"),
1122 "something %(with1)s interpolation (1 step)")
1123 eq(cf.get("Foo", "bar9"),
1124 "something %(with9)s lots of interpolation (9 steps)")
1125 eq(cf.get("Foo", "bar10"),
1126 "something %(with10)s lots of interpolation (10 steps)")
1127 eq(cf.get("Foo", "bar11"),
1128 "something %(with11)s lots of interpolation (11 steps)")
1129
1130 def test_items(self):
1131 self.check_items_config([('default', '<default>'),
1132 ('getdefault', '|%(default)s|'),
1133 ('key', '|%(name)s|'),
1134 ('name', '%(value)s')])
1135
1136 def test_set_nonstring_types(self):
1137 cf = self.newconfig()
1138 cf.add_section('non-string')
1139 cf.set('non-string', 'int', 1)
1140 cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13])
1141 cf.set('non-string', 'dict', {'pi': 3.14159})
1142 self.assertEqual(cf.get('non-string', 'int'), 1)
1143 self.assertEqual(cf.get('non-string', 'list'),
1144 [0, 1, 1, 2, 3, 5, 8, 13])
1145 self.assertEqual(cf.get('non-string', 'dict'), {'pi': 3.14159})
1146 cf.add_section(123)
1147 cf.set(123, 'this is sick', True)
1148 self.assertEqual(cf.get(123, 'this is sick'), True)
1149 if cf._dict is configparser._default_dict:
1150 # would not work for SortedDict; only checking for the most common
1151 # default dictionary (dict)
1152 cf.optionxform = lambda x: x
1153 cf.set('non-string', 1, 1)
1154 self.assertEqual(cf.get('non-string', 1), 1)
1155
1156 def test_defaults_keyword(self):
1157 """bpo-23835 legacy behavior for RawConfigParser"""
1158 with self.assertRaises(AttributeError) as ctx:
1159 self.newconfig(defaults={1: 2.4})
1160 err = ctx.exception
1161 self.assertEqual(str(err), "'int' object has no attribute 'lower'")
1162 cf = self.newconfig(defaults={"A": 5.2})
1163 self.assertAlmostEqual(cf[self.default_section]['a'], 5.2)
1164
1165
1166 class RawConfigParserTestCaseNonStandardDelimiters(RawConfigParserTestCase):
1167 delimiters = (':=', '$')
1168 comment_prefixes = ('//', '"')
1169 inline_comment_prefixes = ('//', '"')
1170
1171
1172 class RawConfigParserTestSambaConf(CfgParserTestCaseClass, unittest.TestCase):
1173 config_class = configparser.RawConfigParser
1174 comment_prefixes = ('#', ';', '----')
1175 inline_comment_prefixes = ('//',)
1176 empty_lines_in_values = False
1177
1178 def test_reading(self):
1179 smbconf = support.findfile("cfgparser.2", subdir="configdata")
1180 # check when we pass a mix of readable and non-readable files:
1181 cf = self.newconfig()
1182 parsed_files = cf.read([smbconf, "nonexistent-file"], encoding='utf-8')
1183 self.assertEqual(parsed_files, [smbconf])
1184 sections = ['global', 'homes', 'printers',
1185 'print$', 'pdf-generator', 'tmp', 'Agustin']
1186 self.assertEqual(cf.sections(), sections)
1187 self.assertEqual(cf.get("global", "workgroup"), "MDKGROUP")
1188 self.assertEqual(cf.getint("global", "max log size"), 50)
1189 self.assertEqual(cf.get("global", "hosts allow"), "127.")
1190 self.assertEqual(cf.get("tmp", "echo command"), "cat %s; rm %s")
1191
1192 class ConfigParserTestCaseExtendedInterpolation(BasicTestCase, unittest.TestCase):
1193 config_class = configparser.ConfigParser
1194 interpolation = configparser.ExtendedInterpolation()
1195 default_section = 'common'
1196 strict = True
1197
1198 def fromstring(self, string, defaults=None, optionxform=None):
1199 cf = self.newconfig(defaults)
1200 if optionxform:
1201 cf.optionxform = optionxform
1202 cf.read_string(string)
1203 return cf
1204
1205 def test_extended_interpolation(self):
1206 cf = self.fromstring(textwrap.dedent("""
1207 [common]
1208 favourite Beatle = Paul
1209 favourite color = green
1210
1211 [tom]
1212 favourite band = ${favourite color} day
1213 favourite pope = John ${favourite Beatle} II
1214 sequel = ${favourite pope}I
1215
1216 [ambv]
1217 favourite Beatle = George
1218 son of Edward VII = ${favourite Beatle} V
1219 son of George V = ${son of Edward VII}I
1220
1221 [stanley]
1222 favourite Beatle = ${ambv:favourite Beatle}
1223 favourite pope = ${tom:favourite pope}
1224 favourite color = black
1225 favourite state of mind = paranoid
1226 favourite movie = soylent ${common:favourite color}
1227 favourite song = ${favourite color} sabbath - ${favourite state of mind}
1228 """).strip())
1229
1230 eq = self.assertEqual
1231 eq(cf['common']['favourite Beatle'], 'Paul')
1232 eq(cf['common']['favourite color'], 'green')
1233 eq(cf['tom']['favourite Beatle'], 'Paul')
1234 eq(cf['tom']['favourite color'], 'green')
1235 eq(cf['tom']['favourite band'], 'green day')
1236 eq(cf['tom']['favourite pope'], 'John Paul II')
1237 eq(cf['tom']['sequel'], 'John Paul III')
1238 eq(cf['ambv']['favourite Beatle'], 'George')
1239 eq(cf['ambv']['favourite color'], 'green')
1240 eq(cf['ambv']['son of Edward VII'], 'George V')
1241 eq(cf['ambv']['son of George V'], 'George VI')
1242 eq(cf['stanley']['favourite Beatle'], 'George')
1243 eq(cf['stanley']['favourite color'], 'black')
1244 eq(cf['stanley']['favourite state of mind'], 'paranoid')
1245 eq(cf['stanley']['favourite movie'], 'soylent green')
1246 eq(cf['stanley']['favourite pope'], 'John Paul II')
1247 eq(cf['stanley']['favourite song'],
1248 'black sabbath - paranoid')
1249
1250 def test_endless_loop(self):
1251 cf = self.fromstring(textwrap.dedent("""
1252 [one for you]
1253 ping = ${one for me:pong}
1254
1255 [one for me]
1256 pong = ${one for you:ping}
1257
1258 [selfish]
1259 me = ${me}
1260 """).strip())
1261
1262 with self.assertRaises(configparser.InterpolationDepthError):
1263 cf['one for you']['ping']
1264 with self.assertRaises(configparser.InterpolationDepthError):
1265 cf['selfish']['me']
1266
1267 def test_strange_options(self):
1268 cf = self.fromstring("""
1269 [dollars]
1270 $var = $$value
1271 $var2 = ${$var}
1272 ${sick} = cannot interpolate me
1273
1274 [interpolated]
1275 $other = ${dollars:$var}
1276 $trying = ${dollars:${sick}}
1277 """)
1278
1279 self.assertEqual(cf['dollars']['$var'], '$value')
1280 self.assertEqual(cf['interpolated']['$other'], '$value')
1281 self.assertEqual(cf['dollars']['${sick}'], 'cannot interpolate me')
1282 exception_class = configparser.InterpolationMissingOptionError
1283 with self.assertRaises(exception_class) as cm:
1284 cf['interpolated']['$trying']
1285 self.assertEqual(cm.exception.reference, 'dollars:${sick')
1286 self.assertEqual(cm.exception.args[2], '${dollars:${sick}}') #rawval
1287
1288 def test_case_sensitivity_basic(self):
1289 ini = textwrap.dedent("""
1290 [common]
1291 optionlower = value
1292 OptionUpper = Value
1293
1294 [Common]
1295 optionlower = a better ${common:optionlower}
1296 OptionUpper = A Better ${common:OptionUpper}
1297
1298 [random]
1299 foolower = ${common:optionlower} redefined
1300 FooUpper = ${Common:OptionUpper} Redefined
1301 """).strip()
1302
1303 cf = self.fromstring(ini)
1304 eq = self.assertEqual
1305 eq(cf['common']['optionlower'], 'value')
1306 eq(cf['common']['OptionUpper'], 'Value')
1307 eq(cf['Common']['optionlower'], 'a better value')
1308 eq(cf['Common']['OptionUpper'], 'A Better Value')
1309 eq(cf['random']['foolower'], 'value redefined')
1310 eq(cf['random']['FooUpper'], 'A Better Value Redefined')
1311
1312 def test_case_sensitivity_conflicts(self):
1313 ini = textwrap.dedent("""
1314 [common]
1315 option = value
1316 Option = Value
1317
1318 [Common]
1319 option = a better ${common:option}
1320 Option = A Better ${common:Option}
1321
1322 [random]
1323 foo = ${common:option} redefined
1324 Foo = ${Common:Option} Redefined
1325 """).strip()
1326 with self.assertRaises(configparser.DuplicateOptionError):
1327 cf = self.fromstring(ini)
1328
1329 # raw options
1330 cf = self.fromstring(ini, optionxform=lambda opt: opt)
1331 eq = self.assertEqual
1332 eq(cf['common']['option'], 'value')
1333 eq(cf['common']['Option'], 'Value')
1334 eq(cf['Common']['option'], 'a better value')
1335 eq(cf['Common']['Option'], 'A Better Value')
1336 eq(cf['random']['foo'], 'value redefined')
1337 eq(cf['random']['Foo'], 'A Better Value Redefined')
1338
1339 def test_other_errors(self):
1340 cf = self.fromstring("""
1341 [interpolation fail]
1342 case1 = ${where's the brace
1343 case2 = ${does_not_exist}
1344 case3 = ${wrong_section:wrong_value}
1345 case4 = ${i:like:colon:characters}
1346 case5 = $100 for Fail No 5!
1347 """)
1348
1349 with self.assertRaises(configparser.InterpolationSyntaxError):
1350 cf['interpolation fail']['case1']
1351 with self.assertRaises(configparser.InterpolationMissingOptionError):
1352 cf['interpolation fail']['case2']
1353 with self.assertRaises(configparser.InterpolationMissingOptionError):
1354 cf['interpolation fail']['case3']
1355 with self.assertRaises(configparser.InterpolationSyntaxError):
1356 cf['interpolation fail']['case4']
1357 with self.assertRaises(configparser.InterpolationSyntaxError):
1358 cf['interpolation fail']['case5']
1359 with self.assertRaises(ValueError):
1360 cf['interpolation fail']['case6'] = "BLACK $ABBATH"
1361
1362
1363 class ConfigParserTestCaseNoValue(ConfigParserTestCase):
1364 allow_no_value = True
1365
1366
1367 class ConfigParserTestCaseTrickyFile(CfgParserTestCaseClass, unittest.TestCase):
1368 config_class = configparser.ConfigParser
1369 delimiters = {'='}
1370 comment_prefixes = {'#'}
1371 allow_no_value = True
1372
1373 def test_cfgparser_dot_3(self):
1374 tricky = support.findfile("cfgparser.3", subdir="configdata")
1375 cf = self.newconfig()
1376 self.assertEqual(len(cf.read(tricky, encoding='utf-8')), 1)
1377 self.assertEqual(cf.sections(), ['strange',
1378 'corruption',
1379 'yeah, sections can be '
1380 'indented as well',
1381 'another one!',
1382 'no values here',
1383 'tricky interpolation',
1384 'more interpolation'])
1385 self.assertEqual(cf.getint(self.default_section, 'go',
1386 vars={'interpolate': '-1'}), -1)
1387 with self.assertRaises(ValueError):
1388 # no interpolation will happen
1389 cf.getint(self.default_section, 'go', raw=True,
1390 vars={'interpolate': '-1'})
1391 self.assertEqual(len(cf.get('strange', 'other').split('\n')), 4)
1392 self.assertEqual(len(cf.get('corruption', 'value').split('\n')), 10)
1393 longname = 'yeah, sections can be indented as well'
1394 self.assertFalse(cf.getboolean(longname, 'are they subsections'))
1395 self.assertEqual(cf.get(longname, 'lets use some Unicode'), '片仮名')
1396 self.assertEqual(len(cf.items('another one!')), 5) # 4 in section and
1397 # `go` from DEFAULT
1398 with self.assertRaises(configparser.InterpolationMissingOptionError):
1399 cf.items('no values here')
1400 self.assertEqual(cf.get('tricky interpolation', 'lets'), 'do this')
1401 self.assertEqual(cf.get('tricky interpolation', 'lets'),
1402 cf.get('tricky interpolation', 'go'))
1403 self.assertEqual(cf.get('more interpolation', 'lets'), 'go shopping')
1404
1405 def test_unicode_failure(self):
1406 tricky = support.findfile("cfgparser.3", subdir="configdata")
1407 cf = self.newconfig()
1408 with self.assertRaises(UnicodeDecodeError):
1409 cf.read(tricky, encoding='ascii')
1410
1411
1412 class Issue7005TestCase(unittest.TestCase):
1413 """Test output when None is set() as a value and allow_no_value == False.
1414
1415 http://bugs.python.org/issue7005
1416
1417 """
1418
1419 expected_output = "[section]\noption = None\n\n"
1420
1421 def prepare(self, config_class):
1422 # This is the default, but that's the point.
1423 cp = config_class(allow_no_value=False)
1424 cp.add_section("section")
1425 cp.set("section", "option", None)
1426 sio = io.StringIO()
1427 cp.write(sio)
1428 return sio.getvalue()
1429
1430 def test_none_as_value_stringified(self):
1431 cp = configparser.ConfigParser(allow_no_value=False)
1432 cp.add_section("section")
1433 with self.assertRaises(TypeError):
1434 cp.set("section", "option", None)
1435
1436 def test_none_as_value_stringified_raw(self):
1437 output = self.prepare(configparser.RawConfigParser)
1438 self.assertEqual(output, self.expected_output)
1439
1440
1441 class SortedTestCase(RawConfigParserTestCase):
1442 dict_type = SortedDict
1443
1444 def test_sorted(self):
1445 cf = self.fromstring("[b]\n"
1446 "o4=1\n"
1447 "o3=2\n"
1448 "o2=3\n"
1449 "o1=4\n"
1450 "[a]\n"
1451 "k=v\n")
1452 output = io.StringIO()
1453 cf.write(output)
1454 self.assertEqual(output.getvalue(),
1455 "[a]\n"
1456 "k = v\n\n"
1457 "[b]\n"
1458 "o1 = 4\n"
1459 "o2 = 3\n"
1460 "o3 = 2\n"
1461 "o4 = 1\n\n")
1462
1463
1464 class CompatibleTestCase(CfgParserTestCaseClass, unittest.TestCase):
1465 config_class = configparser.RawConfigParser
1466 comment_prefixes = '#;'
1467 inline_comment_prefixes = ';'
1468
1469 def test_comment_handling(self):
1470 config_string = textwrap.dedent("""\
1471 [Commented Bar]
1472 baz=qwe ; a comment
1473 foo: bar # not a comment!
1474 # but this is a comment
1475 ; another comment
1476 quirk: this;is not a comment
1477 ; a space must precede an inline comment
1478 """)
1479 cf = self.fromstring(config_string)
1480 self.assertEqual(cf.get('Commented Bar', 'foo'),
1481 'bar # not a comment!')
1482 self.assertEqual(cf.get('Commented Bar', 'baz'), 'qwe')
1483 self.assertEqual(cf.get('Commented Bar', 'quirk'),
1484 'this;is not a comment')
1485
1486 class CopyTestCase(BasicTestCase, unittest.TestCase):
1487 config_class = configparser.ConfigParser
1488
1489 def fromstring(self, string, defaults=None):
1490 cf = self.newconfig(defaults)
1491 cf.read_string(string)
1492 cf_copy = self.newconfig()
1493 cf_copy.read_dict(cf)
1494 # we have to clean up option duplicates that appeared because of
1495 # the magic DEFAULTSECT behaviour.
1496 for section in cf_copy.values():
1497 if section.name == self.default_section:
1498 continue
1499 for default, value in cf[self.default_section].items():
1500 if section[default] == value:
1501 del section[default]
1502 return cf_copy
1503
1504
1505 class FakeFile:
1506 def __init__(self):
1507 file_path = support.findfile("cfgparser.1", subdir="configdata")
1508 with open(file_path, encoding="utf-8") as f:
1509 self.lines = f.readlines()
1510 self.lines.reverse()
1511
1512 def readline(self):
1513 if len(self.lines):
1514 return self.lines.pop()
1515 return ''
1516
1517
1518 def readline_generator(f):
1519 """As advised in Doc/library/configparser.rst."""
1520 line = f.readline()
1521 while line:
1522 yield line
1523 line = f.readline()
1524
1525
1526 class ReadFileTestCase(unittest.TestCase):
1527 def test_file(self):
1528 file_paths = [support.findfile("cfgparser.1", subdir="configdata")]
1529 try:
1530 file_paths.append(file_paths[0].encode('utf8'))
1531 except UnicodeEncodeError:
1532 pass # unfortunately we can't test bytes on this path
1533 for file_path in file_paths:
1534 parser = configparser.ConfigParser()
1535 with open(file_path, encoding="utf-8") as f:
1536 parser.read_file(f)
1537 self.assertIn("Foo Bar", parser)
1538 self.assertIn("foo", parser["Foo Bar"])
1539 self.assertEqual(parser["Foo Bar"]["foo"], "newbar")
1540
1541 def test_iterable(self):
1542 lines = textwrap.dedent("""
1543 [Foo Bar]
1544 foo=newbar""").strip().split('\n')
1545 parser = configparser.ConfigParser()
1546 parser.read_file(lines)
1547 self.assertIn("Foo Bar", parser)
1548 self.assertIn("foo", parser["Foo Bar"])
1549 self.assertEqual(parser["Foo Bar"]["foo"], "newbar")
1550
1551 def test_readline_generator(self):
1552 """Issue #11670."""
1553 parser = configparser.ConfigParser()
1554 with self.assertRaises(TypeError):
1555 parser.read_file(FakeFile())
1556 parser.read_file(readline_generator(FakeFile()))
1557 self.assertIn("Foo Bar", parser)
1558 self.assertIn("foo", parser["Foo Bar"])
1559 self.assertEqual(parser["Foo Bar"]["foo"], "newbar")
1560
1561 def test_source_as_bytes(self):
1562 """Issue #18260."""
1563 lines = textwrap.dedent("""
1564 [badbad]
1565 [badbad]""").strip().split('\n')
1566 parser = configparser.ConfigParser()
1567 with self.assertRaises(configparser.DuplicateSectionError) as dse:
1568 parser.read_file(lines, source=b"badbad")
1569 self.assertEqual(
1570 str(dse.exception),
1571 "While reading from b'badbad' [line 2]: section 'badbad' "
1572 "already exists"
1573 )
1574 lines = textwrap.dedent("""
1575 [badbad]
1576 bad = bad
1577 bad = bad""").strip().split('\n')
1578 parser = configparser.ConfigParser()
1579 with self.assertRaises(configparser.DuplicateOptionError) as dse:
1580 parser.read_file(lines, source=b"badbad")
1581 self.assertEqual(
1582 str(dse.exception),
1583 "While reading from b'badbad' [line 3]: option 'bad' in section "
1584 "'badbad' already exists"
1585 )
1586 lines = textwrap.dedent("""
1587 [badbad]
1588 = bad""").strip().split('\n')
1589 parser = configparser.ConfigParser()
1590 with self.assertRaises(configparser.ParsingError) as dse:
1591 parser.read_file(lines, source=b"badbad")
1592 self.assertEqual(
1593 str(dse.exception),
1594 "Source contains parsing errors: b'badbad'\n\t[line 2]: '= bad'"
1595 )
1596 lines = textwrap.dedent("""
1597 [badbad
1598 bad = bad""").strip().split('\n')
1599 parser = configparser.ConfigParser()
1600 with self.assertRaises(configparser.MissingSectionHeaderError) as dse:
1601 parser.read_file(lines, source=b"badbad")
1602 self.assertEqual(
1603 str(dse.exception),
1604 "File contains no section headers.\nfile: b'badbad', line: 1\n"
1605 "'[badbad'"
1606 )
1607
1608
1609 class CoverageOneHundredTestCase(unittest.TestCase):
1610 """Covers edge cases in the codebase."""
1611
1612 def test_duplicate_option_error(self):
1613 error = configparser.DuplicateOptionError('section', 'option')
1614 self.assertEqual(error.section, 'section')
1615 self.assertEqual(error.option, 'option')
1616 self.assertEqual(error.source, None)
1617 self.assertEqual(error.lineno, None)
1618 self.assertEqual(error.args, ('section', 'option', None, None))
1619 self.assertEqual(str(error), "Option 'option' in section 'section' "
1620 "already exists")
1621
1622 def test_interpolation_depth_error(self):
1623 error = configparser.InterpolationDepthError('option', 'section',
1624 'rawval')
1625 self.assertEqual(error.args, ('option', 'section', 'rawval'))
1626 self.assertEqual(error.option, 'option')
1627 self.assertEqual(error.section, 'section')
1628
1629 def test_parsing_error(self):
1630 with self.assertRaises(ValueError) as cm:
1631 configparser.ParsingError()
1632 self.assertEqual(str(cm.exception), "Required argument `source' not "
1633 "given.")
1634 with self.assertRaises(ValueError) as cm:
1635 configparser.ParsingError(source='source', filename='filename')
1636 self.assertEqual(str(cm.exception), "Cannot specify both `filename' "
1637 "and `source'. Use `source'.")
1638 error = configparser.ParsingError(filename='source')
1639 self.assertEqual(error.source, 'source')
1640 with warnings.catch_warnings(record=True) as w:
1641 warnings.simplefilter("always", DeprecationWarning)
1642 self.assertEqual(error.filename, 'source')
1643 error.filename = 'filename'
1644 self.assertEqual(error.source, 'filename')
1645 for warning in w:
1646 self.assertTrue(warning.category is DeprecationWarning)
1647
1648 def test_interpolation_validation(self):
1649 parser = configparser.ConfigParser()
1650 parser.read_string("""
1651 [section]
1652 invalid_percent = %
1653 invalid_reference = %(()
1654 invalid_variable = %(does_not_exist)s
1655 """)
1656 with self.assertRaises(configparser.InterpolationSyntaxError) as cm:
1657 parser['section']['invalid_percent']
1658 self.assertEqual(str(cm.exception), "'%' must be followed by '%' or "
1659 "'(', found: '%'")
1660 with self.assertRaises(configparser.InterpolationSyntaxError) as cm:
1661 parser['section']['invalid_reference']
1662 self.assertEqual(str(cm.exception), "bad interpolation variable "
1663 "reference '%(()'")
1664
1665 def test_readfp_deprecation(self):
1666 sio = io.StringIO("""
1667 [section]
1668 option = value
1669 """)
1670 parser = configparser.ConfigParser()
1671 with warnings.catch_warnings(record=True) as w:
1672 warnings.simplefilter("always", DeprecationWarning)
1673 parser.readfp(sio, filename='StringIO')
1674 for warning in w:
1675 self.assertTrue(warning.category is DeprecationWarning)
1676 self.assertEqual(len(parser), 2)
1677 self.assertEqual(parser['section']['option'], 'value')
1678
1679 def test_safeconfigparser_deprecation(self):
1680 with warnings.catch_warnings(record=True) as w:
1681 warnings.simplefilter("always", DeprecationWarning)
1682 parser = configparser.SafeConfigParser()
1683 for warning in w:
1684 self.assertTrue(warning.category is DeprecationWarning)
1685
1686 def test_legacyinterpolation_deprecation(self):
1687 with warnings.catch_warnings(record=True) as w:
1688 warnings.simplefilter("always", DeprecationWarning)
1689 configparser.LegacyInterpolation()
1690 self.assertGreaterEqual(len(w), 1)
1691 for warning in w:
1692 self.assertIs(warning.category, DeprecationWarning)
1693
1694 def test_sectionproxy_repr(self):
1695 parser = configparser.ConfigParser()
1696 parser.read_string("""
1697 [section]
1698 key = value
1699 """)
1700 self.assertEqual(repr(parser['section']), '<Section: section>')
1701
1702 def test_inconsistent_converters_state(self):
1703 parser = configparser.ConfigParser()
1704 import decimal
1705 parser.converters['decimal'] = decimal.Decimal
1706 parser.read_string("""
1707 [s1]
1708 one = 1
1709 [s2]
1710 two = 2
1711 """)
1712 self.assertIn('decimal', parser.converters)
1713 self.assertEqual(parser.getdecimal('s1', 'one'), 1)
1714 self.assertEqual(parser.getdecimal('s2', 'two'), 2)
1715 self.assertEqual(parser['s1'].getdecimal('one'), 1)
1716 self.assertEqual(parser['s2'].getdecimal('two'), 2)
1717 del parser.getdecimal
1718 with self.assertRaises(AttributeError):
1719 parser.getdecimal('s1', 'one')
1720 self.assertIn('decimal', parser.converters)
1721 del parser.converters['decimal']
1722 self.assertNotIn('decimal', parser.converters)
1723 with self.assertRaises(AttributeError):
1724 parser.getdecimal('s1', 'one')
1725 with self.assertRaises(AttributeError):
1726 parser['s1'].getdecimal('one')
1727 with self.assertRaises(AttributeError):
1728 parser['s2'].getdecimal('two')
1729
1730
1731 class ExceptionPicklingTestCase(unittest.TestCase):
1732 """Tests for issue #13760: ConfigParser exceptions are not picklable."""
1733
1734 def test_error(self):
1735 import pickle
1736 e1 = configparser.Error('value')
1737 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1738 pickled = pickle.dumps(e1, proto)
1739 e2 = pickle.loads(pickled)
1740 self.assertEqual(e1.message, e2.message)
1741 self.assertEqual(repr(e1), repr(e2))
1742
1743 def test_nosectionerror(self):
1744 import pickle
1745 e1 = configparser.NoSectionError('section')
1746 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1747 pickled = pickle.dumps(e1, proto)
1748 e2 = pickle.loads(pickled)
1749 self.assertEqual(e1.message, e2.message)
1750 self.assertEqual(e1.args, e2.args)
1751 self.assertEqual(e1.section, e2.section)
1752 self.assertEqual(repr(e1), repr(e2))
1753
1754 def test_nooptionerror(self):
1755 import pickle
1756 e1 = configparser.NoOptionError('option', 'section')
1757 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1758 pickled = pickle.dumps(e1, proto)
1759 e2 = pickle.loads(pickled)
1760 self.assertEqual(e1.message, e2.message)
1761 self.assertEqual(e1.args, e2.args)
1762 self.assertEqual(e1.section, e2.section)
1763 self.assertEqual(e1.option, e2.option)
1764 self.assertEqual(repr(e1), repr(e2))
1765
1766 def test_duplicatesectionerror(self):
1767 import pickle
1768 e1 = configparser.DuplicateSectionError('section', 'source', 123)
1769 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1770 pickled = pickle.dumps(e1, proto)
1771 e2 = pickle.loads(pickled)
1772 self.assertEqual(e1.message, e2.message)
1773 self.assertEqual(e1.args, e2.args)
1774 self.assertEqual(e1.section, e2.section)
1775 self.assertEqual(e1.source, e2.source)
1776 self.assertEqual(e1.lineno, e2.lineno)
1777 self.assertEqual(repr(e1), repr(e2))
1778
1779 def test_duplicateoptionerror(self):
1780 import pickle
1781 e1 = configparser.DuplicateOptionError('section', 'option', 'source',
1782 123)
1783 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1784 pickled = pickle.dumps(e1, proto)
1785 e2 = pickle.loads(pickled)
1786 self.assertEqual(e1.message, e2.message)
1787 self.assertEqual(e1.args, e2.args)
1788 self.assertEqual(e1.section, e2.section)
1789 self.assertEqual(e1.option, e2.option)
1790 self.assertEqual(e1.source, e2.source)
1791 self.assertEqual(e1.lineno, e2.lineno)
1792 self.assertEqual(repr(e1), repr(e2))
1793
1794 def test_interpolationerror(self):
1795 import pickle
1796 e1 = configparser.InterpolationError('option', 'section', 'msg')
1797 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1798 pickled = pickle.dumps(e1, proto)
1799 e2 = pickle.loads(pickled)
1800 self.assertEqual(e1.message, e2.message)
1801 self.assertEqual(e1.args, e2.args)
1802 self.assertEqual(e1.section, e2.section)
1803 self.assertEqual(e1.option, e2.option)
1804 self.assertEqual(repr(e1), repr(e2))
1805
1806 def test_interpolationmissingoptionerror(self):
1807 import pickle
1808 e1 = configparser.InterpolationMissingOptionError('option', 'section',
1809 'rawval', 'reference')
1810 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1811 pickled = pickle.dumps(e1, proto)
1812 e2 = pickle.loads(pickled)
1813 self.assertEqual(e1.message, e2.message)
1814 self.assertEqual(e1.args, e2.args)
1815 self.assertEqual(e1.section, e2.section)
1816 self.assertEqual(e1.option, e2.option)
1817 self.assertEqual(e1.reference, e2.reference)
1818 self.assertEqual(repr(e1), repr(e2))
1819
1820 def test_interpolationsyntaxerror(self):
1821 import pickle
1822 e1 = configparser.InterpolationSyntaxError('option', 'section', 'msg')
1823 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1824 pickled = pickle.dumps(e1, proto)
1825 e2 = pickle.loads(pickled)
1826 self.assertEqual(e1.message, e2.message)
1827 self.assertEqual(e1.args, e2.args)
1828 self.assertEqual(e1.section, e2.section)
1829 self.assertEqual(e1.option, e2.option)
1830 self.assertEqual(repr(e1), repr(e2))
1831
1832 def test_interpolationdeptherror(self):
1833 import pickle
1834 e1 = configparser.InterpolationDepthError('option', 'section',
1835 'rawval')
1836 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1837 pickled = pickle.dumps(e1, proto)
1838 e2 = pickle.loads(pickled)
1839 self.assertEqual(e1.message, e2.message)
1840 self.assertEqual(e1.args, e2.args)
1841 self.assertEqual(e1.section, e2.section)
1842 self.assertEqual(e1.option, e2.option)
1843 self.assertEqual(repr(e1), repr(e2))
1844
1845 def test_parsingerror(self):
1846 import pickle
1847 e1 = configparser.ParsingError('source')
1848 e1.append(1, 'line1')
1849 e1.append(2, 'line2')
1850 e1.append(3, 'line3')
1851 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1852 pickled = pickle.dumps(e1, proto)
1853 e2 = pickle.loads(pickled)
1854 self.assertEqual(e1.message, e2.message)
1855 self.assertEqual(e1.args, e2.args)
1856 self.assertEqual(e1.source, e2.source)
1857 self.assertEqual(e1.errors, e2.errors)
1858 self.assertEqual(repr(e1), repr(e2))
1859 e1 = configparser.ParsingError(filename='filename')
1860 e1.append(1, 'line1')
1861 e1.append(2, 'line2')
1862 e1.append(3, 'line3')
1863 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1864 pickled = pickle.dumps(e1, proto)
1865 e2 = pickle.loads(pickled)
1866 self.assertEqual(e1.message, e2.message)
1867 self.assertEqual(e1.args, e2.args)
1868 self.assertEqual(e1.source, e2.source)
1869 self.assertEqual(e1.errors, e2.errors)
1870 self.assertEqual(repr(e1), repr(e2))
1871
1872 def test_missingsectionheadererror(self):
1873 import pickle
1874 e1 = configparser.MissingSectionHeaderError('filename', 123, 'line')
1875 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1876 pickled = pickle.dumps(e1, proto)
1877 e2 = pickle.loads(pickled)
1878 self.assertEqual(e1.message, e2.message)
1879 self.assertEqual(e1.args, e2.args)
1880 self.assertEqual(e1.line, e2.line)
1881 self.assertEqual(e1.source, e2.source)
1882 self.assertEqual(e1.lineno, e2.lineno)
1883 self.assertEqual(repr(e1), repr(e2))
1884
1885
1886 class InlineCommentStrippingTestCase(unittest.TestCase):
1887 """Tests for issue #14590: ConfigParser doesn't strip inline comment when
1888 delimiter occurs earlier without preceding space.."""
1889
1890 def test_stripping(self):
1891 cfg = configparser.ConfigParser(inline_comment_prefixes=(';', '#',
1892 '//'))
1893 cfg.read_string("""
1894 [section]
1895 k1 = v1;still v1
1896 k2 = v2 ;a comment
1897 k3 = v3 ; also a comment
1898 k4 = v4;still v4 ;a comment
1899 k5 = v5;still v5 ; also a comment
1900 k6 = v6;still v6; and still v6 ;a comment
1901 k7 = v7;still v7; and still v7 ; also a comment
1902
1903 [multiprefix]
1904 k1 = v1;still v1 #a comment ; yeah, pretty much
1905 k2 = v2 // this already is a comment ; continued
1906 k3 = v3;#//still v3# and still v3 ; a comment
1907 """)
1908 s = cfg['section']
1909 self.assertEqual(s['k1'], 'v1;still v1')
1910 self.assertEqual(s['k2'], 'v2')
1911 self.assertEqual(s['k3'], 'v3')
1912 self.assertEqual(s['k4'], 'v4;still v4')
1913 self.assertEqual(s['k5'], 'v5;still v5')
1914 self.assertEqual(s['k6'], 'v6;still v6; and still v6')
1915 self.assertEqual(s['k7'], 'v7;still v7; and still v7')
1916 s = cfg['multiprefix']
1917 self.assertEqual(s['k1'], 'v1;still v1')
1918 self.assertEqual(s['k2'], 'v2')
1919 self.assertEqual(s['k3'], 'v3;#//still v3# and still v3')
1920
1921
1922 class ExceptionContextTestCase(unittest.TestCase):
1923 """ Test that implementation details doesn't leak
1924 through raising exceptions. """
1925
1926 def test_get_basic_interpolation(self):
1927 parser = configparser.ConfigParser()
1928 parser.read_string("""
1929 [Paths]
1930 home_dir: /Users
1931 my_dir: %(home_dir1)s/lumberjack
1932 my_pictures: %(my_dir)s/Pictures
1933 """)
1934 cm = self.assertRaises(configparser.InterpolationMissingOptionError)
1935 with cm:
1936 parser.get('Paths', 'my_dir')
1937 self.assertIs(cm.exception.__suppress_context__, True)
1938
1939 def test_get_extended_interpolation(self):
1940 parser = configparser.ConfigParser(
1941 interpolation=configparser.ExtendedInterpolation())
1942 parser.read_string("""
1943 [Paths]
1944 home_dir: /Users
1945 my_dir: ${home_dir1}/lumberjack
1946 my_pictures: ${my_dir}/Pictures
1947 """)
1948 cm = self.assertRaises(configparser.InterpolationMissingOptionError)
1949 with cm:
1950 parser.get('Paths', 'my_dir')
1951 self.assertIs(cm.exception.__suppress_context__, True)
1952
1953 def test_missing_options(self):
1954 parser = configparser.ConfigParser()
1955 parser.read_string("""
1956 [Paths]
1957 home_dir: /Users
1958 """)
1959 with self.assertRaises(configparser.NoSectionError) as cm:
1960 parser.options('test')
1961 self.assertIs(cm.exception.__suppress_context__, True)
1962
1963 def test_missing_section(self):
1964 config = configparser.ConfigParser()
1965 with self.assertRaises(configparser.NoSectionError) as cm:
1966 config.set('Section1', 'an_int', '15')
1967 self.assertIs(cm.exception.__suppress_context__, True)
1968
1969 def test_remove_option(self):
1970 config = configparser.ConfigParser()
1971 with self.assertRaises(configparser.NoSectionError) as cm:
1972 config.remove_option('Section1', 'an_int')
1973 self.assertIs(cm.exception.__suppress_context__, True)
1974
1975
1976 class ConvertersTestCase(BasicTestCase, unittest.TestCase):
1977 """Introduced in 3.5, issue #18159."""
1978
1979 config_class = configparser.ConfigParser
1980
1981 def newconfig(self, defaults=None):
1982 instance = super().newconfig(defaults=defaults)
1983 instance.converters['list'] = lambda v: [e.strip() for e in v.split()
1984 if e.strip()]
1985 return instance
1986
1987 def test_converters(self):
1988 cfg = self.newconfig()
1989 self.assertIn('boolean', cfg.converters)
1990 self.assertIn('list', cfg.converters)
1991 self.assertIsNone(cfg.converters['int'])
1992 self.assertIsNone(cfg.converters['float'])
1993 self.assertIsNone(cfg.converters['boolean'])
1994 self.assertIsNotNone(cfg.converters['list'])
1995 self.assertEqual(len(cfg.converters), 4)
1996 with self.assertRaises(ValueError):
1997 cfg.converters[''] = lambda v: v
1998 with self.assertRaises(ValueError):
1999 cfg.converters[None] = lambda v: v
2000 cfg.read_string("""
2001 [s]
2002 str = string
2003 int = 1
2004 float = 0.5
2005 list = a b c d e f g
2006 bool = yes
2007 """)
2008 s = cfg['s']
2009 self.assertEqual(s['str'], 'string')
2010 self.assertEqual(s['int'], '1')
2011 self.assertEqual(s['float'], '0.5')
2012 self.assertEqual(s['list'], 'a b c d e f g')
2013 self.assertEqual(s['bool'], 'yes')
2014 self.assertEqual(cfg.get('s', 'str'), 'string')
2015 self.assertEqual(cfg.get('s', 'int'), '1')
2016 self.assertEqual(cfg.get('s', 'float'), '0.5')
2017 self.assertEqual(cfg.get('s', 'list'), 'a b c d e f g')
2018 self.assertEqual(cfg.get('s', 'bool'), 'yes')
2019 self.assertEqual(cfg.get('s', 'str'), 'string')
2020 self.assertEqual(cfg.getint('s', 'int'), 1)
2021 self.assertEqual(cfg.getfloat('s', 'float'), 0.5)
2022 self.assertEqual(cfg.getlist('s', 'list'), ['a', 'b', 'c', 'd',
2023 'e', 'f', 'g'])
2024 self.assertEqual(cfg.getboolean('s', 'bool'), True)
2025 self.assertEqual(s.get('str'), 'string')
2026 self.assertEqual(s.getint('int'), 1)
2027 self.assertEqual(s.getfloat('float'), 0.5)
2028 self.assertEqual(s.getlist('list'), ['a', 'b', 'c', 'd',
2029 'e', 'f', 'g'])
2030 self.assertEqual(s.getboolean('bool'), True)
2031 with self.assertRaises(AttributeError):
2032 cfg.getdecimal('s', 'float')
2033 with self.assertRaises(AttributeError):
2034 s.getdecimal('float')
2035 import decimal
2036 cfg.converters['decimal'] = decimal.Decimal
2037 self.assertIn('decimal', cfg.converters)
2038 self.assertIsNotNone(cfg.converters['decimal'])
2039 self.assertEqual(len(cfg.converters), 5)
2040 dec0_5 = decimal.Decimal('0.5')
2041 self.assertEqual(cfg.getdecimal('s', 'float'), dec0_5)
2042 self.assertEqual(s.getdecimal('float'), dec0_5)
2043 del cfg.converters['decimal']
2044 self.assertNotIn('decimal', cfg.converters)
2045 self.assertEqual(len(cfg.converters), 4)
2046 with self.assertRaises(AttributeError):
2047 cfg.getdecimal('s', 'float')
2048 with self.assertRaises(AttributeError):
2049 s.getdecimal('float')
2050 with self.assertRaises(KeyError):
2051 del cfg.converters['decimal']
2052 with self.assertRaises(KeyError):
2053 del cfg.converters['']
2054 with self.assertRaises(KeyError):
2055 del cfg.converters[None]
2056
2057
2058 class BlatantOverrideConvertersTestCase(unittest.TestCase):
2059 """What if somebody overrode a getboolean()? We want to make sure that in
2060 this case the automatic converters do not kick in."""
2061
2062 config = """
2063 [one]
2064 one = false
2065 two = false
2066 three = long story short
2067
2068 [two]
2069 one = false
2070 two = false
2071 three = four
2072 """
2073
2074 def test_converters_at_init(self):
2075 cfg = configparser.ConfigParser(converters={'len': len})
2076 cfg.read_string(self.config)
2077 self._test_len(cfg)
2078 self.assertIsNotNone(cfg.converters['len'])
2079
2080 def test_inheritance(self):
2081 class StrangeConfigParser(configparser.ConfigParser):
2082 gettysburg = 'a historic borough in south central Pennsylvania'
2083
2084 def getboolean(self, section, option, *, raw=False, vars=None,
2085 fallback=configparser._UNSET):
2086 if section == option:
2087 return True
2088 return super().getboolean(section, option, raw=raw, vars=vars,
2089 fallback=fallback)
2090 def getlen(self, section, option, *, raw=False, vars=None,
2091 fallback=configparser._UNSET):
2092 return self._get_conv(section, option, len, raw=raw, vars=vars,
2093 fallback=fallback)
2094
2095 cfg = StrangeConfigParser()
2096 cfg.read_string(self.config)
2097 self._test_len(cfg)
2098 self.assertIsNone(cfg.converters['len'])
2099 self.assertTrue(cfg.getboolean('one', 'one'))
2100 self.assertTrue(cfg.getboolean('two', 'two'))
2101 self.assertFalse(cfg.getboolean('one', 'two'))
2102 self.assertFalse(cfg.getboolean('two', 'one'))
2103 cfg.converters['boolean'] = cfg._convert_to_boolean
2104 self.assertFalse(cfg.getboolean('one', 'one'))
2105 self.assertFalse(cfg.getboolean('two', 'two'))
2106 self.assertFalse(cfg.getboolean('one', 'two'))
2107 self.assertFalse(cfg.getboolean('two', 'one'))
2108
2109 def _test_len(self, cfg):
2110 self.assertEqual(len(cfg.converters), 4)
2111 self.assertIn('boolean', cfg.converters)
2112 self.assertIn('len', cfg.converters)
2113 self.assertNotIn('tysburg', cfg.converters)
2114 self.assertIsNone(cfg.converters['int'])
2115 self.assertIsNone(cfg.converters['float'])
2116 self.assertIsNone(cfg.converters['boolean'])
2117 self.assertEqual(cfg.getlen('one', 'one'), 5)
2118 self.assertEqual(cfg.getlen('one', 'two'), 5)
2119 self.assertEqual(cfg.getlen('one', 'three'), 16)
2120 self.assertEqual(cfg.getlen('two', 'one'), 5)
2121 self.assertEqual(cfg.getlen('two', 'two'), 5)
2122 self.assertEqual(cfg.getlen('two', 'three'), 4)
2123 self.assertEqual(cfg.getlen('two', 'four', fallback=0), 0)
2124 with self.assertRaises(configparser.NoOptionError):
2125 cfg.getlen('two', 'four')
2126 self.assertEqual(cfg['one'].getlen('one'), 5)
2127 self.assertEqual(cfg['one'].getlen('two'), 5)
2128 self.assertEqual(cfg['one'].getlen('three'), 16)
2129 self.assertEqual(cfg['two'].getlen('one'), 5)
2130 self.assertEqual(cfg['two'].getlen('two'), 5)
2131 self.assertEqual(cfg['two'].getlen('three'), 4)
2132 self.assertEqual(cfg['two'].getlen('four', 0), 0)
2133 self.assertEqual(cfg['two'].getlen('four'), None)
2134
2135 def test_instance_assignment(self):
2136 cfg = configparser.ConfigParser()
2137 cfg.getboolean = lambda section, option: True
2138 cfg.getlen = lambda section, option: len(cfg[section][option])
2139 cfg.read_string(self.config)
2140 self.assertEqual(len(cfg.converters), 3)
2141 self.assertIn('boolean', cfg.converters)
2142 self.assertNotIn('len', cfg.converters)
2143 self.assertIsNone(cfg.converters['int'])
2144 self.assertIsNone(cfg.converters['float'])
2145 self.assertIsNone(cfg.converters['boolean'])
2146 self.assertTrue(cfg.getboolean('one', 'one'))
2147 self.assertTrue(cfg.getboolean('two', 'two'))
2148 self.assertTrue(cfg.getboolean('one', 'two'))
2149 self.assertTrue(cfg.getboolean('two', 'one'))
2150 cfg.converters['boolean'] = cfg._convert_to_boolean
2151 self.assertFalse(cfg.getboolean('one', 'one'))
2152 self.assertFalse(cfg.getboolean('two', 'two'))
2153 self.assertFalse(cfg.getboolean('one', 'two'))
2154 self.assertFalse(cfg.getboolean('two', 'one'))
2155 self.assertEqual(cfg.getlen('one', 'one'), 5)
2156 self.assertEqual(cfg.getlen('one', 'two'), 5)
2157 self.assertEqual(cfg.getlen('one', 'three'), 16)
2158 self.assertEqual(cfg.getlen('two', 'one'), 5)
2159 self.assertEqual(cfg.getlen('two', 'two'), 5)
2160 self.assertEqual(cfg.getlen('two', 'three'), 4)
2161 # If a getter impl is assigned straight to the instance, it won't
2162 # be available on the section proxies.
2163 with self.assertRaises(AttributeError):
2164 self.assertEqual(cfg['one'].getlen('one'), 5)
2165 with self.assertRaises(AttributeError):
2166 self.assertEqual(cfg['two'].getlen('one'), 5)
2167
2168
2169 class MiscTestCase(unittest.TestCase):
2170 def test__all__(self):
2171 support.check__all__(self, configparser, not_exported={"Error"})
2172
2173
2174 if __name__ == '__main__':
2175 unittest.main()