Back to index

python3.2  3.2.2
Public Member Functions | Static Public Attributes
test.test_cfgparser.SortedTestCase Class Reference
Inheritance diagram for test.test_cfgparser.SortedTestCase:
Inheritance graph
[legend]
Collaboration diagram for test.test_cfgparser.SortedTestCase:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def test_sorted
def test_interpolation
def test_items
def test_set_nonstring_types
def basic_test
def test_basic
def test_basic_from_dict
def test_case_sensitivity
def test_case_sensitivity_mapping_access
def test_default_case_sensitivity
def test_parse_errors
def parse_error
def test_query_errors
def get_error
def test_boolean
def test_weird_errors
def test_write
def test_set_string_types
def test_read_returns_file_list
def get_interpolation_config
def check_items_config
def newconfig
def fromstring

Static Public Attributes

 dict_type = SortedDict
 config_class = configparser.RawConfigParser
 allow_no_value = False
tuple delimiters = ('=', ':')
tuple comment_prefixes = (';', '#')
tuple inline_comment_prefixes = (';', '#')
 empty_lines_in_values = True
 strict = False
 default_section = configparser.DEFAULTSECT
 interpolation = configparser._UNSET

Detailed Description

Definition at line 1276 of file test_cfgparser.py.


Member Function Documentation

def test.test_cfgparser.BasicTestCase.basic_test (   self,
  cf 
) [inherited]

Definition at line 69 of file test_cfgparser.py.

00069 
00070     def basic_test(self, cf):
00071         E = ['Commented Bar',
00072              'Foo Bar',
00073              'Internationalized Stuff',
00074              'Long Line',
00075              'Section\\with$weird%characters[\t',
00076              'Spaces',
00077              'Spacey Bar',
00078              'Spacey Bar From The Beginning',
00079              'Types',
00080              ]
00081 
00082         if self.allow_no_value:
00083             E.append('NoValue')
00084         E.sort()
00085         F = [('baz', 'qwe'), ('foo', 'bar3')]
00086 
00087         # API access
00088         L = cf.sections()
00089         L.sort()
00090         eq = self.assertEqual
00091         eq(L, E)
00092         L = cf.items('Spacey Bar From The Beginning')
00093         L.sort()
00094         eq(L, F)
00095 
00096         # mapping access
00097         L = [section for section in cf]
00098         L.sort()
00099         E.append(self.default_section)
00100         E.sort()
00101         eq(L, E)
00102         L = cf['Spacey Bar From The Beginning'].items()
00103         L = sorted(list(L))
00104         eq(L, F)
00105         L = cf.items()
00106         L = sorted(list(L))
00107         self.assertEqual(len(L), len(E))
00108         for name, section in L:
00109             eq(name, section.name)
00110         eq(cf.defaults(), cf[self.default_section])
00111 
00112         # The use of spaces in the section names serves as a
00113         # regression test for SourceForge bug #583248:
00114         # http://www.python.org/sf/583248
00115 
00116         # API access
00117         eq(cf.get('Foo Bar', 'foo'), 'bar1')
00118         eq(cf.get('Spacey Bar', 'foo'), 'bar2')
00119         eq(cf.get('Spacey Bar From The Beginning', 'foo'), 'bar3')
00120         eq(cf.get('Spacey Bar From The Beginning', 'baz'), 'qwe')
00121         eq(cf.get('Commented Bar', 'foo'), 'bar4')
00122         eq(cf.get('Commented Bar', 'baz'), 'qwe')
00123         eq(cf.get('Spaces', 'key with spaces'), 'value')
00124         eq(cf.get('Spaces', 'another with spaces'), 'splat!')
00125         eq(cf.getint('Types', 'int'), 42)
00126         eq(cf.get('Types', 'int'), "42")
00127         self.assertAlmostEqual(cf.getfloat('Types', 'float'), 0.44)
00128         eq(cf.get('Types', 'float'), "0.44")
00129         eq(cf.getboolean('Types', 'boolean'), False)
00130         eq(cf.get('Types', '123'), 'strange but acceptable')
00131         if self.allow_no_value:
00132             eq(cf.get('NoValue', 'option-without-value'), None)
00133 
00134         # test vars= and fallback=
00135         eq(cf.get('Foo Bar', 'foo', fallback='baz'), 'bar1')
00136         eq(cf.get('Foo Bar', 'foo', vars={'foo': 'baz'}), 'baz')
00137         with self.assertRaises(configparser.NoSectionError):
00138             cf.get('No Such Foo Bar', 'foo')
00139         with self.assertRaises(configparser.NoOptionError):
00140             cf.get('Foo Bar', 'no-such-foo')
00141         eq(cf.get('No Such Foo Bar', 'foo', fallback='baz'), 'baz')
00142         eq(cf.get('Foo Bar', 'no-such-foo', fallback='baz'), 'baz')
00143         eq(cf.get('Spacey Bar', 'foo', fallback=None), 'bar2')
00144         eq(cf.get('No Such Spacey Bar', 'foo', fallback=None), None)
00145         eq(cf.getint('Types', 'int', fallback=18), 42)
00146         eq(cf.getint('Types', 'no-such-int', fallback=18), 18)
00147         eq(cf.getint('Types', 'no-such-int', fallback="18"), "18") # sic!
00148         with self.assertRaises(configparser.NoOptionError):
00149             cf.getint('Types', 'no-such-int')
00150         self.assertAlmostEqual(cf.getfloat('Types', 'float',
00151                                            fallback=0.0), 0.44)
00152         self.assertAlmostEqual(cf.getfloat('Types', 'no-such-float',
00153                                            fallback=0.0), 0.0)
00154         eq(cf.getfloat('Types', 'no-such-float', fallback="0.0"), "0.0") # sic!
00155         with self.assertRaises(configparser.NoOptionError):
00156             cf.getfloat('Types', 'no-such-float')
00157         eq(cf.getboolean('Types', 'boolean', fallback=True), False)
00158         eq(cf.getboolean('Types', 'no-such-boolean', fallback="yes"),
00159            "yes") # sic!
00160         eq(cf.getboolean('Types', 'no-such-boolean', fallback=True), True)
00161         with self.assertRaises(configparser.NoOptionError):
00162             cf.getboolean('Types', 'no-such-boolean')
00163         eq(cf.getboolean('No Such Types', 'boolean', fallback=True), True)
00164         if self.allow_no_value:
00165             eq(cf.get('NoValue', 'option-without-value', fallback=False), None)
00166             eq(cf.get('NoValue', 'no-such-option-without-value',
00167                       fallback=False), False)
00168 
00169         # mapping access
00170         eq(cf['Foo Bar']['foo'], 'bar1')
00171         eq(cf['Spacey Bar']['foo'], 'bar2')
00172         section = cf['Spacey Bar From The Beginning']
00173         eq(section.name, 'Spacey Bar From The Beginning')
00174         self.assertIs(section.parser, cf)
00175         with self.assertRaises(AttributeError):
00176             section.name = 'Name is read-only'
00177         with self.assertRaises(AttributeError):
00178             section.parser = 'Parser is read-only'
00179         eq(section['foo'], 'bar3')
00180         eq(section['baz'], 'qwe')
00181         eq(cf['Commented Bar']['foo'], 'bar4')
00182         eq(cf['Commented Bar']['baz'], 'qwe')
00183         eq(cf['Spaces']['key with spaces'], 'value')
00184         eq(cf['Spaces']['another with spaces'], 'splat!')
00185         eq(cf['Long Line']['foo'],
00186            'this line is much, much longer than my editor\nlikes it.')
00187         if self.allow_no_value:
00188             eq(cf['NoValue']['option-without-value'], None)
00189         # test vars= and fallback=
00190         eq(cf['Foo Bar'].get('foo', 'baz'), 'bar1')
00191         eq(cf['Foo Bar'].get('foo', fallback='baz'), 'bar1')
00192         eq(cf['Foo Bar'].get('foo', vars={'foo': 'baz'}), 'baz')
00193         with self.assertRaises(KeyError):
00194             cf['No Such Foo Bar']['foo']
00195         with self.assertRaises(KeyError):
00196             cf['Foo Bar']['no-such-foo']
00197         with self.assertRaises(KeyError):
00198             cf['No Such Foo Bar'].get('foo', fallback='baz')
00199         eq(cf['Foo Bar'].get('no-such-foo', 'baz'), 'baz')
00200         eq(cf['Foo Bar'].get('no-such-foo', fallback='baz'), 'baz')
00201         eq(cf['Foo Bar'].get('no-such-foo'), None)
00202         eq(cf['Spacey Bar'].get('foo', None), 'bar2')
00203         eq(cf['Spacey Bar'].get('foo', fallback=None), 'bar2')
00204         with self.assertRaises(KeyError):
00205             cf['No Such Spacey Bar'].get('foo', None)
00206         eq(cf['Types'].getint('int', 18), 42)
00207         eq(cf['Types'].getint('int', fallback=18), 42)
00208         eq(cf['Types'].getint('no-such-int', 18), 18)
00209         eq(cf['Types'].getint('no-such-int', fallback=18), 18)
00210         eq(cf['Types'].getint('no-such-int', "18"), "18") # sic!
00211         eq(cf['Types'].getint('no-such-int', fallback="18"), "18") # sic!
00212         eq(cf['Types'].getint('no-such-int'), None)
00213         self.assertAlmostEqual(cf['Types'].getfloat('float', 0.0), 0.44)
00214         self.assertAlmostEqual(cf['Types'].getfloat('float',
00215                                                     fallback=0.0), 0.44)
00216         self.assertAlmostEqual(cf['Types'].getfloat('no-such-float', 0.0), 0.0)
00217         self.assertAlmostEqual(cf['Types'].getfloat('no-such-float',
00218                                                     fallback=0.0), 0.0)
00219         eq(cf['Types'].getfloat('no-such-float', "0.0"), "0.0") # sic!
00220         eq(cf['Types'].getfloat('no-such-float', fallback="0.0"), "0.0") # sic!
00221         eq(cf['Types'].getfloat('no-such-float'), None)
00222         eq(cf['Types'].getboolean('boolean', True), False)
00223         eq(cf['Types'].getboolean('boolean', fallback=True), False)
00224         eq(cf['Types'].getboolean('no-such-boolean', "yes"), "yes") # sic!
00225         eq(cf['Types'].getboolean('no-such-boolean', fallback="yes"),
00226            "yes") # sic!
00227         eq(cf['Types'].getboolean('no-such-boolean', True), True)
00228         eq(cf['Types'].getboolean('no-such-boolean', fallback=True), True)
00229         eq(cf['Types'].getboolean('no-such-boolean'), None)
00230         if self.allow_no_value:
00231             eq(cf['NoValue'].get('option-without-value', False), None)
00232             eq(cf['NoValue'].get('option-without-value', fallback=False), None)
00233             eq(cf['NoValue'].get('no-such-option-without-value', False), False)
00234             eq(cf['NoValue'].get('no-such-option-without-value',
00235                       fallback=False), False)
00236 
00237         # Make sure the right things happen for remove_section() and
00238         # remove_option(); added to include check for SourceForge bug #123324.
00239 
00240         cf[self.default_section]['this_value'] = '1'
00241         cf[self.default_section]['that_value'] = '2'
00242 
00243         # API access
00244         self.assertTrue(cf.remove_section('Spaces'))
00245         self.assertFalse(cf.has_option('Spaces', 'key with spaces'))
00246         self.assertFalse(cf.remove_section('Spaces'))
00247         self.assertFalse(cf.remove_section(self.default_section))
00248         self.assertTrue(cf.remove_option('Foo Bar', 'foo'),
00249                         "remove_option() failed to report existence of option")
00250         self.assertFalse(cf.has_option('Foo Bar', 'foo'),
00251                     "remove_option() failed to remove option")
00252         self.assertFalse(cf.remove_option('Foo Bar', 'foo'),
00253                     "remove_option() failed to report non-existence of option"
00254                     " that was removed")
00255         self.assertTrue(cf.has_option('Foo Bar', 'this_value'))
00256         self.assertFalse(cf.remove_option('Foo Bar', 'this_value'))
00257         self.assertTrue(cf.remove_option(self.default_section, 'this_value'))
00258         self.assertFalse(cf.has_option('Foo Bar', 'this_value'))
00259         self.assertFalse(cf.remove_option(self.default_section, 'this_value'))
00260 
00261         with self.assertRaises(configparser.NoSectionError) as cm:
00262             cf.remove_option('No Such Section', 'foo')
00263         self.assertEqual(cm.exception.args, ('No Such Section',))
00264 
00265         eq(cf.get('Long Line', 'foo'),
00266            'this line is much, much longer than my editor\nlikes it.')
00267 
00268         # mapping access
00269         del cf['Types']
00270         self.assertFalse('Types' in cf)
00271         with self.assertRaises(KeyError):
00272             del cf['Types']
00273         with self.assertRaises(ValueError):
00274             del cf[self.default_section]
00275         del cf['Spacey Bar']['foo']
00276         self.assertFalse('foo' in cf['Spacey Bar'])
00277         with self.assertRaises(KeyError):
00278             del cf['Spacey Bar']['foo']
00279         self.assertTrue('that_value' in cf['Spacey Bar'])
00280         with self.assertRaises(KeyError):
00281             del cf['Spacey Bar']['that_value']
00282         del cf[self.default_section]['that_value']
00283         self.assertFalse('that_value' in cf['Spacey Bar'])
00284         with self.assertRaises(KeyError):
00285             del cf[self.default_section]['that_value']
00286         with self.assertRaises(KeyError):
00287             del cf['No Such Section']['foo']
00288 
00289         # Don't add new asserts below in this method as most of the options
00290         # and sections are now removed.

Here is the call graph for this function:

Here is the caller graph for this function:

def test.test_cfgparser.BasicTestCase.check_items_config (   self,
  expected 
) [inherited]

Definition at line 760 of file test_cfgparser.py.

00760 
00761     def check_items_config(self, expected):
00762         cf = self.fromstring("""
00763             [section]
00764             name {0[0]} %(value)s
00765             key{0[1]} |%(name)s|
00766             getdefault{0[1]} |%(default)s|
00767         """.format(self.delimiters), defaults={"default": "<default>"})
00768         L = list(cf.items("section", vars={'value': 'value'}))
00769         L.sort()
00770         self.assertEqual(L, expected)
00771         with self.assertRaises(configparser.NoSectionError):
00772             cf.items("no such section")
00773 

Here is the call graph for this function:

Here is the caller graph for this function:

def test.test_cfgparser.CfgParserTestCaseClass.fromstring (   self,
  string,
  defaults = None 
) [inherited]

Reimplemented in test.test_cfgparser.CopyTestCase.

Definition at line 62 of file test_cfgparser.py.

00062 
00063     def fromstring(self, string, defaults=None):
00064         cf = self.newconfig(defaults)
00065         cf.read_string(string)
00066         return cf

Here is the call graph for this function:

Here is the caller graph for this function:

def test.test_cfgparser.BasicTestCase.get_error (   self,
  cf,
  exc,
  section,
  option 
) [inherited]

Definition at line 575 of file test_cfgparser.py.

00575 
00576     def get_error(self, cf, exc, section, option):
00577         try:
00578             cf.get(section, option)
00579         except exc as e:
00580             return e
00581         else:
00582             self.fail("expected exception type %s.%s"
00583                       % (exc.__module__, exc.__name__))

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 733 of file test_cfgparser.py.

00733 
00734     def get_interpolation_config(self):
00735         return self.fromstring(
00736             "[Foo]\n"
00737             "bar{equals}something %(with1)s interpolation (1 step)\n"
00738             "bar9{equals}something %(with9)s lots of interpolation (9 steps)\n"
00739             "bar10{equals}something %(with10)s lots of interpolation (10 steps)\n"
00740             "bar11{equals}something %(with11)s lots of interpolation (11 steps)\n"
00741             "with11{equals}%(with10)s\n"
00742             "with10{equals}%(with9)s\n"
00743             "with9{equals}%(with8)s\n"
00744             "with8{equals}%(With7)s\n"
00745             "with7{equals}%(WITH6)s\n"
00746             "with6{equals}%(with5)s\n"
00747             "With5{equals}%(with4)s\n"
00748             "WITH4{equals}%(with3)s\n"
00749             "with3{equals}%(with2)s\n"
00750             "with2{equals}%(with1)s\n"
00751             "with1{equals}with\n"
00752             "\n"
00753             "[Mutual Recursion]\n"
00754             "foo{equals}%(bar)s\n"
00755             "bar{equals}%(foo)s\n"
00756             "\n"
00757             "[Interpolation Error]\n"
00758             # no definition for 'reference'
00759             "name{equals}%(reference)s\n".format(equals=self.delimiters[0]))

Here is the call graph for this function:

Here is the caller graph for this function:

def test.test_cfgparser.CfgParserTestCaseClass.newconfig (   self,
  defaults = None 
) [inherited]

Definition at line 46 of file test_cfgparser.py.

00046 
00047     def newconfig(self, defaults=None):
00048         arguments = dict(
00049             defaults=defaults,
00050             allow_no_value=self.allow_no_value,
00051             delimiters=self.delimiters,
00052             comment_prefixes=self.comment_prefixes,
00053             inline_comment_prefixes=self.inline_comment_prefixes,
00054             empty_lines_in_values=self.empty_lines_in_values,
00055             dict_type=self.dict_type,
00056             strict=self.strict,
00057             default_section=self.default_section,
00058             interpolation=self.interpolation,
00059         )
00060         instance = self.config_class(**arguments)
00061         return instance

Here is the caller graph for this function:

def test.test_cfgparser.BasicTestCase.parse_error (   self,
  cf,
  exc,
  src 
) [inherited]

Definition at line 549 of file test_cfgparser.py.

00549 
00550     def parse_error(self, cf, exc, src):
00551         if hasattr(src, 'readline'):
00552             sio = src
00553         else:
00554             sio = io.StringIO(src)
00555         with self.assertRaises(exc) as cm:
00556             cf.read_file(sio)
00557         return cm.exception

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 291 of file test_cfgparser.py.

00291 
00292     def test_basic(self):
00293         config_string = """\
00294 [Foo Bar]
00295 foo{0[0]}bar1
00296 [Spacey Bar]
00297 foo {0[0]} bar2
00298 [Spacey Bar From The Beginning]
00299   foo {0[0]} bar3
00300   baz {0[0]} qwe
00301 [Commented Bar]
00302 foo{0[1]} bar4 {1[1]} comment
00303 baz{0[0]}qwe {1[0]}another one
00304 [Long Line]
00305 foo{0[1]} this line is much, much longer than my editor
00306    likes it.
00307 [Section\\with$weird%characters[\t]
00308 [Internationalized Stuff]
00309 foo[bg]{0[1]} Bulgarian
00310 foo{0[0]}Default
00311 foo[en]{0[0]}English
00312 foo[de]{0[0]}Deutsch
00313 [Spaces]
00314 key with spaces {0[1]} value
00315 another with spaces {0[0]} splat!
00316 [Types]
00317 int {0[1]} 42
00318 float {0[0]} 0.44
00319 boolean {0[0]} NO
00320 123 {0[1]} strange but acceptable
00321 """.format(self.delimiters, self.comment_prefixes)
00322         if self.allow_no_value:
00323             config_string += (
00324                 "[NoValue]\n"
00325                 "option-without-value\n"
00326                 )
00327         cf = self.fromstring(config_string)
00328         self.basic_test(cf)
00329         if self.strict:
00330             with self.assertRaises(configparser.DuplicateOptionError):
00331                 cf.read_string(textwrap.dedent("""\
00332                     [Duplicate Options Here]
00333                     option {0[0]} with a value
00334                     option {0[1]} with another value
00335                 """.format(self.delimiters)))
00336             with self.assertRaises(configparser.DuplicateSectionError):
00337                 cf.read_string(textwrap.dedent("""\
00338                     [And Now For Something]
00339                     completely different {0[0]} True
00340                     [And Now For Something]
00341                     the larch {0[1]} 1
00342                 """.format(self.delimiters)))
00343         else:
00344             cf.read_string(textwrap.dedent("""\
00345                 [Duplicate Options Here]
00346                 option {0[0]} with a value
00347                 option {0[1]} with another value
00348             """.format(self.delimiters)))
00349 
00350             cf.read_string(textwrap.dedent("""\
00351                 [And Now For Something]
00352                 completely different {0[0]} True
00353                 [And Now For Something]
00354                 the larch {0[1]} 1
00355             """.format(self.delimiters)))

Here is the call graph for this function:

Definition at line 356 of file test_cfgparser.py.

00356 
00357     def test_basic_from_dict(self):
00358         config = {
00359             "Foo Bar": {
00360                 "foo": "bar1",
00361             },
00362             "Spacey Bar": {
00363                 "foo": "bar2",
00364             },
00365             "Spacey Bar From The Beginning": {
00366                 "foo": "bar3",
00367                 "baz": "qwe",
00368             },
00369             "Commented Bar": {
00370                 "foo": "bar4",
00371                 "baz": "qwe",
00372             },
00373             "Long Line": {
00374                 "foo": "this line is much, much longer than my editor\nlikes "
00375                        "it.",
00376             },
00377             "Section\\with$weird%characters[\t": {
00378             },
00379             "Internationalized Stuff": {
00380                 "foo[bg]": "Bulgarian",
00381                 "foo": "Default",
00382                 "foo[en]": "English",
00383                 "foo[de]": "Deutsch",
00384             },
00385             "Spaces": {
00386                 "key with spaces": "value",
00387                 "another with spaces": "splat!",
00388             },
00389             "Types": {
00390                 "int": 42,
00391                 "float": 0.44,
00392                 "boolean": False,
00393                 123: "strange but acceptable",
00394             },
00395         }
00396         if self.allow_no_value:
00397             config.update({
00398                 "NoValue": {
00399                     "option-without-value": None,
00400                 }
00401             })
00402         cf = self.newconfig()
00403         cf.read_dict(config)
00404         self.basic_test(cf)
00405         if self.strict:
00406             with self.assertRaises(configparser.DuplicateSectionError):
00407                 cf.read_dict({
00408                     '1': {'key': 'value'},
00409                     1: {'key2': 'value2'},
00410                 })
00411             with self.assertRaises(configparser.DuplicateOptionError):
00412                 cf.read_dict({
00413                     "Duplicate Options Here": {
00414                         'option': 'with a value',
00415                         'OPTION': 'with another value',
00416                     },
00417                 })
00418         else:
00419             cf.read_dict({
00420                 'section': {'key': 'value'},
00421                 'SECTION': {'key2': 'value2'},
00422             })
00423             cf.read_dict({
00424                 "Duplicate Options Here": {
00425                     'option': 'with a value',
00426                     'OPTION': 'with another value',
00427                 },
00428             })

Here is the call graph for this function:

Definition at line 584 of file test_cfgparser.py.

00584 
00585     def test_boolean(self):
00586         cf = self.fromstring(
00587             "[BOOLTEST]\n"
00588             "T1{equals}1\n"
00589             "T2{equals}TRUE\n"
00590             "T3{equals}True\n"
00591             "T4{equals}oN\n"
00592             "T5{equals}yes\n"
00593             "F1{equals}0\n"
00594             "F2{equals}FALSE\n"
00595             "F3{equals}False\n"
00596             "F4{equals}oFF\n"
00597             "F5{equals}nO\n"
00598             "E1{equals}2\n"
00599             "E2{equals}foo\n"
00600             "E3{equals}-1\n"
00601             "E4{equals}0.1\n"
00602             "E5{equals}FALSE AND MORE".format(equals=self.delimiters[0])
00603             )
00604         for x in range(1, 5):
00605             self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))
00606             self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x))
00607             self.assertRaises(ValueError,
00608                               cf.getboolean, 'BOOLTEST', 'e%d' % x)

Here is the call graph for this function:

Definition at line 429 of file test_cfgparser.py.

00429 
00430     def test_case_sensitivity(self):
00431         cf = self.newconfig()
00432         cf.add_section("A")
00433         cf.add_section("a")
00434         cf.add_section("B")
00435         L = cf.sections()
00436         L.sort()
00437         eq = self.assertEqual
00438         eq(L, ["A", "B", "a"])
00439         cf.set("a", "B", "value")
00440         eq(cf.options("a"), ["b"])
00441         eq(cf.get("a", "b"), "value",
00442            "could not locate option, expecting case-insensitive option names")
00443         with self.assertRaises(configparser.NoSectionError):
00444             # section names are case-sensitive
00445             cf.set("b", "A", "value")
00446         self.assertTrue(cf.has_option("a", "b"))
00447         self.assertFalse(cf.has_option("b", "b"))
00448         cf.set("A", "A-B", "A-B value")
00449         for opt in ("a-b", "A-b", "a-B", "A-B"):
00450             self.assertTrue(
00451                 cf.has_option("A", opt),
00452                 "has_option() returned false for option which should exist")
00453         eq(cf.options("A"), ["a-b"])
00454         eq(cf.options("a"), ["b"])
00455         cf.remove_option("a", "B")
00456         eq(cf.options("a"), [])
00457 
00458         # SF bug #432369:
00459         cf = self.fromstring(
00460             "[MySection]\nOption{} first line   \n\tsecond line   \n".format(
00461                 self.delimiters[0]))
00462         eq(cf.options("MySection"), ["option"])
00463         eq(cf.get("MySection", "Option"), "first line\nsecond line")
00464 
00465         # SF bug #561822:
00466         cf = self.fromstring("[section]\n"
00467                              "nekey{}nevalue\n".format(self.delimiters[0]),
00468                              defaults={"key":"value"})
00469         self.assertTrue(cf.has_option("section", "Key"))
00470 

Here is the call graph for this function:

Definition at line 471 of file test_cfgparser.py.

00471 
00472     def test_case_sensitivity_mapping_access(self):
00473         cf = self.newconfig()
00474         cf["A"] = {}
00475         cf["a"] = {"B": "value"}
00476         cf["B"] = {}
00477         L = [section for section in cf]
00478         L.sort()
00479         eq = self.assertEqual
00480         elem_eq = self.assertCountEqual
00481         eq(L, sorted(["A", "B", self.default_section, "a"]))
00482         eq(cf["a"].keys(), {"b"})
00483         eq(cf["a"]["b"], "value",
00484            "could not locate option, expecting case-insensitive option names")
00485         with self.assertRaises(KeyError):
00486             # section names are case-sensitive
00487             cf["b"]["A"] = "value"
00488         self.assertTrue("b" in cf["a"])
00489         cf["A"]["A-B"] = "A-B value"
00490         for opt in ("a-b", "A-b", "a-B", "A-B"):
00491             self.assertTrue(
00492                 opt in cf["A"],
00493                 "has_option() returned false for option which should exist")
00494         eq(cf["A"].keys(), {"a-b"})
00495         eq(cf["a"].keys(), {"b"})
00496         del cf["a"]["B"]
00497         elem_eq(cf["a"].keys(), {})
00498 
00499         # SF bug #432369:
00500         cf = self.fromstring(
00501             "[MySection]\nOption{} first line   \n\tsecond line   \n".format(
00502                 self.delimiters[0]))
00503         eq(cf["MySection"].keys(), {"option"})
00504         eq(cf["MySection"]["Option"], "first line\nsecond line")
00505 
00506         # SF bug #561822:
00507         cf = self.fromstring("[section]\n"
00508                              "nekey{}nevalue\n".format(self.delimiters[0]),
00509                              defaults={"key":"value"})
00510         self.assertTrue("Key" in cf["section"])

Here is the call graph for this function:

Definition at line 511 of file test_cfgparser.py.

00511 
00512     def test_default_case_sensitivity(self):
00513         cf = self.newconfig({"foo": "Bar"})
00514         self.assertEqual(
00515             cf.get(self.default_section, "Foo"), "Bar",
00516             "could not locate option, expecting case-insensitive option names")
00517         cf = self.newconfig({"Foo": "Bar"})
00518         self.assertEqual(
00519             cf.get(self.default_section, "Foo"), "Bar",
00520             "could not locate option, expecting case-insensitive defaults")

Here is the call graph for this function:

Definition at line 964 of file test_cfgparser.py.

00964 
00965     def test_interpolation(self):
00966         cf = self.get_interpolation_config()
00967         eq = self.assertEqual
00968         eq(cf.get("Foo", "bar"),
00969            "something %(with1)s interpolation (1 step)")
00970         eq(cf.get("Foo", "bar9"),
00971            "something %(with9)s lots of interpolation (9 steps)")
00972         eq(cf.get("Foo", "bar10"),
00973            "something %(with10)s lots of interpolation (10 steps)")
00974         eq(cf.get("Foo", "bar11"),
00975            "something %(with11)s lots of interpolation (11 steps)")

Here is the call graph for this function:

Definition at line 976 of file test_cfgparser.py.

00976 
00977     def test_items(self):
00978         self.check_items_config([('default', '<default>'),
00979                                  ('getdefault', '|%(default)s|'),
00980                                  ('key', '|%(name)s|'),
00981                                  ('name', '%(value)s'),
00982                                  ('value', 'value')])

Here is the call graph for this function:

Definition at line 521 of file test_cfgparser.py.

00521 
00522     def test_parse_errors(self):
00523         cf = self.newconfig()
00524         self.parse_error(cf, configparser.ParsingError,
00525                          "[Foo]\n"
00526                          "{}val-without-opt-name\n".format(self.delimiters[0]))
00527         self.parse_error(cf, configparser.ParsingError,
00528                          "[Foo]\n"
00529                          "{}val-without-opt-name\n".format(self.delimiters[1]))
00530         e = self.parse_error(cf, configparser.MissingSectionHeaderError,
00531                              "No Section!\n")
00532         self.assertEqual(e.args, ('<???>', 1, "No Section!\n"))
00533         if not self.allow_no_value:
00534             e = self.parse_error(cf, configparser.ParsingError,
00535                                 "[Foo]\n  wrong-indent\n")
00536             self.assertEqual(e.args, ('<???>',))
00537             # read_file on a real file
00538             tricky = support.findfile("cfgparser.3")
00539             if self.delimiters[0] == '=':
00540                 error = configparser.ParsingError
00541                 expected = (tricky,)
00542             else:
00543                 error = configparser.MissingSectionHeaderError
00544                 expected = (tricky, 1,
00545                             '  # INI with as many tricky parts as possible\n')
00546             with open(tricky, encoding='utf-8') as f:
00547                 e = self.parse_error(cf, error, f)
00548             self.assertEqual(e.args, expected)

Here is the call graph for this function:

Definition at line 558 of file test_cfgparser.py.

00558 
00559     def test_query_errors(self):
00560         cf = self.newconfig()
00561         self.assertEqual(cf.sections(), [],
00562                          "new ConfigParser should have no defined sections")
00563         self.assertFalse(cf.has_section("Foo"),
00564                          "new ConfigParser should have no acknowledged "
00565                          "sections")
00566         with self.assertRaises(configparser.NoSectionError):
00567             cf.options("Foo")
00568         with self.assertRaises(configparser.NoSectionError):
00569             cf.set("foo", "bar", "value")
00570         e = self.get_error(cf, configparser.NoSectionError, "foo", "bar")
00571         self.assertEqual(e.args, ("foo",))
00572         cf.add_section("foo")
00573         e = self.get_error(cf, configparser.NoOptionError, "foo", "bar")
00574         self.assertEqual(e.args, ("bar", "foo"))

Here is the call graph for this function:

Definition at line 708 of file test_cfgparser.py.

00708 
00709     def test_read_returns_file_list(self):
00710         if self.delimiters[0] != '=':
00711             # skip reading the file if we're using an incompatible format
00712             return
00713         file1 = support.findfile("cfgparser.1")
00714         # check when we pass a mix of readable and non-readable files:
00715         cf = self.newconfig()
00716         parsed_files = cf.read([file1, "nonexistent-file"])
00717         self.assertEqual(parsed_files, [file1])
00718         self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
00719         # check when we pass only a filename:
00720         cf = self.newconfig()
00721         parsed_files = cf.read(file1)
00722         self.assertEqual(parsed_files, [file1])
00723         self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
00724         # check when we pass only missing files:
00725         cf = self.newconfig()
00726         parsed_files = cf.read(["nonexistent-file"])
00727         self.assertEqual(parsed_files, [])
00728         # check when we pass no files:
00729         cf = self.newconfig()
00730         parsed_files = cf.read([])
00731         self.assertEqual(parsed_files, [])

Here is the call graph for this function:

Definition at line 983 of file test_cfgparser.py.

00983 
00984     def test_set_nonstring_types(self):
00985         cf = self.newconfig()
00986         cf.add_section('non-string')
00987         cf.set('non-string', 'int', 1)
00988         cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13])
00989         cf.set('non-string', 'dict', {'pi': 3.14159})
00990         self.assertEqual(cf.get('non-string', 'int'), 1)
00991         self.assertEqual(cf.get('non-string', 'list'),
00992                          [0, 1, 1, 2, 3, 5, 8, 13])
00993         self.assertEqual(cf.get('non-string', 'dict'), {'pi': 3.14159})
00994         cf.add_section(123)
00995         cf.set(123, 'this is sick', True)
00996         self.assertEqual(cf.get(123, 'this is sick'), True)
00997         if cf._dict is configparser._default_dict:
00998             # would not work for SortedDict; only checking for the most common
00999             # default dictionary (OrderedDict)
01000             cf.optionxform = lambda x: x
01001             cf.set('non-string', 1, 1)
01002             self.assertEqual(cf.get('non-string', 1), 1)

Here is the call graph for this function:

Definition at line 694 of file test_cfgparser.py.

00694 
00695     def test_set_string_types(self):
00696         cf = self.fromstring("[sect]\n"
00697                              "option1{eq}foo\n".format(eq=self.delimiters[0]))
00698         # Check that we don't get an exception when setting values in
00699         # an existing section using strings:
00700         class mystr(str):
00701             pass
00702         cf.set("sect", "option1", "splat")
00703         cf.set("sect", "option1", mystr("splat"))
00704         cf.set("sect", "option2", "splat")
00705         cf.set("sect", "option2", mystr("splat"))
00706         cf.set("sect", "option1", "splat")
00707         cf.set("sect", "option2", "splat")

Here is the call graph for this function:

Definition at line 1279 of file test_cfgparser.py.

01279 
01280     def test_sorted(self):
01281         cf = self.fromstring("[b]\n"
01282                              "o4=1\n"
01283                              "o3=2\n"
01284                              "o2=3\n"
01285                              "o1=4\n"
01286                              "[a]\n"
01287                              "k=v\n")
01288         output = io.StringIO()
01289         cf.write(output)
01290         self.assertEqual(output.getvalue(),
01291                          "[a]\n"
01292                          "k = v\n\n"
01293                          "[b]\n"
01294                          "o1 = 4\n"
01295                          "o2 = 3\n"
01296                          "o3 = 2\n"
01297                          "o4 = 1\n\n")
01298 

Here is the call graph for this function:

Definition at line 609 of file test_cfgparser.py.

00609 
00610     def test_weird_errors(self):
00611         cf = self.newconfig()
00612         cf.add_section("Foo")
00613         with self.assertRaises(configparser.DuplicateSectionError) as cm:
00614             cf.add_section("Foo")
00615         e = cm.exception
00616         self.assertEqual(str(e), "Section 'Foo' already exists")
00617         self.assertEqual(e.args, ("Foo", None, None))
00618 
00619         if self.strict:
00620             with self.assertRaises(configparser.DuplicateSectionError) as cm:
00621                 cf.read_string(textwrap.dedent("""\
00622                     [Foo]
00623                     will this be added{equals}True
00624                     [Bar]
00625                     what about this{equals}True
00626                     [Foo]
00627                     oops{equals}this won't
00628                 """.format(equals=self.delimiters[0])), source='<foo-bar>')
00629             e = cm.exception
00630             self.assertEqual(str(e), "While reading from <foo-bar> [line  5]: "
00631                                      "section 'Foo' already exists")
00632             self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))
00633 
00634             with self.assertRaises(configparser.DuplicateOptionError) as cm:
00635                 cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
00636             e = cm.exception
00637             self.assertEqual(str(e), "While reading from <dict>: option 'opt' "
00638                                      "in section 'Bar' already exists")
00639             self.assertEqual(e.args, ("Bar", "opt", "<dict>", None))

Here is the call graph for this function:

Definition at line 640 of file test_cfgparser.py.

00640 
00641     def test_write(self):
00642         config_string = (
00643             "[Long Line]\n"
00644             "foo{0[0]} this line is much, much longer than my editor\n"
00645             "   likes it.\n"
00646             "[{default_section}]\n"
00647             "foo{0[1]} another very\n"
00648             " long line\n"
00649             "[Long Line - With Comments!]\n"
00650             "test {0[1]} we        {comment} can\n"
00651             "            also      {comment} place\n"
00652             "            comments  {comment} in\n"
00653             "            multiline {comment} values"
00654             "\n".format(self.delimiters, comment=self.comment_prefixes[0],
00655                         default_section=self.default_section)
00656             )
00657         if self.allow_no_value:
00658             config_string += (
00659             "[Valueless]\n"
00660             "option-without-value\n"
00661             )
00662 
00663         cf = self.fromstring(config_string)
00664         for space_around_delimiters in (True, False):
00665             output = io.StringIO()
00666             cf.write(output, space_around_delimiters=space_around_delimiters)
00667             delimiter = self.delimiters[0]
00668             if space_around_delimiters:
00669                 delimiter = " {} ".format(delimiter)
00670             expect_string = (
00671                 "[{default_section}]\n"
00672                 "foo{equals}another very\n"
00673                 "\tlong line\n"
00674                 "\n"
00675                 "[Long Line]\n"
00676                 "foo{equals}this line is much, much longer than my editor\n"
00677                 "\tlikes it.\n"
00678                 "\n"
00679                 "[Long Line - With Comments!]\n"
00680                 "test{equals}we\n"
00681                 "\talso\n"
00682                 "\tcomments\n"
00683                 "\tmultiline\n"
00684                 "\n".format(equals=delimiter,
00685                             default_section=self.default_section)
00686                 )
00687             if self.allow_no_value:
00688                 expect_string += (
00689                     "[Valueless]\n"
00690                     "option-without-value\n"
00691                     "\n"
00692                     )
00693             self.assertEqual(output.getvalue(), expect_string)

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

tuple test.test_cfgparser.CfgParserTestCaseClass.comment_prefixes = (';', '#') [static, inherited]

Definition at line 962 of file test_cfgparser.py.

tuple test.test_cfgparser.CfgParserTestCaseClass.delimiters = ('=', ':') [static, inherited]

Reimplemented from test.test_cfgparser.CfgParserTestCaseClass.

Definition at line 1277 of file test_cfgparser.py.

Reimplemented in test.test_cfgparser.RawConfigParserTestSambaConf.

Definition at line 40 of file test_cfgparser.py.


The documentation for this class was generated from the following file: