+++ /dev/null
-import ConfigParser\r
-import StringIO\r
-import os\r
-import unittest\r
-import UserDict\r
-\r
-from test import test_support\r
-\r
-\r
-class SortedDict(UserDict.UserDict):\r
- def items(self):\r
- result = self.data.items()\r
- result.sort()\r
- return result\r
-\r
- def keys(self):\r
- result = self.data.keys()\r
- result.sort()\r
- return result\r
-\r
- def values(self):\r
- # XXX never used?\r
- result = self.items()\r
- return [i[1] for i in result]\r
-\r
- def iteritems(self): return iter(self.items())\r
- def iterkeys(self): return iter(self.keys())\r
- __iter__ = iterkeys\r
- def itervalues(self): return iter(self.values())\r
-\r
-\r
-class TestCaseBase(unittest.TestCase):\r
- allow_no_value = False\r
-\r
- def newconfig(self, defaults=None):\r
- if defaults is None:\r
- self.cf = self.config_class(allow_no_value=self.allow_no_value)\r
- else:\r
- self.cf = self.config_class(defaults,\r
- allow_no_value=self.allow_no_value)\r
- return self.cf\r
-\r
- def fromstring(self, string, defaults=None):\r
- cf = self.newconfig(defaults)\r
- sio = StringIO.StringIO(string)\r
- cf.readfp(sio)\r
- return cf\r
-\r
- def test_basic(self):\r
- config_string = (\r
- "[Foo Bar]\n"\r
- "foo=bar\n"\r
- "[Spacey Bar]\n"\r
- "foo = bar\n"\r
- "[Commented Bar]\n"\r
- "foo: bar ; comment\n"\r
- "[Long Line]\n"\r
- "foo: this line is much, much longer than my editor\n"\r
- " likes it.\n"\r
- "[Section\\with$weird%characters[\t]\n"\r
- "[Internationalized Stuff]\n"\r
- "foo[bg]: Bulgarian\n"\r
- "foo=Default\n"\r
- "foo[en]=English\n"\r
- "foo[de]=Deutsch\n"\r
- "[Spaces]\n"\r
- "key with spaces : value\n"\r
- "another with spaces = splat!\n"\r
- )\r
- if self.allow_no_value:\r
- config_string += (\r
- "[NoValue]\n"\r
- "option-without-value\n"\r
- )\r
-\r
- cf = self.fromstring(config_string)\r
- L = cf.sections()\r
- L.sort()\r
- E = [r'Commented Bar',\r
- r'Foo Bar',\r
- r'Internationalized Stuff',\r
- r'Long Line',\r
- r'Section\with$weird%characters[' '\t',\r
- r'Spaces',\r
- r'Spacey Bar',\r
- ]\r
- if self.allow_no_value:\r
- E.append(r'NoValue')\r
- E.sort()\r
- eq = self.assertEqual\r
- eq(L, E)\r
-\r
- # The use of spaces in the section names serves as a\r
- # regression test for SourceForge bug #583248:\r
- # http://www.python.org/sf/583248\r
- eq(cf.get('Foo Bar', 'foo'), 'bar')\r
- eq(cf.get('Spacey Bar', 'foo'), 'bar')\r
- eq(cf.get('Commented Bar', 'foo'), 'bar')\r
- eq(cf.get('Spaces', 'key with spaces'), 'value')\r
- eq(cf.get('Spaces', 'another with spaces'), 'splat!')\r
- if self.allow_no_value:\r
- eq(cf.get('NoValue', 'option-without-value'), None)\r
-\r
- self.assertNotIn('__name__', cf.options("Foo Bar"),\r
- '__name__ "option" should not be exposed by the API!')\r
-\r
- # Make sure the right things happen for remove_option();\r
- # added to include check for SourceForge bug #123324:\r
- self.assertTrue(cf.remove_option('Foo Bar', 'foo'),\r
- "remove_option() failed to report existence of option")\r
- self.assertFalse(cf.has_option('Foo Bar', 'foo'),\r
- "remove_option() failed to remove option")\r
- self.assertFalse(cf.remove_option('Foo Bar', 'foo'),\r
- "remove_option() failed to report non-existence of option"\r
- " that was removed")\r
-\r
- self.assertRaises(ConfigParser.NoSectionError,\r
- cf.remove_option, 'No Such Section', 'foo')\r
-\r
- eq(cf.get('Long Line', 'foo'),\r
- 'this line is much, much longer than my editor\nlikes it.')\r
-\r
- def test_case_sensitivity(self):\r
- cf = self.newconfig()\r
- cf.add_section("A")\r
- cf.add_section("a")\r
- L = cf.sections()\r
- L.sort()\r
- eq = self.assertEqual\r
- eq(L, ["A", "a"])\r
- cf.set("a", "B", "value")\r
- eq(cf.options("a"), ["b"])\r
- eq(cf.get("a", "b"), "value",\r
- "could not locate option, expecting case-insensitive option names")\r
- self.assertTrue(cf.has_option("a", "b"))\r
- cf.set("A", "A-B", "A-B value")\r
- for opt in ("a-b", "A-b", "a-B", "A-B"):\r
- self.assertTrue(\r
- cf.has_option("A", opt),\r
- "has_option() returned false for option which should exist")\r
- eq(cf.options("A"), ["a-b"])\r
- eq(cf.options("a"), ["b"])\r
- cf.remove_option("a", "B")\r
- eq(cf.options("a"), [])\r
-\r
- # SF bug #432369:\r
- cf = self.fromstring(\r
- "[MySection]\nOption: first line\n\tsecond line\n")\r
- eq(cf.options("MySection"), ["option"])\r
- eq(cf.get("MySection", "Option"), "first line\nsecond line")\r
-\r
- # SF bug #561822:\r
- cf = self.fromstring("[section]\nnekey=nevalue\n",\r
- defaults={"key":"value"})\r
- self.assertTrue(cf.has_option("section", "Key"))\r
-\r
-\r
- def test_default_case_sensitivity(self):\r
- cf = self.newconfig({"foo": "Bar"})\r
- self.assertEqual(\r
- cf.get("DEFAULT", "Foo"), "Bar",\r
- "could not locate option, expecting case-insensitive option names")\r
- cf = self.newconfig({"Foo": "Bar"})\r
- self.assertEqual(\r
- cf.get("DEFAULT", "Foo"), "Bar",\r
- "could not locate option, expecting case-insensitive defaults")\r
-\r
- def test_parse_errors(self):\r
- self.newconfig()\r
- self.parse_error(ConfigParser.ParsingError,\r
- "[Foo]\n extra-spaces: splat\n")\r
- self.parse_error(ConfigParser.ParsingError,\r
- "[Foo]\n extra-spaces= splat\n")\r
- self.parse_error(ConfigParser.ParsingError,\r
- "[Foo]\n:value-without-option-name\n")\r
- self.parse_error(ConfigParser.ParsingError,\r
- "[Foo]\n=value-without-option-name\n")\r
- self.parse_error(ConfigParser.MissingSectionHeaderError,\r
- "No Section!\n")\r
-\r
- def parse_error(self, exc, src):\r
- sio = StringIO.StringIO(src)\r
- self.assertRaises(exc, self.cf.readfp, sio)\r
-\r
- def test_query_errors(self):\r
- cf = self.newconfig()\r
- self.assertEqual(cf.sections(), [],\r
- "new ConfigParser should have no defined sections")\r
- self.assertFalse(cf.has_section("Foo"),\r
- "new ConfigParser should have no acknowledged "\r
- "sections")\r
- self.assertRaises(ConfigParser.NoSectionError,\r
- cf.options, "Foo")\r
- self.assertRaises(ConfigParser.NoSectionError,\r
- cf.set, "foo", "bar", "value")\r
- self.get_error(ConfigParser.NoSectionError, "foo", "bar")\r
- cf.add_section("foo")\r
- self.get_error(ConfigParser.NoOptionError, "foo", "bar")\r
-\r
- def get_error(self, exc, section, option):\r
- try:\r
- self.cf.get(section, option)\r
- except exc, e:\r
- return e\r
- else:\r
- self.fail("expected exception type %s.%s"\r
- % (exc.__module__, exc.__name__))\r
-\r
- def test_boolean(self):\r
- cf = self.fromstring(\r
- "[BOOLTEST]\n"\r
- "T1=1\n"\r
- "T2=TRUE\n"\r
- "T3=True\n"\r
- "T4=oN\n"\r
- "T5=yes\n"\r
- "F1=0\n"\r
- "F2=FALSE\n"\r
- "F3=False\n"\r
- "F4=oFF\n"\r
- "F5=nO\n"\r
- "E1=2\n"\r
- "E2=foo\n"\r
- "E3=-1\n"\r
- "E4=0.1\n"\r
- "E5=FALSE AND MORE"\r
- )\r
- for x in range(1, 5):\r
- self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))\r
- self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x))\r
- self.assertRaises(ValueError,\r
- cf.getboolean, 'BOOLTEST', 'e%d' % x)\r
-\r
- def test_weird_errors(self):\r
- cf = self.newconfig()\r
- cf.add_section("Foo")\r
- self.assertRaises(ConfigParser.DuplicateSectionError,\r
- cf.add_section, "Foo")\r
-\r
- def test_write(self):\r
- config_string = (\r
- "[Long Line]\n"\r
- "foo: this line is much, much longer than my editor\n"\r
- " likes it.\n"\r
- "[DEFAULT]\n"\r
- "foo: another very\n"\r
- " long line\n"\r
- )\r
- if self.allow_no_value:\r
- config_string += (\r
- "[Valueless]\n"\r
- "option-without-value\n"\r
- )\r
-\r
- cf = self.fromstring(config_string)\r
- output = StringIO.StringIO()\r
- cf.write(output)\r
- expect_string = (\r
- "[DEFAULT]\n"\r
- "foo = another very\n"\r
- "\tlong line\n"\r
- "\n"\r
- "[Long Line]\n"\r
- "foo = this line is much, much longer than my editor\n"\r
- "\tlikes it.\n"\r
- "\n"\r
- )\r
- if self.allow_no_value:\r
- expect_string += (\r
- "[Valueless]\n"\r
- "option-without-value\n"\r
- "\n"\r
- )\r
- self.assertEqual(output.getvalue(), expect_string)\r
-\r
- def test_set_string_types(self):\r
- cf = self.fromstring("[sect]\n"\r
- "option1=foo\n")\r
- # Check that we don't get an exception when setting values in\r
- # an existing section using strings:\r
- class mystr(str):\r
- pass\r
- cf.set("sect", "option1", "splat")\r
- cf.set("sect", "option1", mystr("splat"))\r
- cf.set("sect", "option2", "splat")\r
- cf.set("sect", "option2", mystr("splat"))\r
- try:\r
- unicode\r
- except NameError:\r
- pass\r
- else:\r
- cf.set("sect", "option1", unicode("splat"))\r
- cf.set("sect", "option2", unicode("splat"))\r
-\r
- def test_read_returns_file_list(self):\r
- file1 = test_support.findfile("cfgparser.1")\r
- # check when we pass a mix of readable and non-readable files:\r
- cf = self.newconfig()\r
- parsed_files = cf.read([file1, "nonexistent-file"])\r
- self.assertEqual(parsed_files, [file1])\r
- self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")\r
- # check when we pass only a filename:\r
- cf = self.newconfig()\r
- parsed_files = cf.read(file1)\r
- self.assertEqual(parsed_files, [file1])\r
- self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")\r
- # check when we pass only missing files:\r
- cf = self.newconfig()\r
- parsed_files = cf.read(["nonexistent-file"])\r
- self.assertEqual(parsed_files, [])\r
- # check when we pass no files:\r
- cf = self.newconfig()\r
- parsed_files = cf.read([])\r
- self.assertEqual(parsed_files, [])\r
-\r
- # shared by subclasses\r
- def get_interpolation_config(self):\r
- return self.fromstring(\r
- "[Foo]\n"\r
- "bar=something %(with1)s interpolation (1 step)\n"\r
- "bar9=something %(with9)s lots of interpolation (9 steps)\n"\r
- "bar10=something %(with10)s lots of interpolation (10 steps)\n"\r
- "bar11=something %(with11)s lots of interpolation (11 steps)\n"\r
- "with11=%(with10)s\n"\r
- "with10=%(with9)s\n"\r
- "with9=%(with8)s\n"\r
- "with8=%(With7)s\n"\r
- "with7=%(WITH6)s\n"\r
- "with6=%(with5)s\n"\r
- "With5=%(with4)s\n"\r
- "WITH4=%(with3)s\n"\r
- "with3=%(with2)s\n"\r
- "with2=%(with1)s\n"\r
- "with1=with\n"\r
- "\n"\r
- "[Mutual Recursion]\n"\r
- "foo=%(bar)s\n"\r
- "bar=%(foo)s\n"\r
- "\n"\r
- "[Interpolation Error]\n"\r
- "name=%(reference)s\n",\r
- # no definition for 'reference'\r
- defaults={"getname": "%(__name__)s"})\r
-\r
- def check_items_config(self, expected):\r
- cf = self.fromstring(\r
- "[section]\n"\r
- "name = value\n"\r
- "key: |%(name)s| \n"\r
- "getdefault: |%(default)s|\n"\r
- "getname: |%(__name__)s|",\r
- defaults={"default": "<default>"})\r
- L = list(cf.items("section"))\r
- L.sort()\r
- self.assertEqual(L, expected)\r
-\r
-\r
-class ConfigParserTestCase(TestCaseBase):\r
- config_class = ConfigParser.ConfigParser\r
- allow_no_value = True\r
-\r
- def test_interpolation(self):\r
- rawval = {\r
- ConfigParser.ConfigParser: ("something %(with11)s "\r
- "lots of interpolation (11 steps)"),\r
- ConfigParser.SafeConfigParser: "%(with1)s",\r
- }\r
- cf = self.get_interpolation_config()\r
- eq = self.assertEqual\r
- eq(cf.get("Foo", "getname"), "Foo")\r
- eq(cf.get("Foo", "bar"), "something with interpolation (1 step)")\r
- eq(cf.get("Foo", "bar9"),\r
- "something with lots of interpolation (9 steps)")\r
- eq(cf.get("Foo", "bar10"),\r
- "something with lots of interpolation (10 steps)")\r
- self.get_error(ConfigParser.InterpolationDepthError, "Foo", "bar11")\r
-\r
- def test_interpolation_missing_value(self):\r
- self.get_interpolation_config()\r
- e = self.get_error(ConfigParser.InterpolationError,\r
- "Interpolation Error", "name")\r
- self.assertEqual(e.reference, "reference")\r
- self.assertEqual(e.section, "Interpolation Error")\r
- self.assertEqual(e.option, "name")\r
-\r
- def test_items(self):\r
- self.check_items_config([('default', '<default>'),\r
- ('getdefault', '|<default>|'),\r
- ('getname', '|section|'),\r
- ('key', '|value|'),\r
- ('name', 'value')])\r
-\r
- def test_set_nonstring_types(self):\r
- cf = self.newconfig()\r
- cf.add_section('non-string')\r
- cf.set('non-string', 'int', 1)\r
- cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13, '%('])\r
- cf.set('non-string', 'dict', {'pi': 3.14159, '%(': 1,\r
- '%(list)': '%(list)'})\r
- cf.set('non-string', 'string_with_interpolation', '%(list)s')\r
- cf.set('non-string', 'no-value')\r
- self.assertEqual(cf.get('non-string', 'int', raw=True), 1)\r
- self.assertRaises(TypeError, cf.get, 'non-string', 'int')\r
- self.assertEqual(cf.get('non-string', 'list', raw=True),\r
- [0, 1, 1, 2, 3, 5, 8, 13, '%('])\r
- self.assertRaises(TypeError, cf.get, 'non-string', 'list')\r
- self.assertEqual(cf.get('non-string', 'dict', raw=True),\r
- {'pi': 3.14159, '%(': 1, '%(list)': '%(list)'})\r
- self.assertRaises(TypeError, cf.get, 'non-string', 'dict')\r
- self.assertEqual(cf.get('non-string', 'string_with_interpolation',\r
- raw=True), '%(list)s')\r
- self.assertRaises(ValueError, cf.get, 'non-string',\r
- 'string_with_interpolation', raw=False)\r
- self.assertEqual(cf.get('non-string', 'no-value'), None)\r
-\r
-class MultilineValuesTestCase(TestCaseBase):\r
- config_class = ConfigParser.ConfigParser\r
- wonderful_spam = ("I'm having spam spam spam spam "\r
- "spam spam spam beaked beans spam "\r
- "spam spam and spam!").replace(' ', '\t\n')\r
-\r
- def setUp(self):\r
- cf = self.newconfig()\r
- for i in range(100):\r
- s = 'section{}'.format(i)\r
- cf.add_section(s)\r
- for j in range(10):\r
- cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)\r
- with open(test_support.TESTFN, 'w') as f:\r
- cf.write(f)\r
-\r
- def tearDown(self):\r
- os.unlink(test_support.TESTFN)\r
-\r
- def test_dominating_multiline_values(self):\r
- # we're reading from file because this is where the code changed\r
- # during performance updates in Python 3.2\r
- cf_from_file = self.newconfig()\r
- with open(test_support.TESTFN) as f:\r
- cf_from_file.readfp(f)\r
- self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),\r
- self.wonderful_spam.replace('\t\n', '\n'))\r
-\r
-class RawConfigParserTestCase(TestCaseBase):\r
- config_class = ConfigParser.RawConfigParser\r
-\r
- def test_interpolation(self):\r
- cf = self.get_interpolation_config()\r
- eq = self.assertEqual\r
- eq(cf.get("Foo", "getname"), "%(__name__)s")\r
- eq(cf.get("Foo", "bar"),\r
- "something %(with1)s interpolation (1 step)")\r
- eq(cf.get("Foo", "bar9"),\r
- "something %(with9)s lots of interpolation (9 steps)")\r
- eq(cf.get("Foo", "bar10"),\r
- "something %(with10)s lots of interpolation (10 steps)")\r
- eq(cf.get("Foo", "bar11"),\r
- "something %(with11)s lots of interpolation (11 steps)")\r
-\r
- def test_items(self):\r
- self.check_items_config([('default', '<default>'),\r
- ('getdefault', '|%(default)s|'),\r
- ('getname', '|%(__name__)s|'),\r
- ('key', '|%(name)s|'),\r
- ('name', 'value')])\r
-\r
- def test_set_nonstring_types(self):\r
- cf = self.newconfig()\r
- cf.add_section('non-string')\r
- cf.set('non-string', 'int', 1)\r
- cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13])\r
- cf.set('non-string', 'dict', {'pi': 3.14159})\r
- self.assertEqual(cf.get('non-string', 'int'), 1)\r
- self.assertEqual(cf.get('non-string', 'list'),\r
- [0, 1, 1, 2, 3, 5, 8, 13])\r
- self.assertEqual(cf.get('non-string', 'dict'), {'pi': 3.14159})\r
-\r
-\r
-class SafeConfigParserTestCase(ConfigParserTestCase):\r
- config_class = ConfigParser.SafeConfigParser\r
-\r
- def test_safe_interpolation(self):\r
- # See http://www.python.org/sf/511737\r
- cf = self.fromstring("[section]\n"\r
- "option1=xxx\n"\r
- "option2=%(option1)s/xxx\n"\r
- "ok=%(option1)s/%%s\n"\r
- "not_ok=%(option2)s/%%s")\r
- self.assertEqual(cf.get("section", "ok"), "xxx/%s")\r
- self.assertEqual(cf.get("section", "not_ok"), "xxx/xxx/%s")\r
-\r
- def test_set_malformatted_interpolation(self):\r
- cf = self.fromstring("[sect]\n"\r
- "option1=foo\n")\r
-\r
- self.assertEqual(cf.get('sect', "option1"), "foo")\r
-\r
- self.assertRaises(ValueError, cf.set, "sect", "option1", "%foo")\r
- self.assertRaises(ValueError, cf.set, "sect", "option1", "foo%")\r
- self.assertRaises(ValueError, cf.set, "sect", "option1", "f%oo")\r
-\r
- self.assertEqual(cf.get('sect', "option1"), "foo")\r
-\r
- # bug #5741: double percents are *not* malformed\r
- cf.set("sect", "option2", "foo%%bar")\r
- self.assertEqual(cf.get("sect", "option2"), "foo%bar")\r
-\r
- def test_set_nonstring_types(self):\r
- cf = self.fromstring("[sect]\n"\r
- "option1=foo\n")\r
- # Check that we get a TypeError when setting non-string values\r
- # in an existing section:\r
- self.assertRaises(TypeError, cf.set, "sect", "option1", 1)\r
- self.assertRaises(TypeError, cf.set, "sect", "option1", 1.0)\r
- self.assertRaises(TypeError, cf.set, "sect", "option1", object())\r
- self.assertRaises(TypeError, cf.set, "sect", "option2", 1)\r
- self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0)\r
- self.assertRaises(TypeError, cf.set, "sect", "option2", object())\r
-\r
- def test_add_section_default_1(self):\r
- cf = self.newconfig()\r
- self.assertRaises(ValueError, cf.add_section, "default")\r
-\r
- def test_add_section_default_2(self):\r
- cf = self.newconfig()\r
- self.assertRaises(ValueError, cf.add_section, "DEFAULT")\r
-\r
-\r
-class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase):\r
- allow_no_value = True\r
-\r
-\r
-class Issue7005TestCase(unittest.TestCase):\r
- """Test output when None is set() as a value and allow_no_value == False.\r
-\r
- http://bugs.python.org/issue7005\r
-\r
- """\r
-\r
- expected_output = "[section]\noption = None\n\n"\r
-\r
- def prepare(self, config_class):\r
- # This is the default, but that's the point.\r
- cp = config_class(allow_no_value=False)\r
- cp.add_section("section")\r
- cp.set("section", "option", None)\r
- sio = StringIO.StringIO()\r
- cp.write(sio)\r
- return sio.getvalue()\r
-\r
- def test_none_as_value_stringified(self):\r
- output = self.prepare(ConfigParser.ConfigParser)\r
- self.assertEqual(output, self.expected_output)\r
-\r
- def test_none_as_value_stringified_raw(self):\r
- output = self.prepare(ConfigParser.RawConfigParser)\r
- self.assertEqual(output, self.expected_output)\r
-\r
-\r
-class SortedTestCase(RawConfigParserTestCase):\r
- def newconfig(self, defaults=None):\r
- self.cf = self.config_class(defaults=defaults, dict_type=SortedDict)\r
- return self.cf\r
-\r
- def test_sorted(self):\r
- self.fromstring("[b]\n"\r
- "o4=1\n"\r
- "o3=2\n"\r
- "o2=3\n"\r
- "o1=4\n"\r
- "[a]\n"\r
- "k=v\n")\r
- output = StringIO.StringIO()\r
- self.cf.write(output)\r
- self.assertEqual(output.getvalue(),\r
- "[a]\n"\r
- "k = v\n\n"\r
- "[b]\n"\r
- "o1 = 4\n"\r
- "o2 = 3\n"\r
- "o3 = 2\n"\r
- "o4 = 1\n\n")\r
-\r
-\r
-def test_main():\r
- test_support.run_unittest(\r
- ConfigParserTestCase,\r
- MultilineValuesTestCase,\r
- RawConfigParserTestCase,\r
- SafeConfigParserTestCase,\r
- SafeConfigParserTestCaseNoValue,\r
- SortedTestCase,\r
- Issue7005TestCase,\r
- )\r
-\r
-\r
-if __name__ == "__main__":\r
- test_main()\r