test_cfgparser.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. import ConfigParser
  2. import StringIO
  3. import os
  4. import unittest
  5. import UserDict
  6. from test import test_support
  7. class SortedDict(UserDict.UserDict):
  8. def items(self):
  9. result = self.data.items()
  10. result.sort()
  11. return result
  12. def keys(self):
  13. result = self.data.keys()
  14. result.sort()
  15. return result
  16. def values(self):
  17. # XXX never used?
  18. result = self.items()
  19. return [i[1] for i in result]
  20. def iteritems(self): return iter(self.items())
  21. def iterkeys(self): return iter(self.keys())
  22. __iter__ = iterkeys
  23. def itervalues(self): return iter(self.values())
  24. class TestCaseBase(unittest.TestCase):
  25. allow_no_value = False
  26. def newconfig(self, defaults=None):
  27. if defaults is None:
  28. self.cf = self.config_class(allow_no_value=self.allow_no_value)
  29. else:
  30. self.cf = self.config_class(defaults,
  31. allow_no_value=self.allow_no_value)
  32. return self.cf
  33. def fromstring(self, string, defaults=None):
  34. cf = self.newconfig(defaults)
  35. sio = StringIO.StringIO(string)
  36. cf.readfp(sio)
  37. return cf
  38. def test_basic(self):
  39. config_string = (
  40. "[Foo Bar]\n"
  41. "foo=bar\n"
  42. "[Spacey Bar]\n"
  43. "foo = bar\n"
  44. "[Commented Bar]\n"
  45. "foo: bar ; comment\n"
  46. "[Long Line]\n"
  47. "foo: this line is much, much longer than my editor\n"
  48. " likes it.\n"
  49. "[Section\\with$weird%characters[\t]\n"
  50. "[Internationalized Stuff]\n"
  51. "foo[bg]: Bulgarian\n"
  52. "foo=Default\n"
  53. "foo[en]=English\n"
  54. "foo[de]=Deutsch\n"
  55. "[Spaces]\n"
  56. "key with spaces : value\n"
  57. "another with spaces = splat!\n"
  58. )
  59. if self.allow_no_value:
  60. config_string += (
  61. "[NoValue]\n"
  62. "option-without-value\n"
  63. )
  64. cf = self.fromstring(config_string)
  65. L = cf.sections()
  66. L.sort()
  67. E = [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. ]
  75. if self.allow_no_value:
  76. E.append(r'NoValue')
  77. E.sort()
  78. eq = self.assertEqual
  79. eq(L, E)
  80. # The use of spaces in the section names serves as a
  81. # regression test for SourceForge bug #583248:
  82. # http://www.python.org/sf/583248
  83. eq(cf.get('Foo Bar', 'foo'), 'bar')
  84. eq(cf.get('Spacey Bar', 'foo'), 'bar')
  85. eq(cf.get('Commented Bar', 'foo'), 'bar')
  86. eq(cf.get('Spaces', 'key with spaces'), 'value')
  87. eq(cf.get('Spaces', 'another with spaces'), 'splat!')
  88. if self.allow_no_value:
  89. eq(cf.get('NoValue', 'option-without-value'), None)
  90. self.assertNotIn('__name__', cf.options("Foo Bar"),
  91. '__name__ "option" should not be exposed by the API!')
  92. # Make sure the right things happen for remove_option();
  93. # added to include check for SourceForge bug #123324:
  94. self.assertTrue(cf.remove_option('Foo Bar', 'foo'),
  95. "remove_option() failed to report existence of option")
  96. self.assertFalse(cf.has_option('Foo Bar', 'foo'),
  97. "remove_option() failed to remove option")
  98. self.assertFalse(cf.remove_option('Foo Bar', 'foo'),
  99. "remove_option() failed to report non-existence of option"
  100. " that was removed")
  101. self.assertRaises(ConfigParser.NoSectionError,
  102. cf.remove_option, 'No Such Section', 'foo')
  103. eq(cf.get('Long Line', 'foo'),
  104. 'this line is much, much longer than my editor\nlikes it.')
  105. def test_case_sensitivity(self):
  106. cf = self.newconfig()
  107. cf.add_section("A")
  108. cf.add_section("a")
  109. L = cf.sections()
  110. L.sort()
  111. eq = self.assertEqual
  112. eq(L, ["A", "a"])
  113. cf.set("a", "B", "value")
  114. eq(cf.options("a"), ["b"])
  115. eq(cf.get("a", "b"), "value",
  116. "could not locate option, expecting case-insensitive option names")
  117. self.assertTrue(cf.has_option("a", "b"))
  118. cf.set("A", "A-B", "A-B value")
  119. for opt in ("a-b", "A-b", "a-B", "A-B"):
  120. self.assertTrue(
  121. cf.has_option("A", opt),
  122. "has_option() returned false for option which should exist")
  123. eq(cf.options("A"), ["a-b"])
  124. eq(cf.options("a"), ["b"])
  125. cf.remove_option("a", "B")
  126. eq(cf.options("a"), [])
  127. # SF bug #432369:
  128. cf = self.fromstring(
  129. "[MySection]\nOption: first line\n\tsecond line\n")
  130. eq(cf.options("MySection"), ["option"])
  131. eq(cf.get("MySection", "Option"), "first line\nsecond line")
  132. # SF bug #561822:
  133. cf = self.fromstring("[section]\nnekey=nevalue\n",
  134. defaults={"key":"value"})
  135. self.assertTrue(cf.has_option("section", "Key"))
  136. def test_default_case_sensitivity(self):
  137. cf = self.newconfig({"foo": "Bar"})
  138. self.assertEqual(
  139. cf.get("DEFAULT", "Foo"), "Bar",
  140. "could not locate option, expecting case-insensitive option names")
  141. cf = self.newconfig({"Foo": "Bar"})
  142. self.assertEqual(
  143. cf.get("DEFAULT", "Foo"), "Bar",
  144. "could not locate option, expecting case-insensitive defaults")
  145. def test_parse_errors(self):
  146. self.newconfig()
  147. self.parse_error(ConfigParser.ParsingError,
  148. "[Foo]\n extra-spaces: splat\n")
  149. self.parse_error(ConfigParser.ParsingError,
  150. "[Foo]\n extra-spaces= splat\n")
  151. self.parse_error(ConfigParser.ParsingError,
  152. "[Foo]\n:value-without-option-name\n")
  153. self.parse_error(ConfigParser.ParsingError,
  154. "[Foo]\n=value-without-option-name\n")
  155. self.parse_error(ConfigParser.MissingSectionHeaderError,
  156. "No Section!\n")
  157. def parse_error(self, exc, src):
  158. sio = StringIO.StringIO(src)
  159. self.assertRaises(exc, self.cf.readfp, sio)
  160. def test_query_errors(self):
  161. cf = self.newconfig()
  162. self.assertEqual(cf.sections(), [],
  163. "new ConfigParser should have no defined sections")
  164. self.assertFalse(cf.has_section("Foo"),
  165. "new ConfigParser should have no acknowledged "
  166. "sections")
  167. self.assertRaises(ConfigParser.NoSectionError,
  168. cf.options, "Foo")
  169. self.assertRaises(ConfigParser.NoSectionError,
  170. cf.set, "foo", "bar", "value")
  171. self.get_error(ConfigParser.NoSectionError, "foo", "bar")
  172. cf.add_section("foo")
  173. self.get_error(ConfigParser.NoOptionError, "foo", "bar")
  174. def get_error(self, exc, section, option):
  175. try:
  176. self.cf.get(section, option)
  177. except exc, e:
  178. return e
  179. else:
  180. self.fail("expected exception type %s.%s"
  181. % (exc.__module__, exc.__name__))
  182. def test_boolean(self):
  183. cf = self.fromstring(
  184. "[BOOLTEST]\n"
  185. "T1=1\n"
  186. "T2=TRUE\n"
  187. "T3=True\n"
  188. "T4=oN\n"
  189. "T5=yes\n"
  190. "F1=0\n"
  191. "F2=FALSE\n"
  192. "F3=False\n"
  193. "F4=oFF\n"
  194. "F5=nO\n"
  195. "E1=2\n"
  196. "E2=foo\n"
  197. "E3=-1\n"
  198. "E4=0.1\n"
  199. "E5=FALSE AND MORE"
  200. )
  201. for x in range(1, 5):
  202. self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))
  203. self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x))
  204. self.assertRaises(ValueError,
  205. cf.getboolean, 'BOOLTEST', 'e%d' % x)
  206. def test_weird_errors(self):
  207. cf = self.newconfig()
  208. cf.add_section("Foo")
  209. self.assertRaises(ConfigParser.DuplicateSectionError,
  210. cf.add_section, "Foo")
  211. def test_write(self):
  212. config_string = (
  213. "[Long Line]\n"
  214. "foo: this line is much, much longer than my editor\n"
  215. " likes it.\n"
  216. "[DEFAULT]\n"
  217. "foo: another very\n"
  218. " long line\n"
  219. )
  220. if self.allow_no_value:
  221. config_string += (
  222. "[Valueless]\n"
  223. "option-without-value\n"
  224. )
  225. cf = self.fromstring(config_string)
  226. output = StringIO.StringIO()
  227. cf.write(output)
  228. expect_string = (
  229. "[DEFAULT]\n"
  230. "foo = another very\n"
  231. "\tlong line\n"
  232. "\n"
  233. "[Long Line]\n"
  234. "foo = this line is much, much longer than my editor\n"
  235. "\tlikes it.\n"
  236. "\n"
  237. )
  238. if self.allow_no_value:
  239. expect_string += (
  240. "[Valueless]\n"
  241. "option-without-value\n"
  242. "\n"
  243. )
  244. self.assertEqual(output.getvalue(), expect_string)
  245. def test_set_string_types(self):
  246. cf = self.fromstring("[sect]\n"
  247. "option1=foo\n")
  248. # Check that we don't get an exception when setting values in
  249. # an existing section using strings:
  250. class mystr(str):
  251. pass
  252. cf.set("sect", "option1", "splat")
  253. cf.set("sect", "option1", mystr("splat"))
  254. cf.set("sect", "option2", "splat")
  255. cf.set("sect", "option2", mystr("splat"))
  256. def test_set_unicode(self):
  257. try:
  258. unicode
  259. except NameError:
  260. self.skipTest('no unicode support')
  261. cf = self.fromstring("[sect]\n"
  262. "option1=foo\n")
  263. cf.set("sect", "option1", unicode("splat"))
  264. cf.set("sect", "option2", unicode("splat"))
  265. def test_read_returns_file_list(self):
  266. file1 = test_support.findfile("cfgparser.1")
  267. # check when we pass a mix of readable and non-readable files:
  268. cf = self.newconfig()
  269. parsed_files = cf.read([file1, "nonexistent-file"])
  270. self.assertEqual(parsed_files, [file1])
  271. self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
  272. # check when we pass only a filename:
  273. cf = self.newconfig()
  274. parsed_files = cf.read(file1)
  275. self.assertEqual(parsed_files, [file1])
  276. self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
  277. # check when we pass only missing files:
  278. cf = self.newconfig()
  279. parsed_files = cf.read(["nonexistent-file"])
  280. self.assertEqual(parsed_files, [])
  281. # check when we pass no files:
  282. cf = self.newconfig()
  283. parsed_files = cf.read([])
  284. self.assertEqual(parsed_files, [])
  285. # shared by subclasses
  286. def get_interpolation_config(self):
  287. return self.fromstring(
  288. "[Foo]\n"
  289. "bar=something %(with1)s interpolation (1 step)\n"
  290. "bar9=something %(with9)s lots of interpolation (9 steps)\n"
  291. "bar10=something %(with10)s lots of interpolation (10 steps)\n"
  292. "bar11=something %(with11)s lots of interpolation (11 steps)\n"
  293. "with11=%(with10)s\n"
  294. "with10=%(with9)s\n"
  295. "with9=%(with8)s\n"
  296. "with8=%(With7)s\n"
  297. "with7=%(WITH6)s\n"
  298. "with6=%(with5)s\n"
  299. "With5=%(with4)s\n"
  300. "WITH4=%(with3)s\n"
  301. "with3=%(with2)s\n"
  302. "with2=%(with1)s\n"
  303. "with1=with\n"
  304. "\n"
  305. "[Mutual Recursion]\n"
  306. "foo=%(bar)s\n"
  307. "bar=%(foo)s\n"
  308. "\n"
  309. "[Interpolation Error]\n"
  310. "name=%(reference)s\n",
  311. # no definition for 'reference'
  312. defaults={"getname": "%(__name__)s"})
  313. def check_items_config(self, expected):
  314. cf = self.fromstring(
  315. "[section]\n"
  316. "name = value\n"
  317. "key: |%(name)s| \n"
  318. "getdefault: |%(default)s|\n"
  319. "getname: |%(__name__)s|",
  320. defaults={"default": "<default>"})
  321. L = list(cf.items("section"))
  322. L.sort()
  323. self.assertEqual(L, expected)
  324. class ConfigParserTestCase(TestCaseBase):
  325. config_class = ConfigParser.ConfigParser
  326. allow_no_value = True
  327. def test_interpolation(self):
  328. rawval = {
  329. ConfigParser.ConfigParser: ("something %(with11)s "
  330. "lots of interpolation (11 steps)"),
  331. ConfigParser.SafeConfigParser: "%(with1)s",
  332. }
  333. cf = self.get_interpolation_config()
  334. eq = self.assertEqual
  335. eq(cf.get("Foo", "getname"), "Foo")
  336. eq(cf.get("Foo", "bar"), "something with interpolation (1 step)")
  337. eq(cf.get("Foo", "bar9"),
  338. "something with lots of interpolation (9 steps)")
  339. eq(cf.get("Foo", "bar10"),
  340. "something with lots of interpolation (10 steps)")
  341. self.get_error(ConfigParser.InterpolationDepthError, "Foo", "bar11")
  342. def test_interpolation_missing_value(self):
  343. self.get_interpolation_config()
  344. e = self.get_error(ConfigParser.InterpolationError,
  345. "Interpolation Error", "name")
  346. self.assertEqual(e.reference, "reference")
  347. self.assertEqual(e.section, "Interpolation Error")
  348. self.assertEqual(e.option, "name")
  349. def test_items(self):
  350. self.check_items_config([('default', '<default>'),
  351. ('getdefault', '|<default>|'),
  352. ('getname', '|section|'),
  353. ('key', '|value|'),
  354. ('name', 'value')])
  355. def test_set_nonstring_types(self):
  356. cf = self.newconfig()
  357. cf.add_section('non-string')
  358. cf.set('non-string', 'int', 1)
  359. cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13, '%('])
  360. cf.set('non-string', 'dict', {'pi': 3.14159, '%(': 1,
  361. '%(list)': '%(list)'})
  362. cf.set('non-string', 'string_with_interpolation', '%(list)s')
  363. cf.set('non-string', 'no-value')
  364. self.assertEqual(cf.get('non-string', 'int', raw=True), 1)
  365. self.assertRaises(TypeError, cf.get, 'non-string', 'int')
  366. self.assertEqual(cf.get('non-string', 'list', raw=True),
  367. [0, 1, 1, 2, 3, 5, 8, 13, '%('])
  368. self.assertRaises(TypeError, cf.get, 'non-string', 'list')
  369. self.assertEqual(cf.get('non-string', 'dict', raw=True),
  370. {'pi': 3.14159, '%(': 1, '%(list)': '%(list)'})
  371. self.assertRaises(TypeError, cf.get, 'non-string', 'dict')
  372. self.assertEqual(cf.get('non-string', 'string_with_interpolation',
  373. raw=True), '%(list)s')
  374. self.assertRaises(ValueError, cf.get, 'non-string',
  375. 'string_with_interpolation', raw=False)
  376. self.assertEqual(cf.get('non-string', 'no-value'), None)
  377. class MultilineValuesTestCase(TestCaseBase):
  378. config_class = ConfigParser.ConfigParser
  379. wonderful_spam = ("I'm having spam spam spam spam "
  380. "spam spam spam beaked beans spam "
  381. "spam spam and spam!").replace(' ', '\t\n')
  382. def setUp(self):
  383. cf = self.newconfig()
  384. for i in range(100):
  385. s = 'section{}'.format(i)
  386. cf.add_section(s)
  387. for j in range(10):
  388. cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)
  389. with open(test_support.TESTFN, 'w') as f:
  390. cf.write(f)
  391. def tearDown(self):
  392. os.unlink(test_support.TESTFN)
  393. def test_dominating_multiline_values(self):
  394. # we're reading from file because this is where the code changed
  395. # during performance updates in Python 3.2
  396. cf_from_file = self.newconfig()
  397. with open(test_support.TESTFN) as f:
  398. cf_from_file.readfp(f)
  399. self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
  400. self.wonderful_spam.replace('\t\n', '\n'))
  401. class RawConfigParserTestCase(TestCaseBase):
  402. config_class = ConfigParser.RawConfigParser
  403. def test_interpolation(self):
  404. cf = self.get_interpolation_config()
  405. eq = self.assertEqual
  406. eq(cf.get("Foo", "getname"), "%(__name__)s")
  407. eq(cf.get("Foo", "bar"),
  408. "something %(with1)s interpolation (1 step)")
  409. eq(cf.get("Foo", "bar9"),
  410. "something %(with9)s lots of interpolation (9 steps)")
  411. eq(cf.get("Foo", "bar10"),
  412. "something %(with10)s lots of interpolation (10 steps)")
  413. eq(cf.get("Foo", "bar11"),
  414. "something %(with11)s lots of interpolation (11 steps)")
  415. def test_items(self):
  416. self.check_items_config([('default', '<default>'),
  417. ('getdefault', '|%(default)s|'),
  418. ('getname', '|%(__name__)s|'),
  419. ('key', '|%(name)s|'),
  420. ('name', 'value')])
  421. def test_set_nonstring_types(self):
  422. cf = self.newconfig()
  423. cf.add_section('non-string')
  424. cf.set('non-string', 'int', 1)
  425. cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13])
  426. cf.set('non-string', 'dict', {'pi': 3.14159})
  427. self.assertEqual(cf.get('non-string', 'int'), 1)
  428. self.assertEqual(cf.get('non-string', 'list'),
  429. [0, 1, 1, 2, 3, 5, 8, 13])
  430. self.assertEqual(cf.get('non-string', 'dict'), {'pi': 3.14159})
  431. class SafeConfigParserTestCase(ConfigParserTestCase):
  432. config_class = ConfigParser.SafeConfigParser
  433. def test_safe_interpolation(self):
  434. # See http://www.python.org/sf/511737
  435. cf = self.fromstring("[section]\n"
  436. "option1=xxx\n"
  437. "option2=%(option1)s/xxx\n"
  438. "ok=%(option1)s/%%s\n"
  439. "not_ok=%(option2)s/%%s")
  440. self.assertEqual(cf.get("section", "ok"), "xxx/%s")
  441. self.assertEqual(cf.get("section", "not_ok"), "xxx/xxx/%s")
  442. def test_set_malformatted_interpolation(self):
  443. cf = self.fromstring("[sect]\n"
  444. "option1=foo\n")
  445. self.assertEqual(cf.get('sect', "option1"), "foo")
  446. self.assertRaises(ValueError, cf.set, "sect", "option1", "%foo")
  447. self.assertRaises(ValueError, cf.set, "sect", "option1", "foo%")
  448. self.assertRaises(ValueError, cf.set, "sect", "option1", "f%oo")
  449. self.assertEqual(cf.get('sect', "option1"), "foo")
  450. # bug #5741: double percents are *not* malformed
  451. cf.set("sect", "option2", "foo%%bar")
  452. self.assertEqual(cf.get("sect", "option2"), "foo%bar")
  453. def test_set_nonstring_types(self):
  454. cf = self.fromstring("[sect]\n"
  455. "option1=foo\n")
  456. # Check that we get a TypeError when setting non-string values
  457. # in an existing section:
  458. self.assertRaises(TypeError, cf.set, "sect", "option1", 1)
  459. self.assertRaises(TypeError, cf.set, "sect", "option1", 1.0)
  460. self.assertRaises(TypeError, cf.set, "sect", "option1", object())
  461. self.assertRaises(TypeError, cf.set, "sect", "option2", 1)
  462. self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0)
  463. self.assertRaises(TypeError, cf.set, "sect", "option2", object())
  464. def test_add_section_default_1(self):
  465. cf = self.newconfig()
  466. self.assertRaises(ValueError, cf.add_section, "default")
  467. def test_add_section_default_2(self):
  468. cf = self.newconfig()
  469. self.assertRaises(ValueError, cf.add_section, "DEFAULT")
  470. class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase):
  471. allow_no_value = True
  472. class TestChainMap(unittest.TestCase):
  473. def test_issue_12717(self):
  474. d1 = dict(red=1, green=2)
  475. d2 = dict(green=3, blue=4)
  476. dcomb = d2.copy()
  477. dcomb.update(d1)
  478. cm = ConfigParser._Chainmap(d1, d2)
  479. self.assertIsInstance(cm.keys(), list)
  480. self.assertEqual(set(cm.keys()), set(dcomb.keys())) # keys()
  481. self.assertEqual(set(cm.values()), set(dcomb.values())) # values()
  482. self.assertEqual(set(cm.items()), set(dcomb.items())) # items()
  483. self.assertEqual(set(cm), set(dcomb)) # __iter__ ()
  484. self.assertEqual(cm, dcomb) # __eq__()
  485. self.assertEqual([cm[k] for k in dcomb], dcomb.values()) # __getitem__()
  486. klist = 'red green blue black brown'.split()
  487. self.assertEqual([cm.get(k, 10) for k in klist],
  488. [dcomb.get(k, 10) for k in klist]) # get()
  489. self.assertEqual([k in cm for k in klist],
  490. [k in dcomb for k in klist]) # __contains__()
  491. with test_support.check_py3k_warnings():
  492. self.assertEqual([cm.has_key(k) for k in klist],
  493. [dcomb.has_key(k) for k in klist]) # has_key()
  494. class Issue7005TestCase(unittest.TestCase):
  495. """Test output when None is set() as a value and allow_no_value == False.
  496. http://bugs.python.org/issue7005
  497. """
  498. expected_output = "[section]\noption = None\n\n"
  499. def prepare(self, config_class):
  500. # This is the default, but that's the point.
  501. cp = config_class(allow_no_value=False)
  502. cp.add_section("section")
  503. cp.set("section", "option", None)
  504. sio = StringIO.StringIO()
  505. cp.write(sio)
  506. return sio.getvalue()
  507. def test_none_as_value_stringified(self):
  508. output = self.prepare(ConfigParser.ConfigParser)
  509. self.assertEqual(output, self.expected_output)
  510. def test_none_as_value_stringified_raw(self):
  511. output = self.prepare(ConfigParser.RawConfigParser)
  512. self.assertEqual(output, self.expected_output)
  513. class SortedTestCase(RawConfigParserTestCase):
  514. def newconfig(self, defaults=None):
  515. self.cf = self.config_class(defaults=defaults, dict_type=SortedDict)
  516. return self.cf
  517. def test_sorted(self):
  518. self.fromstring("[b]\n"
  519. "o4=1\n"
  520. "o3=2\n"
  521. "o2=3\n"
  522. "o1=4\n"
  523. "[a]\n"
  524. "k=v\n")
  525. output = StringIO.StringIO()
  526. self.cf.write(output)
  527. self.assertEqual(output.getvalue(),
  528. "[a]\n"
  529. "k = v\n\n"
  530. "[b]\n"
  531. "o1 = 4\n"
  532. "o2 = 3\n"
  533. "o3 = 2\n"
  534. "o4 = 1\n\n")
  535. class ExceptionPicklingTestCase(unittest.TestCase):
  536. """Tests for issue #13760: ConfigParser exceptions are not picklable."""
  537. def test_error(self):
  538. import pickle
  539. e1 = ConfigParser.Error('value')
  540. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  541. pickled = pickle.dumps(e1, proto)
  542. e2 = pickle.loads(pickled)
  543. self.assertEqual(e1.message, e2.message)
  544. self.assertEqual(repr(e1), repr(e2))
  545. def test_nosectionerror(self):
  546. import pickle
  547. e1 = ConfigParser.NoSectionError('section')
  548. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  549. pickled = pickle.dumps(e1, proto)
  550. e2 = pickle.loads(pickled)
  551. self.assertEqual(e1.message, e2.message)
  552. self.assertEqual(e1.args, e2.args)
  553. self.assertEqual(e1.section, e2.section)
  554. self.assertEqual(repr(e1), repr(e2))
  555. def test_nooptionerror(self):
  556. import pickle
  557. e1 = ConfigParser.NoOptionError('option', 'section')
  558. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  559. pickled = pickle.dumps(e1, proto)
  560. e2 = pickle.loads(pickled)
  561. self.assertEqual(e1.message, e2.message)
  562. self.assertEqual(e1.args, e2.args)
  563. self.assertEqual(e1.section, e2.section)
  564. self.assertEqual(e1.option, e2.option)
  565. self.assertEqual(repr(e1), repr(e2))
  566. def test_duplicatesectionerror(self):
  567. import pickle
  568. e1 = ConfigParser.DuplicateSectionError('section')
  569. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  570. pickled = pickle.dumps(e1, proto)
  571. e2 = pickle.loads(pickled)
  572. self.assertEqual(e1.message, e2.message)
  573. self.assertEqual(e1.args, e2.args)
  574. self.assertEqual(e1.section, e2.section)
  575. self.assertEqual(repr(e1), repr(e2))
  576. def test_interpolationerror(self):
  577. import pickle
  578. e1 = ConfigParser.InterpolationError('option', 'section', 'msg')
  579. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  580. pickled = pickle.dumps(e1, proto)
  581. e2 = pickle.loads(pickled)
  582. self.assertEqual(e1.message, e2.message)
  583. self.assertEqual(e1.args, e2.args)
  584. self.assertEqual(e1.section, e2.section)
  585. self.assertEqual(e1.option, e2.option)
  586. self.assertEqual(repr(e1), repr(e2))
  587. def test_interpolationmissingoptionerror(self):
  588. import pickle
  589. e1 = ConfigParser.InterpolationMissingOptionError('option', 'section',
  590. 'rawval', 'reference')
  591. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  592. pickled = pickle.dumps(e1, proto)
  593. e2 = pickle.loads(pickled)
  594. self.assertEqual(e1.message, e2.message)
  595. self.assertEqual(e1.args, e2.args)
  596. self.assertEqual(e1.section, e2.section)
  597. self.assertEqual(e1.option, e2.option)
  598. self.assertEqual(e1.reference, e2.reference)
  599. self.assertEqual(repr(e1), repr(e2))
  600. def test_interpolationsyntaxerror(self):
  601. import pickle
  602. e1 = ConfigParser.InterpolationSyntaxError('option', 'section', 'msg')
  603. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  604. pickled = pickle.dumps(e1, proto)
  605. e2 = pickle.loads(pickled)
  606. self.assertEqual(e1.message, e2.message)
  607. self.assertEqual(e1.args, e2.args)
  608. self.assertEqual(e1.section, e2.section)
  609. self.assertEqual(e1.option, e2.option)
  610. self.assertEqual(repr(e1), repr(e2))
  611. def test_interpolationdeptherror(self):
  612. import pickle
  613. e1 = ConfigParser.InterpolationDepthError('option', 'section',
  614. 'rawval')
  615. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  616. pickled = pickle.dumps(e1, proto)
  617. e2 = pickle.loads(pickled)
  618. self.assertEqual(e1.message, e2.message)
  619. self.assertEqual(e1.args, e2.args)
  620. self.assertEqual(e1.section, e2.section)
  621. self.assertEqual(e1.option, e2.option)
  622. self.assertEqual(repr(e1), repr(e2))
  623. def test_parsingerror(self):
  624. import pickle
  625. e1 = ConfigParser.ParsingError('source')
  626. e1.append(1, 'line1')
  627. e1.append(2, 'line2')
  628. e1.append(3, 'line3')
  629. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  630. pickled = pickle.dumps(e1, proto)
  631. e2 = pickle.loads(pickled)
  632. self.assertEqual(e1.message, e2.message)
  633. self.assertEqual(e1.args, e2.args)
  634. self.assertEqual(e1.filename, e2.filename)
  635. self.assertEqual(e1.errors, e2.errors)
  636. self.assertEqual(repr(e1), repr(e2))
  637. def test_missingsectionheadererror(self):
  638. import pickle
  639. e1 = ConfigParser.MissingSectionHeaderError('filename', 123, 'line')
  640. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  641. pickled = pickle.dumps(e1, proto)
  642. e2 = pickle.loads(pickled)
  643. self.assertEqual(e1.message, e2.message)
  644. self.assertEqual(e1.args, e2.args)
  645. self.assertEqual(e1.line, e2.line)
  646. self.assertEqual(e1.filename, e2.filename)
  647. self.assertEqual(e1.lineno, e2.lineno)
  648. self.assertEqual(repr(e1), repr(e2))
  649. def test_main():
  650. test_support.run_unittest(
  651. ConfigParserTestCase,
  652. MultilineValuesTestCase,
  653. RawConfigParserTestCase,
  654. SafeConfigParserTestCase,
  655. SafeConfigParserTestCaseNoValue,
  656. SortedTestCase,
  657. Issue7005TestCase,
  658. TestChainMap,
  659. ExceptionPicklingTestCase,
  660. )
  661. if __name__ == "__main__":
  662. test_main()