Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(264947)

Delta Between Two Patch Sets: Lib/test/test_configparser.py

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 6 years, 9 months ago
Right Patch Set: Created 5 years, 6 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_concurrent_futures.py ('k') | Lib/test/test_copyreg.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 import collections 1 import collections
2 import configparser 2 import configparser
3 import io 3 import io
4 import os 4 import os
5 import sys 5 import sys
6 import textwrap 6 import textwrap
7 import unittest 7 import unittest
8 import warnings 8 import warnings
9 9
10 from test import support 10 from test import support
(...skipping 14 matching lines...) Expand all
25 25
26 def iterkeys(self): 26 def iterkeys(self):
27 return iter(self.keys()) 27 return iter(self.keys())
28 28
29 def itervalues(self): 29 def itervalues(self):
30 return iter(self.values()) 30 return iter(self.values())
31 31
32 __iter__ = iterkeys 32 __iter__ = iterkeys
33 33
34 34
35 class CfgParserTestCaseClass(unittest.TestCase): 35 class CfgParserTestCaseClass:
36 allow_no_value = False 36 allow_no_value = False
37 delimiters = ('=', ':') 37 delimiters = ('=', ':')
38 comment_prefixes = (';', '#') 38 comment_prefixes = (';', '#')
39 inline_comment_prefixes = (';', '#') 39 inline_comment_prefixes = (';', '#')
40 empty_lines_in_values = True 40 empty_lines_in_values = True
41 dict_type = configparser._default_dict 41 dict_type = configparser._default_dict
42 strict = False 42 strict = False
43 default_section = configparser.DEFAULTSECT 43 default_section = configparser.DEFAULTSECT
44 interpolation = configparser._UNSET 44 interpolation = configparser._UNSET
45 45
(...skipping 573 matching lines...) Expand 10 before | Expand all | Expand 10 after
619 with self.assertRaises(configparser.DuplicateSectionError) as cm: 619 with self.assertRaises(configparser.DuplicateSectionError) as cm:
620 cf.read_string(textwrap.dedent("""\ 620 cf.read_string(textwrap.dedent("""\
621 [Foo] 621 [Foo]
622 will this be added{equals}True 622 will this be added{equals}True
623 [Bar] 623 [Bar]
624 what about this{equals}True 624 what about this{equals}True
625 [Foo] 625 [Foo]
626 oops{equals}this won't 626 oops{equals}this won't
627 """.format(equals=self.delimiters[0])), source='<foo-bar>') 627 """.format(equals=self.delimiters[0])), source='<foo-bar>')
628 e = cm.exception 628 e = cm.exception
629 self.assertEqual(str(e), "While reading from <foo-bar> [line 5]: " 629 self.assertEqual(str(e), "While reading from '<foo-bar>' "
630 "section 'Foo' already exists") 630 "[line 5]: section 'Foo' already exists")
631 self.assertEqual(e.args, ("Foo", '<foo-bar>', 5)) 631 self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))
632 632
633 with self.assertRaises(configparser.DuplicateOptionError) as cm: 633 with self.assertRaises(configparser.DuplicateOptionError) as cm:
634 cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}}) 634 cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
635 e = cm.exception 635 e = cm.exception
636 self.assertEqual(str(e), "While reading from <dict>: option 'opt' " 636 self.assertEqual(str(e), "While reading from '<dict>': option "
637 "in section 'Bar' already exists") 637 "'opt' in section 'Bar' already exists")
638 self.assertEqual(e.args, ("Bar", "opt", "<dict>", None)) 638 self.assertEqual(e.args, ("Bar", "opt", "<dict>", None))
639 639
640 def test_write(self): 640 def test_write(self):
641 config_string = ( 641 config_string = (
642 "[Long Line]\n" 642 "[Long Line]\n"
643 "foo{0[0]} this line is much, much longer than my editor\n" 643 "foo{0[0]} this line is much, much longer than my editor\n"
644 " likes it.\n" 644 " likes it.\n"
645 "[{default_section}]\n" 645 "[{default_section}]\n"
646 "foo{0[1]} another very\n" 646 "foo{0[1]} another very\n"
647 " long line\n" 647 " long line\n"
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
700 pass 700 pass
701 cf.set("sect", "option1", "splat") 701 cf.set("sect", "option1", "splat")
702 cf.set("sect", "option1", mystr("splat")) 702 cf.set("sect", "option1", mystr("splat"))
703 cf.set("sect", "option2", "splat") 703 cf.set("sect", "option2", "splat")
704 cf.set("sect", "option2", mystr("splat")) 704 cf.set("sect", "option2", mystr("splat"))
705 cf.set("sect", "option1", "splat") 705 cf.set("sect", "option1", "splat")
706 cf.set("sect", "option2", "splat") 706 cf.set("sect", "option2", "splat")
707 707
708 def test_read_returns_file_list(self): 708 def test_read_returns_file_list(self):
709 if self.delimiters[0] != '=': 709 if self.delimiters[0] != '=':
710 # skip reading the file if we're using an incompatible format 710 self.skipTest('incompatible format')
711 return
712 file1 = support.findfile("cfgparser.1") 711 file1 = support.findfile("cfgparser.1")
713 # check when we pass a mix of readable and non-readable files: 712 # check when we pass a mix of readable and non-readable files:
714 cf = self.newconfig() 713 cf = self.newconfig()
715 parsed_files = cf.read([file1, "nonexistent-file"]) 714 parsed_files = cf.read([file1, "nonexistent-file"])
716 self.assertEqual(parsed_files, [file1]) 715 self.assertEqual(parsed_files, [file1])
717 self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") 716 self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
718 # check when we pass only a filename: 717 # check when we pass only a filename:
719 cf = self.newconfig() 718 cf = self.newconfig()
720 parsed_files = cf.read(file1) 719 parsed_files = cf.read(file1)
721 self.assertEqual(parsed_files, [file1]) 720 self.assertEqual(parsed_files, [file1])
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
763 name {0[0]} %(value)s 762 name {0[0]} %(value)s
764 key{0[1]} |%(name)s| 763 key{0[1]} |%(name)s|
765 getdefault{0[1]} |%(default)s| 764 getdefault{0[1]} |%(default)s|
766 """.format(self.delimiters), defaults={"default": "<default>"}) 765 """.format(self.delimiters), defaults={"default": "<default>"})
767 L = list(cf.items("section", vars={'value': 'value'})) 766 L = list(cf.items("section", vars={'value': 'value'}))
768 L.sort() 767 L.sort()
769 self.assertEqual(L, expected) 768 self.assertEqual(L, expected)
770 with self.assertRaises(configparser.NoSectionError): 769 with self.assertRaises(configparser.NoSectionError):
771 cf.items("no such section") 770 cf.items("no such section")
772 771
773 772 def test_popitem(self):
774 class StrictTestCase(BasicTestCase): 773 cf = self.fromstring("""
774 [section1]
775 name1 {0[0]} value1
776 [section2]
777 name2 {0[0]} value2
778 [section3]
779 name3 {0[0]} value3
780 """.format(self.delimiters), defaults={"default": "<default>"})
781 self.assertEqual(cf.popitem()[0], 'section1')
782 self.assertEqual(cf.popitem()[0], 'section2')
783 self.assertEqual(cf.popitem()[0], 'section3')
784 with self.assertRaises(KeyError):
785 cf.popitem()
786
787 def test_clear(self):
788 cf = self.newconfig({"foo": "Bar"})
789 self.assertEqual(
790 cf.get(self.default_section, "Foo"), "Bar",
791 "could not locate option, expecting case-insensitive option names")
792 cf['zing'] = {'option1': 'value1', 'option2': 'value2'}
793 self.assertEqual(cf.sections(), ['zing'])
794 self.assertEqual(set(cf['zing'].keys()), {'option1', 'option2', 'foo'})
795 cf.clear()
796 self.assertEqual(set(cf.sections()), set())
797 self.assertEqual(set(cf[self.default_section].keys()), {'foo'})
798
799 def test_setitem(self):
800 cf = self.fromstring("""
801 [section1]
802 name1 {0[0]} value1
803 [section2]
804 name2 {0[0]} value2
805 [section3]
806 name3 {0[0]} value3
807 """.format(self.delimiters), defaults={"nameD": "valueD"})
808 self.assertEqual(set(cf['section1'].keys()), {'name1', 'named'})
809 self.assertEqual(set(cf['section2'].keys()), {'name2', 'named'})
810 self.assertEqual(set(cf['section3'].keys()), {'name3', 'named'})
811 self.assertEqual(cf['section1']['name1'], 'value1')
812 self.assertEqual(cf['section2']['name2'], 'value2')
813 self.assertEqual(cf['section3']['name3'], 'value3')
814 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
815 cf['section2'] = {'name22': 'value22'}
816 self.assertEqual(set(cf['section2'].keys()), {'name22', 'named'})
817 self.assertEqual(cf['section2']['name22'], 'value22')
818 self.assertNotIn('name2', cf['section2'])
819 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
820 cf['section3'] = {}
821 self.assertEqual(set(cf['section3'].keys()), {'named'})
822 self.assertNotIn('name3', cf['section3'])
823 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
824 cf[self.default_section] = {}
825 self.assertEqual(set(cf[self.default_section].keys()), set())
826 self.assertEqual(set(cf['section1'].keys()), {'name1'})
827 self.assertEqual(set(cf['section2'].keys()), {'name22'})
828 self.assertEqual(set(cf['section3'].keys()), set())
829 self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
830
831
832 class StrictTestCase(BasicTestCase, unittest.TestCase):
775 config_class = configparser.RawConfigParser 833 config_class = configparser.RawConfigParser
776 strict = True 834 strict = True
777 835
778 836
779 class ConfigParserTestCase(BasicTestCase): 837 class ConfigParserTestCase(BasicTestCase, unittest.TestCase):
780 config_class = configparser.ConfigParser 838 config_class = configparser.ConfigParser
781 839
782 def test_interpolation(self): 840 def test_interpolation(self):
783 cf = self.get_interpolation_config() 841 cf = self.get_interpolation_config()
784 eq = self.assertEqual 842 eq = self.assertEqual
785 eq(cf.get("Foo", "bar"), "something with interpolation (1 step)") 843 eq(cf.get("Foo", "bar"), "something with interpolation (1 step)")
786 eq(cf.get("Foo", "bar9"), 844 eq(cf.get("Foo", "bar9"),
787 "something with lots of interpolation (9 steps)") 845 "something with lots of interpolation (9 steps)")
788 eq(cf.get("Foo", "bar10"), 846 eq(cf.get("Foo", "bar10"),
789 "something with lots of interpolation (10 steps)") 847 "something with lots of interpolation (10 steps)")
(...skipping 68 matching lines...) Expand 10 before | Expand all | Expand 10 after
858 self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0) 916 self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0)
859 self.assertRaises(TypeError, cf.set, "sect", "option2", object()) 917 self.assertRaises(TypeError, cf.set, "sect", "option2", object())
860 self.assertRaises(TypeError, cf.set, "sect", 123, "invalid opt name!") 918 self.assertRaises(TypeError, cf.set, "sect", 123, "invalid opt name!")
861 self.assertRaises(TypeError, cf.add_section, 123) 919 self.assertRaises(TypeError, cf.add_section, 123)
862 920
863 def test_add_section_default(self): 921 def test_add_section_default(self):
864 cf = self.newconfig() 922 cf = self.newconfig()
865 self.assertRaises(ValueError, cf.add_section, self.default_section) 923 self.assertRaises(ValueError, cf.add_section, self.default_section)
866 924
867 925
868 class ConfigParserTestCaseNoInterpolation(BasicTestCase): 926 class ConfigParserTestCaseNoInterpolation(BasicTestCase, unittest.TestCase):
869 config_class = configparser.ConfigParser 927 config_class = configparser.ConfigParser
870 interpolation = None 928 interpolation = None
871 ini = textwrap.dedent(""" 929 ini = textwrap.dedent("""
872 [numbers] 930 [numbers]
873 one = 1 931 one = 1
874 two = %(one)s * 2 932 two = %(one)s * 2
875 three = ${common:one} * 3 933 three = ${common:one} * 3
876 934
877 [hexen] 935 [hexen]
878 sixteen = ${numbers:two} * 8 936 sixteen = ${numbers:two} * 8
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
923 self.assertEqual(cf.get("sect", "option2"), "foo%%bar") 981 self.assertEqual(cf.get("sect", "option2"), "foo%%bar")
924 982
925 class ConfigParserTestCaseNonStandardDelimiters(ConfigParserTestCase): 983 class ConfigParserTestCaseNonStandardDelimiters(ConfigParserTestCase):
926 delimiters = (':=', '$') 984 delimiters = (':=', '$')
927 comment_prefixes = ('//', '"') 985 comment_prefixes = ('//', '"')
928 inline_comment_prefixes = ('//', '"') 986 inline_comment_prefixes = ('//', '"')
929 987
930 class ConfigParserTestCaseNonStandardDefaultSection(ConfigParserTestCase): 988 class ConfigParserTestCaseNonStandardDefaultSection(ConfigParserTestCase):
931 default_section = 'general' 989 default_section = 'general'
932 990
933 class MultilineValuesTestCase(BasicTestCase): 991 class MultilineValuesTestCase(BasicTestCase, unittest.TestCase):
934 config_class = configparser.ConfigParser 992 config_class = configparser.ConfigParser
935 wonderful_spam = ("I'm having spam spam spam spam " 993 wonderful_spam = ("I'm having spam spam spam spam "
936 "spam spam spam beaked beans spam " 994 "spam spam spam beaked beans spam "
937 "spam spam and spam!").replace(' ', '\t\n') 995 "spam spam and spam!").replace(' ', '\t\n')
938 996
939 def setUp(self): 997 def setUp(self):
940 cf = self.newconfig() 998 cf = self.newconfig()
941 for i in range(100): 999 for i in range(100):
942 s = 'section{}'.format(i) 1000 s = 'section{}'.format(i)
943 cf.add_section(s) 1001 cf.add_section(s)
944 for j in range(10): 1002 for j in range(10):
945 cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam) 1003 cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)
946 with open(support.TESTFN, 'w') as f: 1004 with open(support.TESTFN, 'w') as f:
947 cf.write(f) 1005 cf.write(f)
948 1006
949 def tearDown(self): 1007 def tearDown(self):
950 os.unlink(support.TESTFN) 1008 os.unlink(support.TESTFN)
951 1009
952 def test_dominating_multiline_values(self): 1010 def test_dominating_multiline_values(self):
953 # We're reading from file because this is where the code changed 1011 # We're reading from file because this is where the code changed
954 # during performance updates in Python 3.2 1012 # during performance updates in Python 3.2
955 cf_from_file = self.newconfig() 1013 cf_from_file = self.newconfig()
956 with open(support.TESTFN) as f: 1014 with open(support.TESTFN) as f:
957 cf_from_file.read_file(f) 1015 cf_from_file.read_file(f)
958 self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'), 1016 self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
959 self.wonderful_spam.replace('\t\n', '\n')) 1017 self.wonderful_spam.replace('\t\n', '\n'))
960 1018
961 class RawConfigParserTestCase(BasicTestCase): 1019 class RawConfigParserTestCase(BasicTestCase, unittest.TestCase):
962 config_class = configparser.RawConfigParser 1020 config_class = configparser.RawConfigParser
963 1021
964 def test_interpolation(self): 1022 def test_interpolation(self):
965 cf = self.get_interpolation_config() 1023 cf = self.get_interpolation_config()
966 eq = self.assertEqual 1024 eq = self.assertEqual
967 eq(cf.get("Foo", "bar"), 1025 eq(cf.get("Foo", "bar"),
968 "something %(with1)s interpolation (1 step)") 1026 "something %(with1)s interpolation (1 step)")
969 eq(cf.get("Foo", "bar9"), 1027 eq(cf.get("Foo", "bar9"),
970 "something %(with9)s lots of interpolation (9 steps)") 1028 "something %(with9)s lots of interpolation (9 steps)")
971 eq(cf.get("Foo", "bar10"), 1029 eq(cf.get("Foo", "bar10"),
(...skipping 26 matching lines...) Expand all
998 # default dictionary (OrderedDict) 1056 # default dictionary (OrderedDict)
999 cf.optionxform = lambda x: x 1057 cf.optionxform = lambda x: x
1000 cf.set('non-string', 1, 1) 1058 cf.set('non-string', 1, 1)
1001 self.assertEqual(cf.get('non-string', 1), 1) 1059 self.assertEqual(cf.get('non-string', 1), 1)
1002 1060
1003 class RawConfigParserTestCaseNonStandardDelimiters(RawConfigParserTestCase): 1061 class RawConfigParserTestCaseNonStandardDelimiters(RawConfigParserTestCase):
1004 delimiters = (':=', '$') 1062 delimiters = (':=', '$')
1005 comment_prefixes = ('//', '"') 1063 comment_prefixes = ('//', '"')
1006 inline_comment_prefixes = ('//', '"') 1064 inline_comment_prefixes = ('//', '"')
1007 1065
1008 class RawConfigParserTestSambaConf(CfgParserTestCaseClass): 1066 class RawConfigParserTestSambaConf(CfgParserTestCaseClass, unittest.TestCase):
1009 config_class = configparser.RawConfigParser 1067 config_class = configparser.RawConfigParser
1010 comment_prefixes = ('#', ';', '----') 1068 comment_prefixes = ('#', ';', '----')
1011 inline_comment_prefixes = ('//',) 1069 inline_comment_prefixes = ('//',)
1012 empty_lines_in_values = False 1070 empty_lines_in_values = False
1013 1071
1014 def test_reading(self): 1072 def test_reading(self):
1015 smbconf = support.findfile("cfgparser.2") 1073 smbconf = support.findfile("cfgparser.2")
1016 # check when we pass a mix of readable and non-readable files: 1074 # check when we pass a mix of readable and non-readable files:
1017 cf = self.newconfig() 1075 cf = self.newconfig()
1018 parsed_files = cf.read([smbconf, "nonexistent-file"], encoding='utf-8') 1076 parsed_files = cf.read([smbconf, "nonexistent-file"], encoding='utf-8')
1019 self.assertEqual(parsed_files, [smbconf]) 1077 self.assertEqual(parsed_files, [smbconf])
1020 sections = ['global', 'homes', 'printers', 1078 sections = ['global', 'homes', 'printers',
1021 'print$', 'pdf-generator', 'tmp', 'Agustin'] 1079 'print$', 'pdf-generator', 'tmp', 'Agustin']
1022 self.assertEqual(cf.sections(), sections) 1080 self.assertEqual(cf.sections(), sections)
1023 self.assertEqual(cf.get("global", "workgroup"), "MDKGROUP") 1081 self.assertEqual(cf.get("global", "workgroup"), "MDKGROUP")
1024 self.assertEqual(cf.getint("global", "max log size"), 50) 1082 self.assertEqual(cf.getint("global", "max log size"), 50)
1025 self.assertEqual(cf.get("global", "hosts allow"), "127.") 1083 self.assertEqual(cf.get("global", "hosts allow"), "127.")
1026 self.assertEqual(cf.get("tmp", "echo command"), "cat %s; rm %s") 1084 self.assertEqual(cf.get("tmp", "echo command"), "cat %s; rm %s")
1027 1085
1028 class ConfigParserTestCaseExtendedInterpolation(BasicTestCase): 1086 class ConfigParserTestCaseExtendedInterpolation(BasicTestCase, unittest.TestCase ):
1029 config_class = configparser.ConfigParser 1087 config_class = configparser.ConfigParser
1030 interpolation = configparser.ExtendedInterpolation() 1088 interpolation = configparser.ExtendedInterpolation()
1031 default_section = 'common' 1089 default_section = 'common'
1032 strict = True 1090 strict = True
1033 1091
1034 def fromstring(self, string, defaults=None, optionxform=None): 1092 def fromstring(self, string, defaults=None, optionxform=None):
1035 cf = self.newconfig(defaults) 1093 cf = self.newconfig(defaults)
1036 if optionxform: 1094 if optionxform:
1037 cf.optionxform = optionxform 1095 cf.optionxform = optionxform
1038 cf.read_string(string) 1096 cf.read_string(string)
(...skipping 153 matching lines...) Expand 10 before | Expand all | Expand 10 after
1192 cf['interpolation fail']['case4'] 1250 cf['interpolation fail']['case4']
1193 with self.assertRaises(configparser.InterpolationSyntaxError): 1251 with self.assertRaises(configparser.InterpolationSyntaxError):
1194 cf['interpolation fail']['case5'] 1252 cf['interpolation fail']['case5']
1195 with self.assertRaises(ValueError): 1253 with self.assertRaises(ValueError):
1196 cf['interpolation fail']['case6'] = "BLACK $ABBATH" 1254 cf['interpolation fail']['case6'] = "BLACK $ABBATH"
1197 1255
1198 1256
1199 class ConfigParserTestCaseNoValue(ConfigParserTestCase): 1257 class ConfigParserTestCaseNoValue(ConfigParserTestCase):
1200 allow_no_value = True 1258 allow_no_value = True
1201 1259
1202 class ConfigParserTestCaseTrickyFile(CfgParserTestCaseClass): 1260 class ConfigParserTestCaseTrickyFile(CfgParserTestCaseClass, unittest.TestCase):
1203 config_class = configparser.ConfigParser 1261 config_class = configparser.ConfigParser
1204 delimiters = {'='} 1262 delimiters = {'='}
1205 comment_prefixes = {'#'} 1263 comment_prefixes = {'#'}
1206 allow_no_value = True 1264 allow_no_value = True
1207 1265
1208 def test_cfgparser_dot_3(self): 1266 def test_cfgparser_dot_3(self):
1209 tricky = support.findfile("cfgparser.3") 1267 tricky = support.findfile("cfgparser.3")
1210 cf = self.newconfig() 1268 cf = self.newconfig()
1211 self.assertEqual(len(cf.read(tricky, encoding='utf-8')), 1) 1269 self.assertEqual(len(cf.read(tricky, encoding='utf-8')), 1)
1212 self.assertEqual(cf.sections(), ['strange', 1270 self.assertEqual(cf.sections(), ['strange',
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
1289 self.assertEqual(output.getvalue(), 1347 self.assertEqual(output.getvalue(),
1290 "[a]\n" 1348 "[a]\n"
1291 "k = v\n\n" 1349 "k = v\n\n"
1292 "[b]\n" 1350 "[b]\n"
1293 "o1 = 4\n" 1351 "o1 = 4\n"
1294 "o2 = 3\n" 1352 "o2 = 3\n"
1295 "o3 = 2\n" 1353 "o3 = 2\n"
1296 "o4 = 1\n\n") 1354 "o4 = 1\n\n")
1297 1355
1298 1356
1299 class CompatibleTestCase(CfgParserTestCaseClass): 1357 class CompatibleTestCase(CfgParserTestCaseClass, unittest.TestCase):
1300 config_class = configparser.RawConfigParser 1358 config_class = configparser.RawConfigParser
1301 comment_prefixes = '#;' 1359 comment_prefixes = '#;'
1302 inline_comment_prefixes = ';' 1360 inline_comment_prefixes = ';'
1303 1361
1304 def test_comment_handling(self): 1362 def test_comment_handling(self):
1305 config_string = textwrap.dedent("""\ 1363 config_string = textwrap.dedent("""\
1306 [Commented Bar] 1364 [Commented Bar]
1307 baz=qwe ; a comment 1365 baz=qwe ; a comment
1308 foo: bar # not a comment! 1366 foo: bar # not a comment!
1309 # but this is a comment 1367 # but this is a comment
1310 ; another comment 1368 ; another comment
1311 quirk: this;is not a comment 1369 quirk: this;is not a comment
1312 ; a space must precede an inline comment 1370 ; a space must precede an inline comment
1313 """) 1371 """)
1314 cf = self.fromstring(config_string) 1372 cf = self.fromstring(config_string)
1315 self.assertEqual(cf.get('Commented Bar', 'foo'), 1373 self.assertEqual(cf.get('Commented Bar', 'foo'),
1316 'bar # not a comment!') 1374 'bar # not a comment!')
1317 self.assertEqual(cf.get('Commented Bar', 'baz'), 'qwe') 1375 self.assertEqual(cf.get('Commented Bar', 'baz'), 'qwe')
1318 self.assertEqual(cf.get('Commented Bar', 'quirk'), 1376 self.assertEqual(cf.get('Commented Bar', 'quirk'),
1319 'this;is not a comment') 1377 'this;is not a comment')
1320 1378
1321 class CopyTestCase(BasicTestCase): 1379 class CopyTestCase(BasicTestCase, unittest.TestCase):
1322 config_class = configparser.ConfigParser 1380 config_class = configparser.ConfigParser
1323 1381
1324 def fromstring(self, string, defaults=None): 1382 def fromstring(self, string, defaults=None):
1325 cf = self.newconfig(defaults) 1383 cf = self.newconfig(defaults)
1326 cf.read_string(string) 1384 cf.read_string(string)
1327 cf_copy = self.newconfig() 1385 cf_copy = self.newconfig()
1328 cf_copy.read_dict(cf) 1386 cf_copy.read_dict(cf)
1329 # we have to clean up option duplicates that appeared because of 1387 # we have to clean up option duplicates that appeared because of
1330 # the magic DEFAULTSECT behaviour. 1388 # the magic DEFAULTSECT behaviour.
1331 for section in cf_copy.values(): 1389 for section in cf_copy.values():
(...skipping 21 matching lines...) Expand all
1353 def readline_generator(f): 1411 def readline_generator(f):
1354 """As advised in Doc/library/configparser.rst.""" 1412 """As advised in Doc/library/configparser.rst."""
1355 line = f.readline() 1413 line = f.readline()
1356 while line: 1414 while line:
1357 yield line 1415 yield line
1358 line = f.readline() 1416 line = f.readline()
1359 1417
1360 1418
1361 class ReadFileTestCase(unittest.TestCase): 1419 class ReadFileTestCase(unittest.TestCase):
1362 def test_file(self): 1420 def test_file(self):
1363 file_path = support.findfile("cfgparser.1") 1421 file_paths = [support.findfile("cfgparser.1")]
1364 parser = configparser.ConfigParser() 1422 try:
1365 with open(file_path) as f: 1423 file_paths.append(file_paths[0].encode('utf8'))
1366 parser.read_file(f) 1424 except UnicodeEncodeError:
1367 self.assertIn("Foo Bar", parser) 1425 pass # unfortunately we can't test bytes on this path
1368 self.assertIn("foo", parser["Foo Bar"]) 1426 for file_path in file_paths:
1369 self.assertEqual(parser["Foo Bar"]["foo"], "newbar") 1427 parser = configparser.ConfigParser()
1428 with open(file_path) as f:
1429 parser.read_file(f)
1430 self.assertIn("Foo Bar", parser)
1431 self.assertIn("foo", parser["Foo Bar"])
1432 self.assertEqual(parser["Foo Bar"]["foo"], "newbar")
1370 1433
1371 def test_iterable(self): 1434 def test_iterable(self):
1372 lines = textwrap.dedent(""" 1435 lines = textwrap.dedent("""
1373 [Foo Bar] 1436 [Foo Bar]
1374 foo=newbar""").strip().split('\n') 1437 foo=newbar""").strip().split('\n')
1375 parser = configparser.ConfigParser() 1438 parser = configparser.ConfigParser()
1376 parser.read_file(lines) 1439 parser.read_file(lines)
1377 self.assertIn("Foo Bar", parser) 1440 self.assertIn("Foo Bar", parser)
1378 self.assertIn("foo", parser["Foo Bar"]) 1441 self.assertIn("foo", parser["Foo Bar"])
1379 self.assertEqual(parser["Foo Bar"]["foo"], "newbar") 1442 self.assertEqual(parser["Foo Bar"]["foo"], "newbar")
1380 1443
1381 def test_readline_generator(self): 1444 def test_readline_generator(self):
1382 """Issue #11670.""" 1445 """Issue #11670."""
1383 parser = configparser.ConfigParser() 1446 parser = configparser.ConfigParser()
1384 with self.assertRaises(TypeError): 1447 with self.assertRaises(TypeError):
1385 parser.read_file(FakeFile()) 1448 parser.read_file(FakeFile())
1386 parser.read_file(readline_generator(FakeFile())) 1449 parser.read_file(readline_generator(FakeFile()))
1387 self.assertIn("Foo Bar", parser) 1450 self.assertIn("Foo Bar", parser)
1388 self.assertIn("foo", parser["Foo Bar"]) 1451 self.assertIn("foo", parser["Foo Bar"])
1389 self.assertEqual(parser["Foo Bar"]["foo"], "newbar") 1452 self.assertEqual(parser["Foo Bar"]["foo"], "newbar")
1453
1454 def test_source_as_bytes(self):
1455 """Issue #18260."""
1456 lines = textwrap.dedent("""
1457 [badbad]
1458 [badbad]""").strip().split('\n')
1459 parser = configparser.ConfigParser()
1460 with self.assertRaises(configparser.DuplicateSectionError) as dse:
1461 parser.read_file(lines, source=b"badbad")
1462 self.assertEqual(
1463 str(dse.exception),
1464 "While reading from b'badbad' [line 2]: section 'badbad' "
1465 "already exists"
1466 )
1467 lines = textwrap.dedent("""
1468 [badbad]
1469 bad = bad
1470 bad = bad""").strip().split('\n')
1471 parser = configparser.ConfigParser()
1472 with self.assertRaises(configparser.DuplicateOptionError) as dse:
1473 parser.read_file(lines, source=b"badbad")
1474 self.assertEqual(
1475 str(dse.exception),
1476 "While reading from b'badbad' [line 3]: option 'bad' in section "
1477 "'badbad' already exists"
1478 )
1479 lines = textwrap.dedent("""
1480 [badbad]
1481 = bad""").strip().split('\n')
1482 parser = configparser.ConfigParser()
1483 with self.assertRaises(configparser.ParsingError) as dse:
1484 parser.read_file(lines, source=b"badbad")
1485 self.assertEqual(
1486 str(dse.exception),
1487 "Source contains parsing errors: b'badbad'\n\t[line 2]: '= bad'"
1488 )
1489 lines = textwrap.dedent("""
1490 [badbad
1491 bad = bad""").strip().split('\n')
1492 parser = configparser.ConfigParser()
1493 with self.assertRaises(configparser.MissingSectionHeaderError) as dse:
1494 parser.read_file(lines, source=b"badbad")
1495 self.assertEqual(
1496 str(dse.exception),
1497 "File contains no section headers.\nfile: b'badbad', line: 1\n"
1498 "'[badbad'"
1499 )
1390 1500
1391 1501
1392 class CoverageOneHundredTestCase(unittest.TestCase): 1502 class CoverageOneHundredTestCase(unittest.TestCase):
1393 """Covers edge cases in the codebase.""" 1503 """Covers edge cases in the codebase."""
1394 1504
1395 def test_duplicate_option_error(self): 1505 def test_duplicate_option_error(self):
1396 error = configparser.DuplicateOptionError('section', 'option') 1506 error = configparser.DuplicateOptionError('section', 'option')
1397 self.assertEqual(error.section, 'section') 1507 self.assertEqual(error.section, 'section')
1398 self.assertEqual(error.option, 'option') 1508 self.assertEqual(error.option, 'option')
1399 self.assertEqual(error.source, None) 1509 self.assertEqual(error.source, None)
(...skipping 247 matching lines...) Expand 10 before | Expand all | Expand 10 after
1647 self.assertEqual(s['k4'], 'v4;still v4') 1757 self.assertEqual(s['k4'], 'v4;still v4')
1648 self.assertEqual(s['k5'], 'v5;still v5') 1758 self.assertEqual(s['k5'], 'v5;still v5')
1649 self.assertEqual(s['k6'], 'v6;still v6; and still v6') 1759 self.assertEqual(s['k6'], 'v6;still v6; and still v6')
1650 self.assertEqual(s['k7'], 'v7;still v7; and still v7') 1760 self.assertEqual(s['k7'], 'v7;still v7; and still v7')
1651 s = cfg['multiprefix'] 1761 s = cfg['multiprefix']
1652 self.assertEqual(s['k1'], 'v1;still v1') 1762 self.assertEqual(s['k1'], 'v1;still v1')
1653 self.assertEqual(s['k2'], 'v2') 1763 self.assertEqual(s['k2'], 'v2')
1654 self.assertEqual(s['k3'], 'v3;#//still v3# and still v3') 1764 self.assertEqual(s['k3'], 'v3;#//still v3# and still v3')
1655 1765
1656 1766
1657 def test_main(): 1767 if __name__ == '__main__':
1658 support.run_unittest( 1768 unittest.main()
1659 ConfigParserTestCase,
1660 ConfigParserTestCaseNonStandardDelimiters,
1661 ConfigParserTestCaseNoValue,
1662 ConfigParserTestCaseExtendedInterpolation,
1663 ConfigParserTestCaseLegacyInterpolation,
1664 ConfigParserTestCaseNoInterpolation,
1665 ConfigParserTestCaseTrickyFile,
1666 MultilineValuesTestCase,
1667 RawConfigParserTestCase,
1668 RawConfigParserTestCaseNonStandardDelimiters,
1669 RawConfigParserTestSambaConf,
1670 SortedTestCase,
1671 Issue7005TestCase,
1672 StrictTestCase,
1673 CompatibleTestCase,
1674 CopyTestCase,
1675 ConfigParserTestCaseNonStandardDefaultSection,
1676 ReadFileTestCase,
1677 CoverageOneHundredTestCase,
1678 ExceptionPicklingTestCase,
1679 InlineCommentStrippingTestCase,
1680 )
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+