summaryrefslogtreecommitdiff
path: root/tests/scanner/annotationparser/test_parser.py
blob: ee1103c270b2f7d76aaa7156e8571c7d0dd1f34e (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
# -*- Mode: Python -*-
# GObject-Introspection - a framework for introspecting GObject libraries
# Copyright (C) 2012 Dieter Verfaillie <dieterv@optionexplicit.be>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#


'''
test_parser.py

Tests ensuring annotationparser.py continues to function correctly.
'''

import difflib
import os
import subprocess
import unittest
import xml.etree.ElementTree as etree

from giscanner.annotationparser import GtkDocCommentBlockParser, GtkDocCommentBlockWriter
from giscanner.ast import Namespace
from giscanner.message import MessageLogger


XML_NS = 'http://schemas.gnome.org/gobject-introspection/2013/test'
XML_SCHEMA = os.path.abspath(os.path.join(os.path.dirname(__file__), 'tests.xsd'))
XML_LINT = None


class ChunkedIO(object):
    def __init__(self):
        self.buffer = []

    def write(self, s):
        self.buffer.append(s)

    def getvalue(self):
        return self.buffer


def ns(x):
    return x.replace('{}', '{%s}' % (XML_NS, ))


def validate(tests_file):
    global XML_LINT

    try:
        cmd = ['xmllint', '--noout', '--nonet', '--schema', XML_SCHEMA, tests_file]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        stdout, stderr = p.communicate()
    except OSError:
        if XML_LINT is None:
            XML_LINT = False
            print('warning: xmllint not found, validation of test definition files will be skipped')
    else:
        if p.returncode != 0:
            raise SystemExit(stdout)


class TestCommentBlock(unittest.TestCase):
    @classmethod
    def __create_test__(cls, logger, testcase):
        def do_test(self):
            output = ChunkedIO()
            logger._output = output

            # Parse GTK-Doc comment block
            commentblock = testcase.find(ns('{}input')).text
            parsed_docblock = GtkDocCommentBlockParser().parse_comment_block(commentblock, 'test.c', 1)
            parsed_tree = self.parsed2tree(parsed_docblock).split('\n')
            emitted_messages = [w[w.find(':') + 1:].strip() for w in output.getvalue()]

            # Get expected parser output
            expected_docblock = testcase.find(ns('{}parser/{}docblock'))
            expected_tree = self.expected2tree(expected_docblock).split('\n')

            expected_messages = []
            for w in testcase.findall(ns('{}parser/{}messages/{}message')):
                expected_messages.append(w.text.strip())

            # Compare parsed with expected GtkDocCommentBlock
            msg = 'Parsed GtkDocCommentBlock object tree does not match expected output:\n\n'
            msg += '%s\n\n' % (commentblock, )

            diff = difflib.unified_diff(expected_tree, parsed_tree,
                                        'Expected GtkDocCommentBlock', 'Parsed GtkDocCommentBlock',
                                        n=max(len(expected_tree), len(parsed_tree)),
                                        lineterm='')
            for line in diff:
                msg += '%s\n' % (line, )

            self.assertTrue(parsed_tree == expected_tree, msg)

            # Compare emitted with expected messages
            msg = 'Emitted messages do not match expected messages:\n\n'
            msg += '%s\n\n' % (commentblock, )
            msg += self._diff_messages(expected_messages, emitted_messages)
            self.assertTrue(len(expected_messages) == len(emitted_messages), msg)

            for emitted_message, expected_message in zip(emitted_messages, expected_messages):
                msg = 'Emitted message does not match expected message:\n\n'
                msg += '%s\n\n' % (commentblock, )
                msg += self._diff_messages([expected_message], [emitted_message])
                self.assertTrue(expected_message == emitted_message, msg)

            # Compare serialized with expected comment block
            expected_serialized = testcase.find(ns('{}output'))
            indent = True

            if expected_serialized is None:
                expected_serialized = ''
            else:
                if 'indent' in expected_serialized.attrib:
                    indent = expected_serialized.attrib['indent']
                    if indent.lower() in ('false', '0'):
                        indent = False
                    elif indent.lower() in ('true', '1'):
                        indent = True
                    else:
                        self.assert_(False, 'Unknown value for "indent" attribute: %s' % (indent))

                expected_serialized = expected_serialized.text + '\n' or None

            commentblockwriter = GtkDocCommentBlockWriter(indent=indent)
            serialized = commentblockwriter.write(parsed_docblock)

            msg = 'Serialized comment block does not match expected output:\n\n'
            msg += self._diff_messages(expected_serialized.split('\n'), serialized.split('\n'))
            self.assertTrue(expected_serialized == serialized, msg)

        return do_test

    def parsed2tree(self, docblock):
        parsed = ''

        if docblock is not None:
            parsed += '<docblock>\n'

            parsed += '  <identifier>\n'
            parsed += '    <name>%s</name>\n' % (docblock.name, )
            if docblock.annotations:
                parsed += '    <annotations>\n'
                for ann_name, ann_options in docblock.annotations.items():
                    parsed += '      <annotation>\n'
                    parsed += '        <name>%s</name>\n' % (ann_name, )
                    if ann_options:
                        parsed += '        <options>\n'
                        if isinstance(ann_options, list):
                            for option in ann_options:
                                parsed += '          <option>\n'
                                parsed += '            <name>%s</name>\n' % (option, )
                                parsed += '          </option>\n'
                        else:
                            for (option, value) in ann_options.items():
                                parsed += '          <option>\n'
                                parsed += '            <name>%s</name>\n' % (option, )
                                if value:
                                    parsed += '            <value>%s</value>\n' % (value, )
                                parsed += '          </option>\n'
                        parsed += '        </options>\n'
                    parsed += '      </annotation>\n'
                parsed += '    </annotations>\n'
            parsed += '  </identifier>\n'

            if docblock.params:
                parsed += '  <parameters>\n'
                for param_name in docblock.params:
                    param = docblock.params.get(param_name)
                    parsed += '    <parameter>\n'
                    parsed += '      <name>%s</name>\n' % (param_name, )
                    if param.annotations:
                        parsed += '      <annotations>\n'
                        for ann_name, ann_options in param.annotations.items():
                            parsed += '        <annotation>\n'
                            parsed += '          <name>%s</name>\n' % (ann_name, )
                            if ann_options:
                                parsed += '          <options>\n'
                                if isinstance(ann_options, list):
                                    for option in ann_options:
                                        parsed += '            <option>\n'
                                        parsed += '              <name>%s</name>\n' % (option, )
                                        parsed += '            </option>\n'
                                else:
                                    for (option, value) in ann_options.items():
                                        parsed += '            <option>\n'
                                        parsed += '              <name>%s</name>\n' % (option, )
                                        if value:
                                            parsed += '              <value>%s</value>\n' % (value, )
                                        parsed += '            </option>\n'
                                parsed += '          </options>\n'
                            parsed += '        </annotation>\n'
                        parsed += '      </annotations>\n'
                    if param.description:
                        parsed += '      <description>%s</description>\n' % (param.description, )
                    parsed += '    </parameter>\n'
                parsed += '  </parameters>\n'

            if docblock.description:
                parsed += '  <description>%s</description>\n' % (docblock.description, )

            if docblock.tags:
                parsed += '  <tags>\n'
                for tag_name in docblock.tags:
                    tag = docblock.tags.get(tag_name)
                    parsed += '    <tag>\n'
                    parsed += '      <name>%s</name>\n' % (tag_name, )
                    if tag.annotations:
                        parsed += '      <annotations>\n'
                        for ann_name, ann_options in tag.annotations.items():
                            parsed += '        <annotation>\n'
                            parsed += '          <name>%s</name>\n' % (ann_name, )
                            if ann_options:
                                parsed += '          <options>\n'
                                if isinstance(ann_options, list):
                                    for option in ann_options:
                                        parsed += '            <option>\n'
                                        parsed += '              <name>%s</name>\n' % (option, )
                                        parsed += '            </option>\n'
                                else:
                                    for (option, value) in ann_options.items():
                                        parsed += '            <option>\n'
                                        parsed += '              <name>%s</name>\n' % (option, )
                                        if value:
                                            parsed += '              <value>%s</value>\n' % (value, )
                                        parsed += '            </option>\n'
                                parsed += '          </options>\n'
                            parsed += '        </annotation>\n'
                        parsed += '      </annotations>\n'
                    if tag.value:
                        parsed += '      <value>%s</value>\n' % (tag.value, )
                    if tag.description:
                        parsed += '      <description>%s</description>\n' % (tag.description, )
                    parsed += '    </tag>\n'
                parsed += '  </tags>\n'

            parsed += '</docblock>'

        return parsed

    def expected2tree(self, docblock):
        expected = ''

        if docblock is not None:
            expected += '<docblock>\n'

            if docblock.find(ns('{}identifier')) is not None:
                expected += '  <identifier>\n'
                expected += '    <name>%s</name>\n' % (docblock.find(ns('{}identifier/{}name')).text, )
                annotations = docblock.find(ns('{}identifier/{}annotations'))
                if annotations is not None:
                    expected += '    <annotations>\n'
                    for annotation in annotations.findall(ns('{}annotation')):
                        expected += '      <annotation>\n'
                        expected += '        <name>%s</name>\n' % (annotation.find(ns('{}name')).text, )
                        if annotation.find(ns('{}options')) is not None:
                            expected += '        <options>\n'
                            for option in annotation.findall(ns('{}options/{}option')):
                                expected += '          <option>\n'
                                if option.find(ns('{}name')) is not None:
                                    expected += '            <name>%s</name>\n' % (option.find(ns('{}name')).text, )
                                if option.find(ns('{}value')) is not None:
                                    expected += '            <value>%s</value>\n' % (option.find(ns('{}value')).text, )
                                expected += '          </option>\n'
                            expected += '        </options>\n'
                        expected += '      </annotation>\n'
                    expected += '    </annotations>\n'
                expected += '  </identifier>\n'

            parameters = docblock.find(ns('{}parameters'))
            if parameters is not None:
                expected += '  <parameters>\n'
                for parameter in parameters.findall(ns('{}parameter')):
                    expected += '    <parameter>\n'
                    expected += '      <name>%s</name>\n' % (parameter.find(ns('{}name')).text, )
                    annotations = parameter.find(ns('{}annotations'))
                    if annotations is not None:
                        expected += '      <annotations>\n'
                        for annotation in parameter.findall(ns('{}annotations/{}annotation')):
                            expected += '        <annotation>\n'
                            expected += '          <name>%s</name>\n' % (annotation.find(ns('{}name')).text, )
                            if annotation.find(ns('{}options')) is not None:
                                expected += '          <options>\n'
                                for option in annotation.findall(ns('{}options/{}option')):
                                    expected += '            <option>\n'
                                    if option.find(ns('{}name')) is not None:
                                        expected += '              <name>%s</name>\n' % (option.find(ns('{}name')).text, )
                                    if option.find(ns('{}value')) is not None:
                                        expected += '              <value>%s</value>\n' % (option.find(ns('{}value')).text, )
                                    expected += '            </option>\n'
                                expected += '          </options>\n'
                            expected += '        </annotation>\n'
                        expected += '      </annotations>\n'
                    if parameter.find(ns('{}description')) is not None:
                        expected += '      <description>%s</description>\n' % (parameter.find(ns('{}description')).text, )
                    expected += '    </parameter>\n'
                expected += '  </parameters>\n'

            description = docblock.find(ns('{}description'))
            if description is not None:
                expected += '  <description>%s</description>\n' % (description.text, )

            tags = docblock.find(ns('{}tags'))
            if tags is not None:
                expected += '  <tags>\n'
                for tag in tags.findall(ns('{}tag')):
                    expected += '    <tag>\n'
                    expected += '      <name>%s</name>\n' % (tag.find(ns('{}name')).text, )
                    annotations = tag.find(ns('{}annotations'))
                    if annotations is not None:
                        expected += '      <annotations>\n'
                        for annotation in tag.findall(ns('{}annotations/{}annotation')):
                            expected += '        <annotation>\n'
                            expected += '          <name>%s</name>\n' % (annotation.find(ns('{}name')).text, )
                            if annotation.find(ns('{}options')) is not None:
                                expected += '          <options>\n'
                                for option in annotation.findall(ns('{}options/{}option')):
                                    expected += '            <option>\n'
                                    if option.find(ns('{}name')) is not None:
                                        expected += '              <name>%s</name>\n' % (option.find(ns('{}name')).text, )
                                    if option.find(ns('{}value')) is not None:
                                        expected += '              <value>%s</value>\n' % (option.find(ns('{}value')).text, )
                                    expected += '            </option>\n'
                                expected += '          </options>\n'
                            expected += '        </annotation>\n'
                        expected += '      </annotations>\n'
                    if tag.find(ns('{}value')) is not None:
                        expected += '      <value>%s</value>\n' % (tag.find(ns('{}value')).text, )
                    if tag.find(ns('{}description')) is not None:
                        expected += '      <description>%s</description>\n' % (tag.find(ns('{}description')).text, )
                    expected += '    </tag>\n'
                expected += '  </tags>\n'

            expected += '</docblock>'

        return expected

    def _diff_messages(self, a, b):
        retval = ''
        started = False

        for group in difflib.SequenceMatcher(None, a, b).get_grouped_opcodes(3):
            if not started:
                started = True
                retval += '--- expected\n'
                retval += '+++ emitted\n'

            for tag, i1, i2, j1, j2 in group:
                if tag == 'equal':
                    for line in a[i1:i2]:
                        for l in line.split('\n'):
                            retval += ' ' + l + '\n'
                    continue

                if tag in ('replace', 'delete'):
                    for line in a[i1:i2]:
                        for l in line.split('\n'):
                            retval += '-' + l + '\n'

                if tag in ('replace', 'insert'):
                    for line in b[j1:j2]:
                        for l in line.split('\n'):
                            retval += '+' + l + '\n'

        return retval


def create_test_case(logger, tests_dir, tests_file):
    tests_tree = etree.parse(tests_file).getroot()

    fix_cdata_elements = tests_tree.findall(ns('{}test/{}input'))
    fix_cdata_elements += tests_tree.findall(ns('.//{}description'))
    fix_cdata_elements += tests_tree.findall(ns('{}test/{}output'))

    for element in fix_cdata_elements:
        if element.text:
            element.text = element.text.replace('{{?', '<!')
            element.text = element.text.replace('}}', '>')

    test_methods = {}
    for counter, test in enumerate(tests_tree.findall(ns('{}test'))):
        test_name = 'test_%03d' % (counter + 1)
        test_method = TestCommentBlock.__create_test__(logger, test)
        test_method.__name__ = test_name
        test_methods[test_name] = test_method

    # Dynamically generate a new subclass of TestCommentBlock in TitleCase
    # with generated test methods.
    test_class_name = os.path.relpath(tests_file[:-4], tests_dir)
    test_class_name = test_class_name.replace('/', ' ').replace('\\', ' ').replace('.', ' ')
    test_class_name = 'Test' + test_class_name.title().replace(' ', '')
    return type(test_class_name, (TestCommentBlock,), test_methods)


def create_test_cases():
    # Initialize message logger
    namespace = Namespace('Test', '1.0')
    logger = MessageLogger.get(namespace=namespace)
    logger.enable_warnings(True)
    test_cases = {}

    # Load test cases from disc
    tests_dir = os.path.dirname(os.path.abspath(__file__))

    for dirpath, dirnames, filenames in os.walk(tests_dir):
        for filename in filenames:
            tests_file = os.path.join(dirpath, filename)
            if os.path.basename(tests_file).endswith('.xml'):
                validate(tests_file)
                test_case = create_test_case(logger, tests_dir, tests_file)
                test_cases[test_case.__name__] = test_case

    return test_cases


# We currently need to push all the new test cases into the modules globals
# in order for parameterized tests to work. Ideally all that should be needed
# is the "load_tests" hook, but this does not work in the case were the tests
# are run in parameterized mode, e.g: python -m unittest test_parser.Test...
_all_tests = create_test_cases()
globals().update(_all_tests)


if __name__ == '__main__':
    unittest.main()