summaryrefslogtreecommitdiff
path: root/tests/test_ini.py
blob: 6a76edb447adcd998daee6ce061fe7db5d8e26dc (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
import unittest
from StringIO import StringIO

from iniparse import ini
from iniparse import compat
from iniparse import config

class test_section_line(unittest.TestCase):
    invalid_lines = [
        '# this is a comment',
        '; this is a comment',
        '  [sections must start on column1]',
        '[incomplete',
        '[ no closing ]brackets]',
        'ice-cream = mmmm',
        'ic[e-c]ream = mmmm',
        '[ice-cream] = mmmm',
        '-$%^',
    ]
    def test_invalid(self):
        for l in self.invalid_lines:
            p = ini.SectionLine.parse(l)
            self.assertEqual(p, None)

    lines = [
        ('[section]' ,          ('section', None, None, -1)),
        ('[se\ct%[ion\t]' ,     ('se\ct%[ion\t', None, None, -1)),
        ('[sec tion]  ; hi' ,   ('sec tion', ' hi', ';', 12)),
        ('[section]  #oops!' ,  ('section', 'oops!', '#', 11)),
        ('[section]   ;  ' ,    ('section', '', ';', 12)),
        ('[section]      ' ,    ('section', None, None, -1)),
    ]
    def test_parsing(self):
        for l in self.lines:
            p = ini.SectionLine.parse(l[0])
            self.assertNotEqual(p, None)
            self.assertEqual(p.name, l[1][0])
            self.assertEqual(p.comment, l[1][1])
            self.assertEqual(p.comment_separator, l[1][2])
            self.assertEqual(p.comment_offset, l[1][3])

    def test_printing(self):
        for l in self.lines:
            p = ini.SectionLine.parse(l[0])
            self.assertEqual(str(p), l[0])
            self.assertEqual(p.to_string(), l[0].strip())

    indent_test_lines = [
        ('[oldname]             ; comment', 'long new name',
         '[long new name]       ; comment'),
        ('[oldname]             ; comment', 'short',
         '[short]               ; comment'),
        ('[oldname]             ; comment', 'really long new name',
         '[really long new name] ; comment'),
    ]
    def test_preserve_indentation(self):
        for l in self.indent_test_lines:
            p = ini.SectionLine.parse(l[0])
            p.name = l[1]
            self.assertEqual(str(p), l[2])

class test_option_line(unittest.TestCase):
    lines = [
        ('option = value', 'option', ' = ', 'value', None, None, -1),
        ('option:   value', 'option', ':   ', 'value', None, None, -1),
        ('option=value', 'option', '=', 'value', None, None, -1),
        ('op[ti]on=value', 'op[ti]on', '=', 'value', None, None, -1),

        ('option = value # no comment', 'option', ' = ', 'value # no comment',
                                         None, None, -1),
        ('option = value     ;', 'option', ' = ', 'value',
                                         ';', '', 19),
        ('option = value     ; comment', 'option', ' = ', 'value',
                                         ';', ' comment', 19),
        ('option = value;1   ; comment', 'option', ' = ', 'value;1   ; comment',
                                         None, None, -1),
        ('op;ti on = value      ;; comm;ent', 'op;ti on', ' = ', 'value',
                                         ';', '; comm;ent', 22),
    ]
    def test_parsing(self):
        for l in self.lines:
            p = ini.OptionLine.parse(l[0])
            self.assertEqual(p.name, l[1])
            self.assertEqual(p.separator, l[2])
            self.assertEqual(p.value, l[3])
            self.assertEqual(p.comment_separator, l[4])
            self.assertEqual(p.comment, l[5])
            self.assertEqual(p.comment_offset, l[6])

    invalid_lines = [
        '  option = value',
        '# comment',
        '; comment',
        '[section 7]',
        '[section=option]',
        'option',
    ]
    def test_invalid(self):
        for l in self.invalid_lines:
            p = ini.OptionLine.parse(l)
            self.assertEqual(p, None)

    print_lines = [
        'option = value',
        'option= value',
        'option : value',
        'option: value  ',
        'option   =    value  ',
        'option = value   ;',
        'option = value;2    ;; 4 5',
        'option = value     ; hi!',
    ]
    def test_printing(self):
        for l in self.print_lines:
            p = ini.OptionLine.parse(l)
            self.assertEqual(str(p), l)
            self.assertEqual(p.to_string(), l.rstrip())

    indent_test_lines = [
        ('option = value   ;comment', 'newoption', 'newval',
         'newoption = newval ;comment'),
        ('option = value       ;comment', 'newoption', 'newval',
         'newoption = newval   ;comment'),
    ]
    def test_preserve_indentation(self):
        for l in self.indent_test_lines:
            p = ini.OptionLine.parse(l[0])
            p.name = l[1]
            p.value = l[2]
            self.assertEqual(str(p), l[3])

class test_comment_line(unittest.TestCase):
    invalid_lines = [
        '[section]',
        'option = value ;comment',
        '  # must start on first column',
    ]
    def test_invalid(self):
        for l in self.invalid_lines:
            p = ini.CommentLine.parse(l)
            self.assertEqual(p, None)

    lines = [
        '#this is a comment',
        ';; this is also a comment',
        '; so is this   ',
        'Rem and this',
        'remthis too!'
    ]
    def test_parsing(self):
        for l in self.lines:
            p = ini.CommentLine.parse(l)
            self.assertEqual(str(p), l)
            self.assertEqual(p.to_string(), l.rstrip())

class test_other_lines(unittest.TestCase):
    def test_empty(self):
        for s in ['asdf', '; hi', '  #rr', '[sec]', 'opt=val']:
            self.assertEqual(ini.EmptyLine.parse(s), None)
        for s in ['', '  ', '\t  \t']:
            self.assertEqual(str(ini.EmptyLine.parse(s)), s)

    def test_continuation(self):
        for s in ['asdf', '; hi', '[sec]', 'a=3']:
            self.assertEqual(ini.ContinuationLine.parse(s), None)
        for s in [' asdfasd ', '\t mmmm']:
            self.assertEqual(ini.ContinuationLine.parse(s).value,
                             s.strip())
            self.assertEqual(ini.ContinuationLine.parse(s).to_string(),
                             s.rstrip().replace('\t',' '))


class test_ini(unittest.TestCase):
    s1 = """
[section1]
help = me
I'm  = desperate     ; really!

[section2]
# comment and empty line before the first option

just = what?
just = kidding

[section1]
help = yourself
but = also me
"""

    def test_basic(self):
        sio = StringIO(self.s1)
        p = ini.INIConfig(sio)
        self.assertEqual(str(p), self.s1)
        self.assertEqual(p._data.find('section1').find('but').value, 'also me')
        self.assertEqual(p._data.find('section1').find('help').value, 'yourself')
        self.assertEqual(p._data.find('section2').find('just').value, 'kidding')

        itr = p._data.finditer('section1')
        v = itr.next()
        self.assertEqual(v.find('help').value, 'yourself')
        self.assertEqual(v.find('but').value, 'also me')
        v = itr.next()
        self.assertEqual(v.find('help').value, 'me')
        self.assertEqual(v.find('I\'m').value, 'desperate')
        self.assertRaises(StopIteration, itr.next)

        self.assertRaises(KeyError, p._data.find, 'section')
        self.assertRaises(KeyError, p._data.find('section2').find, 'ahem')

    def test_lookup(self):
        sio = StringIO(self.s1)
        p = ini.INIConfig(sio)
        self.assertEqual(p.section1.help, 'yourself')
        self.assertEqual(p.section1.but, 'also me')
        self.assertEqual(getattr(p.section1, 'I\'m'), 'desperate')
        self.assertEqual(p.section2.just, 'kidding')

        self.assertEqual(p.section1.just.__class__, config.Undefined)
        self.assertEqual(p.section2.help.__class__, config.Undefined)

    def test_newsection(self):
        sio = StringIO(self.s1)
        p = ini.INIConfig(sio)
        p.new1.created = 1
        setattr(getattr(p, 'new2'), 'created', 1)
        p.new3['created'] = 1
        p['new4'].created = 1
        p['new5']['created'] = 1
        self.assertEqual(p.new1.created, 1)
        self.assertEqual(p.new2.created, 1)
        self.assertEqual(p.new3.created, 1)
        self.assertEqual(p.new4.created, 1)
        self.assertEqual(p.new5.created, 1)

    def test_order(self):
        sio = StringIO(self.s1)
        p = ini.INIConfig(sio)
        self.assertEqual(list(p), ['section1','section2'])
        self.assertEqual(list(p.section1), ['help', "i'm", 'but'])
        self.assertEqual(list(p.section2), ['just'])

    def test_delete(self):
        sio = StringIO(self.s1)
        p = ini.INIConfig(sio)
        del p.section1.help
        self.assertEqual(list(p.section1), ["i'm", 'but'])
        self.assertEqual(str(p), """
[section1]
I'm  = desperate     ; really!

[section2]
# comment and empty line before the first option

just = what?
just = kidding

[section1]
but = also me
""")
        del p.section2
        self.assertEqual(str(p), """
[section1]
I'm  = desperate     ; really!


[section1]
but = also me
""")

    def check_order(self, c):
        sio = StringIO(self.s1)
        c = c({'pi':'3.14153'})
        c.readfp(sio)
        self.assertEqual(c.sections(), ['section1','section2'])
        self.assertEqual(c.options('section1'), ['help', "i'm", 'but', 'pi'])
        self.assertEqual(c.items('section1'), [
            ('help', 'yourself'),
            ("i'm", 'desperate'),
            ('but', 'also me'),
            ('pi', '3.14153'),
        ])

    def test_compat_order(self):
        self.check_order(compat.RawConfigParser)
        self.check_order(compat.ConfigParser)

    inv = (
("""
# values must be in a section
value = 5
""",
"""
# values must be in a section
#value = 5
"""),
("""
# continuation lines only allowed after options
[section]
op1 = qwert
    yuiop
op2 = qwert

    yuiop
op3 = qwert
# yup
    yuiop

[another section]
    hmmm
""",
"""
# continuation lines only allowed after options
[section]
op1 = qwert
    yuiop
op2 = qwert

    yuiop
op3 = qwert
# yup
    yuiop

[another section]
#    hmmm
"""))

    def test_invalid(self):
        for (org, mod) in self.inv:
            ip = ini.INIConfig(StringIO(org), parse_exc=False)
            self.assertEqual(str(ip), mod)

    # test multi-line values
    s2 = (
"""
[section]
option =
  foo
  bar

  baz
  yam
"""
)

    s3 = (
"""
[section]
option =
  foo
  bar
  mum

  baz
  yam
"""
)

    def test_option_continuation(self):
        ip = ini.INIConfig(StringIO(self.s2))
        self.assertEqual(str(ip), self.s2)
        value = ip.section.option.split('\n')
        value.insert(3, 'mum')
        ip.section.option = '\n'.join(value)
        self.assertEqual(str(ip), self.s3)

    s5 = (
"""
[section]
option =
  foo
  bar
"""
)

    s6 = (
"""
[section]
option =


  foo



another = baz
"""
)

    def test_option_continuation_single(self):
        ip = ini.INIConfig(StringIO(self.s5))
        self.assertEqual(str(ip), self.s5)
        ip.section.option = '\n'.join(['', '', '', 'foo', '', '', ''])
        ip.section.another = 'baz'
        self.assertEqual(str(ip), self.s6)


class suite(unittest.TestSuite):
    def __init__(self):
        unittest.TestSuite.__init__(self, [
                unittest.makeSuite(test_section_line, 'test'),
                unittest.makeSuite(test_option_line, 'test'),
                unittest.makeSuite(test_comment_line, 'test'),
                unittest.makeSuite(test_other_lines, 'test'),
                unittest.makeSuite(test_ini, 'test'),
        ])