Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/test/test_cfgparser.py

    r2 r391  
    11import ConfigParser
    22import StringIO
     3import os
    34import unittest
    45import UserDict
    56
    67from test import test_support
     8
    79
    810class SortedDict(UserDict.UserDict):
     
    2729    def itervalues(self): return iter(self.values())
    2830
     31
    2932class TestCaseBase(unittest.TestCase):
     33    allow_no_value = False
     34
    3035    def newconfig(self, defaults=None):
    3136        if defaults is None:
    32             self.cf = self.config_class()
     37            self.cf = self.config_class(allow_no_value=self.allow_no_value)
    3338        else:
    34             self.cf = self.config_class(defaults)
     39            self.cf = self.config_class(defaults,
     40                                        allow_no_value=self.allow_no_value)
    3541        return self.cf
    3642
     
    4248
    4349    def test_basic(self):
    44         cf = self.fromstring(
     50        config_string = (
    4551            "[Foo Bar]\n"
    4652            "foo=bar\n"
     
    6268            "another with spaces = splat!\n"
    6369            )
     70        if self.allow_no_value:
     71            config_string += (
     72                "[NoValue]\n"
     73                "option-without-value\n"
     74                )
     75
     76        cf = self.fromstring(config_string)
    6477        L = cf.sections()
    6578        L.sort()
     79        E = [r'Commented Bar',
     80             r'Foo Bar',
     81             r'Internationalized Stuff',
     82             r'Long Line',
     83             r'Section\with$weird%characters[' '\t',
     84             r'Spaces',
     85             r'Spacey Bar',
     86             ]
     87        if self.allow_no_value:
     88            E.append(r'NoValue')
     89        E.sort()
    6690        eq = self.assertEqual
    67         eq(L, [r'Commented Bar',
    68                r'Foo Bar',
    69                r'Internationalized Stuff',
    70                r'Long Line',
    71                r'Section\with$weird%characters[' '\t',
    72                r'Spaces',
    73                r'Spacey Bar',
    74                ])
     91        eq(L, E)
    7592
    7693        # The use of spaces in the section names serves as a
     
    8299        eq(cf.get('Spaces', 'key with spaces'), 'value')
    83100        eq(cf.get('Spaces', 'another with spaces'), 'splat!')
    84 
    85         self.failIf('__name__' in cf.options("Foo Bar"),
    86                     '__name__ "option" should not be exposed by the API!')
     101        if self.allow_no_value:
     102            eq(cf.get('NoValue', 'option-without-value'), None)
     103
     104        self.assertNotIn('__name__', cf.options("Foo Bar"),
     105                         '__name__ "option" should not be exposed by the API!')
    87106
    88107        # Make sure the right things happen for remove_option();
    89108        # added to include check for SourceForge bug #123324:
    90         self.failUnless(cf.remove_option('Foo Bar', 'foo'),
     109        self.assertTrue(cf.remove_option('Foo Bar', 'foo'),
    91110                        "remove_option() failed to report existence of option")
    92         self.failIf(cf.has_option('Foo Bar', 'foo'),
     111        self.assertFalse(cf.has_option('Foo Bar', 'foo'),
    93112                    "remove_option() failed to remove option")
    94         self.failIf(cf.remove_option('Foo Bar', 'foo'),
     113        self.assertFalse(cf.remove_option('Foo Bar', 'foo'),
    95114                    "remove_option() failed to report non-existence of option"
    96115                    " that was removed")
     
    114133        eq(cf.get("a", "b"), "value",
    115134           "could not locate option, expecting case-insensitive option names")
    116         self.failUnless(cf.has_option("a", "b"))
     135        self.assertTrue(cf.has_option("a", "b"))
    117136        cf.set("A", "A-B", "A-B value")
    118137        for opt in ("a-b", "A-b", "a-B", "A-B"):
    119             self.failUnless(
     138            self.assertTrue(
    120139                cf.has_option("A", opt),
    121140                "has_option() returned false for option which should exist")
     
    134153        cf = self.fromstring("[section]\nnekey=nevalue\n",
    135154                             defaults={"key":"value"})
    136         self.failUnless(cf.has_option("section", "Key"))
     155        self.assertTrue(cf.has_option("section", "Key"))
    137156
    138157
     
    154173                         "[Foo]\n  extra-spaces= splat\n")
    155174        self.parse_error(ConfigParser.ParsingError,
    156                          "[Foo]\noption-without-value\n")
    157         self.parse_error(ConfigParser.ParsingError,
    158175                         "[Foo]\n:value-without-option-name\n")
    159176        self.parse_error(ConfigParser.ParsingError,
     
    170187        self.assertEqual(cf.sections(), [],
    171188                         "new ConfigParser should have no defined sections")
    172         self.failIf(cf.has_section("Foo"),
    173                     "new ConfigParser should have no acknowledged sections")
     189        self.assertFalse(cf.has_section("Foo"),
     190                         "new ConfigParser should have no acknowledged "
     191                         "sections")
    174192        self.assertRaises(ConfigParser.NoSectionError,
    175193                          cf.options, "Foo")
     
    209227            )
    210228        for x in range(1, 5):
    211             self.failUnless(cf.getboolean('BOOLTEST', 't%d' % x))
    212             self.failIf(cf.getboolean('BOOLTEST', 'f%d' % x))
     229            self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))
     230            self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x))
    213231            self.assertRaises(ValueError,
    214232                              cf.getboolean, 'BOOLTEST', 'e%d' % x)
     
    221239
    222240    def test_write(self):
    223         cf = self.fromstring(
     241        config_string = (
    224242            "[Long Line]\n"
    225243            "foo: this line is much, much longer than my editor\n"
     
    227245            "[DEFAULT]\n"
    228246            "foo: another very\n"
    229             " long line"
     247            " long line\n"
    230248            )
     249        if self.allow_no_value:
     250            config_string += (
     251            "[Valueless]\n"
     252            "option-without-value\n"
     253            )
     254
     255        cf = self.fromstring(config_string)
    231256        output = StringIO.StringIO()
    232257        cf.write(output)
    233         self.assertEqual(
    234             output.getvalue(),
     258        expect_string = (
    235259            "[DEFAULT]\n"
    236260            "foo = another very\n"
     
    242266            "\n"
    243267            )
     268        if self.allow_no_value:
     269            expect_string += (
     270                "[Valueless]\n"
     271                "option-without-value\n"
     272                "\n"
     273                )
     274        self.assertEqual(output.getvalue(), expect_string)
    244275
    245276    def test_set_string_types(self):
     
    327358class ConfigParserTestCase(TestCaseBase):
    328359    config_class = ConfigParser.ConfigParser
     360    allow_no_value = True
    329361
    330362    def test_interpolation(self):
     363        rawval = {
     364            ConfigParser.ConfigParser: ("something %(with11)s "
     365                                        "lots of interpolation (11 steps)"),
     366            ConfigParser.SafeConfigParser: "%(with1)s",
     367        }
    331368        cf = self.get_interpolation_config()
    332369        eq = self.assertEqual
     
    340377
    341378    def test_interpolation_missing_value(self):
    342         cf = self.get_interpolation_config()
     379        self.get_interpolation_config()
    343380        e = self.get_error(ConfigParser.InterpolationError,
    344381                           "Interpolation Error", "name")
     
    362399                                      '%(list)': '%(list)'})
    363400        cf.set('non-string', 'string_with_interpolation', '%(list)s')
     401        cf.set('non-string', 'no-value')
    364402        self.assertEqual(cf.get('non-string', 'int', raw=True), 1)
    365403        self.assertRaises(TypeError, cf.get, 'non-string', 'int')
     
    374412        self.assertRaises(ValueError, cf.get, 'non-string',
    375413                          'string_with_interpolation', raw=False)
    376 
     414        self.assertEqual(cf.get('non-string', 'no-value'), None)
     415
     416class MultilineValuesTestCase(TestCaseBase):
     417    config_class = ConfigParser.ConfigParser
     418    wonderful_spam = ("I'm having spam spam spam spam "
     419                      "spam spam spam beaked beans spam "
     420                      "spam spam and spam!").replace(' ', '\t\n')
     421
     422    def setUp(self):
     423        cf = self.newconfig()
     424        for i in range(100):
     425            s = 'section{}'.format(i)
     426            cf.add_section(s)
     427            for j in range(10):
     428                cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)
     429        with open(test_support.TESTFN, 'w') as f:
     430            cf.write(f)
     431
     432    def tearDown(self):
     433        os.unlink(test_support.TESTFN)
     434
     435    def test_dominating_multiline_values(self):
     436        # we're reading from file because this is where the code changed
     437        # during performance updates in Python 3.2
     438        cf_from_file = self.newconfig()
     439        with open(test_support.TESTFN) as f:
     440            cf_from_file.readfp(f)
     441        self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
     442                         self.wonderful_spam.replace('\t\n', '\n'))
    377443
    378444class RawConfigParserTestCase(TestCaseBase):
     
    460526        self.assertRaises(ValueError, cf.add_section, "DEFAULT")
    461527
     528
     529class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase):
     530    allow_no_value = True
     531
     532class TestChainMap(unittest.TestCase):
     533    def test_issue_12717(self):
     534        d1 = dict(red=1, green=2)
     535        d2 = dict(green=3, blue=4)
     536        dcomb = d2.copy()
     537        dcomb.update(d1)
     538        cm = ConfigParser._Chainmap(d1, d2)
     539        self.assertIsInstance(cm.keys(), list)
     540        self.assertEqual(set(cm.keys()), set(dcomb.keys()))      # keys()
     541        self.assertEqual(set(cm.values()), set(dcomb.values()))  # values()
     542        self.assertEqual(set(cm.items()), set(dcomb.items()))    # items()
     543        self.assertEqual(set(cm), set(dcomb))                    # __iter__ ()
     544        self.assertEqual(cm, dcomb)                              # __eq__()
     545        self.assertEqual([cm[k] for k in dcomb], dcomb.values()) # __getitem__()
     546        klist = 'red green blue black brown'.split()
     547        self.assertEqual([cm.get(k, 10) for k in klist],
     548                         [dcomb.get(k, 10) for k in klist])      # get()
     549        self.assertEqual([k in cm for k in klist],
     550                         [k in dcomb for k in klist])            # __contains__()
     551        with test_support.check_py3k_warnings():
     552            self.assertEqual([cm.has_key(k) for k in klist],
     553                             [dcomb.has_key(k) for k in klist])  # has_key()
     554
     555class Issue7005TestCase(unittest.TestCase):
     556    """Test output when None is set() as a value and allow_no_value == False.
     557
     558    http://bugs.python.org/issue7005
     559
     560    """
     561
     562    expected_output = "[section]\noption = None\n\n"
     563
     564    def prepare(self, config_class):
     565        # This is the default, but that's the point.
     566        cp = config_class(allow_no_value=False)
     567        cp.add_section("section")
     568        cp.set("section", "option", None)
     569        sio = StringIO.StringIO()
     570        cp.write(sio)
     571        return sio.getvalue()
     572
     573    def test_none_as_value_stringified(self):
     574        output = self.prepare(ConfigParser.ConfigParser)
     575        self.assertEqual(output, self.expected_output)
     576
     577    def test_none_as_value_stringified_raw(self):
     578        output = self.prepare(ConfigParser.RawConfigParser)
     579        self.assertEqual(output, self.expected_output)
     580
     581
    462582class SortedTestCase(RawConfigParserTestCase):
    463583    def newconfig(self, defaults=None):
     
    475595        output = StringIO.StringIO()
    476596        self.cf.write(output)
    477         self.assertEquals(output.getvalue(),
    478                           "[a]\n"
    479                           "k = v\n\n"
    480                           "[b]\n"
    481                           "o1 = 4\n"
    482                           "o2 = 3\n"
    483                           "o3 = 2\n"
    484                           "o4 = 1\n\n")
     597        self.assertEqual(output.getvalue(),
     598                         "[a]\n"
     599                         "k = v\n\n"
     600                         "[b]\n"
     601                         "o1 = 4\n"
     602                         "o2 = 3\n"
     603                         "o3 = 2\n"
     604                         "o4 = 1\n\n")
     605
     606
     607class ExceptionPicklingTestCase(unittest.TestCase):
     608    """Tests for issue #13760: ConfigParser exceptions are not picklable."""
     609
     610    def test_error(self):
     611        import pickle
     612        e1 = ConfigParser.Error('value')
     613        pickled = pickle.dumps(e1)
     614        e2 = pickle.loads(pickled)
     615        self.assertEqual(e1.message, e2.message)
     616        self.assertEqual(repr(e1), repr(e2))
     617
     618    def test_nosectionerror(self):
     619        import pickle
     620        e1 = ConfigParser.NoSectionError('section')
     621        pickled = pickle.dumps(e1)
     622        e2 = pickle.loads(pickled)
     623        self.assertEqual(e1.message, e2.message)
     624        self.assertEqual(e1.args, e2.args)
     625        self.assertEqual(e1.section, e2.section)
     626        self.assertEqual(repr(e1), repr(e2))
     627
     628    def test_nooptionerror(self):
     629        import pickle
     630        e1 = ConfigParser.NoOptionError('option', 'section')
     631        pickled = pickle.dumps(e1)
     632        e2 = pickle.loads(pickled)
     633        self.assertEqual(e1.message, e2.message)
     634        self.assertEqual(e1.args, e2.args)
     635        self.assertEqual(e1.section, e2.section)
     636        self.assertEqual(e1.option, e2.option)
     637        self.assertEqual(repr(e1), repr(e2))
     638
     639    def test_duplicatesectionerror(self):
     640        import pickle
     641        e1 = ConfigParser.DuplicateSectionError('section')
     642        pickled = pickle.dumps(e1)
     643        e2 = pickle.loads(pickled)
     644        self.assertEqual(e1.message, e2.message)
     645        self.assertEqual(e1.args, e2.args)
     646        self.assertEqual(e1.section, e2.section)
     647        self.assertEqual(repr(e1), repr(e2))
     648
     649    def test_interpolationerror(self):
     650        import pickle
     651        e1 = ConfigParser.InterpolationError('option', 'section', 'msg')
     652        pickled = pickle.dumps(e1)
     653        e2 = pickle.loads(pickled)
     654        self.assertEqual(e1.message, e2.message)
     655        self.assertEqual(e1.args, e2.args)
     656        self.assertEqual(e1.section, e2.section)
     657        self.assertEqual(e1.option, e2.option)
     658        self.assertEqual(repr(e1), repr(e2))
     659
     660    def test_interpolationmissingoptionerror(self):
     661        import pickle
     662        e1 = ConfigParser.InterpolationMissingOptionError('option', 'section',
     663            'rawval', 'reference')
     664        pickled = pickle.dumps(e1)
     665        e2 = pickle.loads(pickled)
     666        self.assertEqual(e1.message, e2.message)
     667        self.assertEqual(e1.args, e2.args)
     668        self.assertEqual(e1.section, e2.section)
     669        self.assertEqual(e1.option, e2.option)
     670        self.assertEqual(e1.reference, e2.reference)
     671        self.assertEqual(repr(e1), repr(e2))
     672
     673    def test_interpolationsyntaxerror(self):
     674        import pickle
     675        e1 = ConfigParser.InterpolationSyntaxError('option', 'section', 'msg')
     676        pickled = pickle.dumps(e1)
     677        e2 = pickle.loads(pickled)
     678        self.assertEqual(e1.message, e2.message)
     679        self.assertEqual(e1.args, e2.args)
     680        self.assertEqual(e1.section, e2.section)
     681        self.assertEqual(e1.option, e2.option)
     682        self.assertEqual(repr(e1), repr(e2))
     683
     684    def test_interpolationdeptherror(self):
     685        import pickle
     686        e1 = ConfigParser.InterpolationDepthError('option', 'section',
     687            'rawval')
     688        pickled = pickle.dumps(e1)
     689        e2 = pickle.loads(pickled)
     690        self.assertEqual(e1.message, e2.message)
     691        self.assertEqual(e1.args, e2.args)
     692        self.assertEqual(e1.section, e2.section)
     693        self.assertEqual(e1.option, e2.option)
     694        self.assertEqual(repr(e1), repr(e2))
     695
     696    def test_parsingerror(self):
     697        import pickle
     698        e1 = ConfigParser.ParsingError('source')
     699        e1.append(1, 'line1')
     700        e1.append(2, 'line2')
     701        e1.append(3, 'line3')
     702        pickled = pickle.dumps(e1)
     703        e2 = pickle.loads(pickled)
     704        self.assertEqual(e1.message, e2.message)
     705        self.assertEqual(e1.args, e2.args)
     706        self.assertEqual(e1.filename, e2.filename)
     707        self.assertEqual(e1.errors, e2.errors)
     708        self.assertEqual(repr(e1), repr(e2))
     709
     710    def test_missingsectionheadererror(self):
     711        import pickle
     712        e1 = ConfigParser.MissingSectionHeaderError('filename', 123, 'line')
     713        pickled = pickle.dumps(e1)
     714        e2 = pickle.loads(pickled)
     715        self.assertEqual(e1.message, e2.message)
     716        self.assertEqual(e1.args, e2.args)
     717        self.assertEqual(e1.line, e2.line)
     718        self.assertEqual(e1.filename, e2.filename)
     719        self.assertEqual(e1.lineno, e2.lineno)
     720        self.assertEqual(repr(e1), repr(e2))
     721
    485722
    486723def test_main():
    487724    test_support.run_unittest(
    488725        ConfigParserTestCase,
     726        MultilineValuesTestCase,
    489727        RawConfigParserTestCase,
    490728        SafeConfigParserTestCase,
    491         SortedTestCase
    492     )
     729        SafeConfigParserTestCaseNoValue,
     730        SortedTestCase,
     731        Issue7005TestCase,
     732        TestChainMap,
     733        ExceptionPicklingTestCase,
     734        )
     735
    493736
    494737if __name__ == "__main__":
Note: See TracChangeset for help on using the changeset viewer.