summaryrefslogtreecommitdiff
path: root/tests/test_misc.py
blob: 31cf4dae5516b2165c84214a8448c5c315900507 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import re
import unittest
import pickle
import ConfigParser
from textwrap import dedent
from StringIO import StringIO
from iniparse import compat, ini

class CaseSensitiveConfigParser(compat.ConfigParser):
    """Case Sensitive version of ConfigParser"""
    def optionxform(self, option):
        """Use str()"""
        return str(option)

class test_optionxform_override(unittest.TestCase):
    def test_derivedclass(self):
        c = CaseSensitiveConfigParser()
        c.add_section('foo')
        c.set('foo', 'bar', 'a')
        c.set('foo', 'Bar', 'b')
        self.assertEqual(c.get('foo', 'bar'), 'a')
        self.assertEqual(c.get('foo', 'Bar'), 'b')

    def test_assignment(self):
        c = compat.ConfigParser()
        c.optionxform = str
        c.add_section('foo')
        c.set('foo', 'bar', 'a')
        c.set('foo', 'Bar', 'b')
        self.assertEqual(c.get('foo', 'bar'), 'a')
        self.assertEqual(c.get('foo', 'Bar'), 'b')

    def test_dyanamic(self):
        c = compat.ConfigParser()
        c.optionxform = str
        c.add_section('foo')
        c.set('foo', 'bar', 'a')
        c.set('foo', 'Bar', 'b')
        c.set('foo', 'BAR', 'c')
        c.optionxform = str.upper
        self.assertEqual(c.get('foo', 'Bar'), 'c')
        c.optionxform = str.lower
        self.assertEqual(c.get('foo', 'Bar'), 'a')
        c.optionxform = str
        self.assertEqual(c.get('foo', 'Bar'), 'b')


class OnlyReadline:
    def __init__(self, s):
        self.sio = StringIO(s)

    def readline(self):
        return self.sio.readline()

class test_readline(unittest.TestCase):
    """Test that the file object passed to readfp only needs to
    support the .readline() method.  As of Python-2.4.4, this is
    true of the standard librariy's ConfigParser, and so other
    code uses that to guide what is sufficiently file-like."""

    test_strings = [
"""\
[foo]
bar=7
baz=8""",
"""\
[foo]
bar=7
baz=8
""",
"""\
[foo]
bar=7
baz=8
    """]

    def test_readline_iniconfig(self):
        for s in self.test_strings:
            fp = OnlyReadline(s)
            c = ini.INIConfig()
            c._readfp(fp)
            self.assertEqual(s, str(c))

    def test_readline_configparser(self):
        for s in self.test_strings:
            fp = OnlyReadline(s)
            c = compat.ConfigParser()
            c.readfp(fp)
            ss = StringIO()
            c.write(ss)
            self.assertEqual(s, ss.getvalue())


class test_multiline_with_comments(unittest.TestCase):
    """Test that multiline values are allowed to span comments."""

    s = """\
[sec]
opt = 1
 2

# comment
 3"""

    def test_read(self):
        c = ini.INIConfig()
        c._readfp(StringIO(self.s))
        self.assertEqual(c.sec.opt, '1\n2\n\n3')

    def test_write(self):
        c = ini.INIConfig()
        c._readfp(StringIO(self.s))
        c.sec.opt = 'xyz'
        self.assertEqual(str(c), """\
[sec]
opt = xyz""")

class test_empty_file(unittest.TestCase):
    """Test if it works with an blank file"""

    s = ""

    def test_read(self):
        c = ini.INIConfig()
        c._readfp(StringIO(self.s))
        self.assertEqual(str(c), '')

    def test_write(self):
        c = ini.INIConfig()
        c._readfp(StringIO(self.s))
        c.sec.opt = 'xyz'
        self.assertEqual(str(c), """\
[sec]
opt = xyz""")

class test_custom_dict(unittest.TestCase):
    def test_custom_dict_not_supported(self):
        self.assertRaises(ValueError, compat.RawConfigParser, None, 'foo')

class test_compat(unittest.TestCase):
    """Miscellaneous compatibility tests."""

    s = dedent("""\
        [DEFAULT]
        pi = 3.1415
        three = 3
        poet = e e

             cummings
        NH =
         live free

         or die

        [sec]
        opt = 6
        three = 3.0
        no-three = one
         two

         four
        longopt = foo
         bar

        # empty line should not be part of value
         baz

         bat

        """)

    def do_test(self, c):
        # default section is not acknowledged
        self.assertEqual(c.sections(), ['sec'])
        # options in the default section are merged with other sections
        self.assertEqual(sorted(c.options('sec')),
                         ['longopt', 'nh', 'no-three', 'opt', 'pi', 'poet', 'three'])

        # empty lines are stripped from multi-line values
        self.assertEqual(c.get('sec', 'poet').split('\n'),
                         ['e e', 'cummings'])
        self.assertEqual(c.get('DEFAULT', 'poet').split('\n'),
                         ['e e', 'cummings'])
        self.assertEqual(c.get('sec', 'longopt').split('\n'),
                         ['foo', 'bar', 'baz', 'bat'])
        self.assertEqual(c.get('sec', 'NH').split('\n'),
                         ['', 'live free', 'or die'])

        # check that empy-line stripping happens on all access paths
        # defaults()
        self.assertEqual(c.defaults(), {
            'poet': 'e e\ncummings',
            'nh': '\nlive free\nor die',
            'pi': '3.1415',
            'three': '3',
        })
        # items()
        l = c.items('sec')
        l.sort()
        self.assertEqual(l, [
            ('longopt', 'foo\nbar\nbaz\nbat'),
            ('nh', '\nlive free\nor die'),
            ('no-three', 'one\ntwo\nfour'),
            ('opt', '6'),
            ('pi', '3.1415'),
            ('poet', 'e e\ncummings'),
            ('three', '3.0'),
        ])

        # empty lines are preserved on explicitly set values
        c.set('sec', 'longopt', '\n'.join(['a', 'b', '', 'c', '', '', 'd']))
        c.set('DEFAULT', 'NH', '\nlive free\n\nor die')
        self.assertEqual(c.get('sec', 'longopt').split('\n'),
                         ['a', 'b', '', 'c', '', '', 'd'])
        self.assertEqual(c.get('sec', 'NH').split('\n'),
                         ['', 'live free', '', 'or die'])
        self.assertEqual(c.defaults(), {
            'poet': 'e e\ncummings',
            'nh': '\nlive free\n\nor die',
            'pi': '3.1415',
            'three': '3',
        })
        # items()
        l = c.items('sec')
        l.sort()
        self.assertEqual(l, [
            ('longopt', 'a\nb\n\nc\n\n\nd'),
            ('nh', '\nlive free\n\nor die'),
            ('no-three', 'one\ntwo\nfour'),
            ('opt', '6'),
            ('pi', '3.1415'),
            ('poet', 'e e\ncummings'),
            ('three', '3.0'),
        ])

        # empty line special magic goes away after remove_option()
        self.assertEqual(c.get('sec', 'no-three').split('\n'),
                         ['one', 'two','four'])
        c.remove_option('sec', 'no-three')
        c.set('sec', 'no-three', 'q\n\nw')
        self.assertEqual(c.get('sec', 'no-three'), 'q\n\nw')
        c.remove_option('sec', 'no-three')

    def do_configparser_test(self, cfg_class):
        c = cfg_class()
        c.readfp(StringIO(self.s))
        self.do_test(c)
        o = StringIO()
        c.write(o)
        self.assertEqual(o.getvalue().split('\n'), [
            '[DEFAULT]',
            'poet = e e',
            '\tcummings',
            'nh = ',
            '\tlive free',
            '\t',
            '\tor die',
            'pi = 3.1415',
            'three = 3',
            '',
            '[sec]',
            'opt = 6',
            'longopt = a',
            '\tb',
            '\t',
            '\tc',
            '\t',
            '\t',
            '\td',
            'three = 3.0',
            '',
            ''])

    def test_py_rawcfg(self):
        self.do_configparser_test(ConfigParser.RawConfigParser)

    def test_py_cfg(self):
        self.do_configparser_test(ConfigParser.ConfigParser)

    def test_py_safecfg(self):
        self.do_configparser_test(ConfigParser.SafeConfigParser)

    def do_compat_test(self, cfg_class):
        c = cfg_class()
        c.readfp(StringIO(self.s))
        self.do_test(c)
        o = StringIO()
        c.write(o)
        self.assertEqual(o.getvalue().split('\n'), [
            '[DEFAULT]',
            'pi = 3.1415',
            'three = 3',
            'poet = e e',
            '',
            '     cummings',
            'NH =',
            ' live free',
            '',
            ' or die',
            '',
            '[sec]',
            'opt = 6',
            'three = 3.0',
            'longopt = a',
            ' b',
            '',
            ' c',
            '',
            '',
            ' d',
            '',
            ''])

    def test_py_rawcfg(self):
        self.do_compat_test(compat.RawConfigParser)

    def test_py_cfg(self):
        self.do_compat_test(compat.ConfigParser)

    def test_py_safecfg(self):
        self.do_compat_test(compat.SafeConfigParser)

class test_pickle(unittest.TestCase):
    s = dedent("""\
        [DEFAULT]
        pi = 3.1415
        three = 3
        poet = e e

             cummings
        NH =
         live free

         or die

        [sec]
        opt = 6
        three = 3.0
        no-three = one
         two

         four

        james = bond
        """)

    def do_compat_checks(self, c):
        self.assertEqual(c.sections(), ['sec'])
        self.assertEqual(sorted(c.options('sec')),
                         ['james', 'nh', 'no-three', 'opt', 'pi', 'poet', 'three'])
        self.assertEqual(c.defaults(), {
            'poet': 'e e\ncummings',
            'nh': '\nlive free\nor die',
            'pi': '3.1415',
            'three': '3',
        })
        l = c.items('sec')
        l.sort()
        self.assertEqual(l, [
            ('james', 'bond'),
            ('nh', '\nlive free\nor die'),
            ('no-three', 'one\ntwo\nfour'),
            ('opt', '6'),
            ('pi', '3.1415'),
            ('poet', 'e e\ncummings'),
            ('three', '3.0'),
        ])
        self.do_ini_checks(c.data)

    def do_ini_checks(self, c):
        self.assertEqual(list(c), ['sec'])
        self.assertEqual(sorted(c['sec']), ['james', 'nh', 'no-three', 'opt', 'pi', 'poet', 'three'])
        self.assertEqual(c._defaults['pi'], '3.1415')
        self.assertEqual(c.sec.opt, '6')
        self.assertEqual(c.sec.three, '3.0')
        self.assertEqual(c.sec['no-three'], 'one\ntwo\n\nfour')
        self.assertEqual(c.sec.james, 'bond')
        self.assertEqual(c.sec.pi, '3.1415')
        self.assertEqual(c.sec.poet, 'e e\n\ncummings')
        self.assertEqual(c.sec.NH, '\nlive free\n\nor die')
        self.assertEqual(str(c), self.s)

    def test_compat(self):
        for cfg_class in (compat.ConfigParser, compat.RawConfigParser, compat.SafeConfigParser):
            c = cfg_class()
            c.readfp(StringIO(self.s))
            self.do_compat_checks(c)
            for i in range(0, pickle.HIGHEST_PROTOCOL+1):
                p = pickle.dumps(c, protocol=i)
                c2 = pickle.loads(p)
                self.do_compat_checks(c2)

    def test_ini(self):
        c = ini.INIConfig()
        c._readfp(StringIO(self.s))
        self.do_ini_checks(c)
        for i in range(0, pickle.HIGHEST_PROTOCOL+1):
            p = pickle.dumps(c, protocol=i)
            c2 = pickle.loads(p)
            self.do_ini_checks(c2)

class test_comment_syntax(unittest.TestCase):
    """Test changing comment syntax with change_comment_syntax"""

    def test_regex(self):
        # original regular expression
        org_regex = re.compile(r'^(?P<csep>[;#]|[rR][eE][mM])(?P<comment>.*)$')
        ini.change_comment_syntax(';#', True)
        self.assertEqual(ini.CommentLine.regex, org_regex)
        
        # mercurial-safe comment line regex, as given by Steve Borho & Paul Lambert
        # bitbucket.org/tortoisehg/stable/src/tip/tortoisehg/hgtk/thgconfig.py#cl-1084
        # http://groups.google.com/group/iniparse-discuss/msg/b41a54aa185a9b7c
        hg_regex = re.compile(r'^(?P<csep>[%;#])(?P<comment>.*)$')
        ini.change_comment_syntax('%;#', False)
        self.assertEqual(ini.CommentLine.regex, hg_regex)

        # change_comment_syntax() defaults to hg regex
        ini.change_comment_syntax()
        self.assertEqual(ini.CommentLine.regex, hg_regex)

        # test escaping of special chars in pattern
        regex = re.compile(r'^(?P<csep>[;#\-\^[\]])(?P<comment>.*)$')
        ini.change_comment_syntax(';#-^[]')
        self.assertEqual(ini.CommentLine.regex, regex)

    def test_ignore_includes(self):
        ini.change_comment_syntax()
        cfg = ini.INIConfig(StringIO(dedent("""
            # This is a mercurial-style config
            % include foobar

            [ui]
            username = Firstname Lastname <a@b.c>
            """)))
        self.assertEqual(cfg.ui.username, 'Firstname Lastname <a@b.c>')
        self.assertEqual(str(cfg), dedent("""
            # This is a mercurial-style config
            % include foobar

            [ui]
            username = Firstname Lastname <a@b.c>
            """))

    def tearDown(self):
        ini.change_comment_syntax(';#', True)


class suite(unittest.TestSuite):
    def __init__(self):
        unittest.TestSuite.__init__(self, [
                unittest.makeSuite(test_optionxform_override, 'test'),
                unittest.makeSuite(test_readline, 'test'),
                unittest.makeSuite(test_multiline_with_comments, 'test'),
                unittest.makeSuite(test_empty_file, 'test'),
                unittest.makeSuite(test_custom_dict, 'test'),
                unittest.makeSuite(test_compat, 'test'),
                unittest.makeSuite(test_pickle, 'test'),
                unittest.makeSuite(test_comment_syntax, 'test'),
    ])