File: pytap13.py

package info (click to toggle)
tarantool 2.6.0-1.4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 85,412 kB
  • sloc: ansic: 513,775; cpp: 69,493; sh: 25,650; python: 19,190; perl: 14,973; makefile: 4,178; yacc: 1,329; sql: 1,074; pascal: 620; ruby: 190; awk: 18; lisp: 7
file content (225 lines) | stat: -rw-r--r-- 7,697 bytes parent folder | download | duplicates (3)
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
# Copyright 2013, Red Hat, Inc.
#
# 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.
#
# Author: Josef Skladanka <jskladan@redhat.com>

import re
try:
    from CStringIO import StringIO
except ImportError:
    from StringIO import StringIO

import yaml


RE_VERSION = re.compile(r"^\s*TAP version 13\s*$")
RE_PLAN = re.compile(
    r"^\s*(?P<start>\d+)\.\.(?P<end>\d+)\s*(#\s*(?P<explanation>.*))?\s*$")
RE_TEST_LINE = re.compile(
    r"^\s*(?P<result>(not\s+)?ok)\s*(?P<id>\d+)?\s*(?P<description>[^#]+)?" +
    r"\s*(#\s*(?P<directive>TODO|SKIP)?\s*(?P<comment>.+)?)?\s*$",
    re.IGNORECASE)
RE_DIAGNOSTIC = re.compile(r"^\s*#\s*(?P<diagnostic>.+)?\s*$")
RE_YAMLISH_START = re.compile(r"^\s*---.*$")
RE_YAMLISH_END = re.compile(r"^\s*\.\.\.\s*$")


class Test(object):
    def __init__(self, result, id, description=None, directive=None,
                 comment=None):
        self.result = result
        self.id = id
        self.description = description
        try:
            self.directive = directive.upper()
        except AttributeError:
            self.directive = directive
        self.comment = comment
        self.yaml = None
        self._yaml_buffer = StringIO()
        self.diagnostics = []


class TAP13(object):
    def __init__(self, strict=False):
        self.tests = []
        self.__tests_counter = 0
        self.tests_planned = None
        self.strict = strict

    def _parse(self, source):
        seek_version = True
        seek_plan = False
        seek_test = False

        in_test = False
        in_yaml = False
        for line in source:
            if not seek_version and RE_VERSION.match(line):
                raise ValueError("Bad TAP format, multiple TAP headers")

            if in_yaml:
                if RE_YAMLISH_END.match(line):
                    test = self.tests[-1]
                    try:
                        test.yaml = yaml.safe_load(
                            test._yaml_buffer.getvalue())
                    except Exception as e:
                        if not self.strict:
                            continue
                        test_num = len(self.tests) + 1
                        comment = 'DIAG: Test %s has wrong YAML: %s' % (
                            test_num, str(e))
                        self.tests.append(Test('not ok', test_num,
                                               comment=comment))
                    in_yaml = False
                else:
                    self.tests[-1]._yaml_buffer.write(line)
                continue

            if in_test:
                if RE_DIAGNOSTIC.match(line):
                    self.tests[-1].diagnostics.append(line.strip())
                    continue
                if RE_YAMLISH_START.match(line):
                    in_yaml = True
                    continue

            on_top_level = not line.startswith('    ')
            raw_line = line.rstrip('\n')
            line = line.strip()

            if RE_DIAGNOSTIC.match(line):
                continue

            # this is "beginning" of the parsing, skip all lines until
            # version is found (in non-strict mode)
            if seek_version:
                m = RE_VERSION.match(line)
                if m:
                    seek_version = False
                    seek_plan = True
                    seek_test = True
                    continue
                elif not self.strict:
                    continue

            m = RE_PLAN.match(line)
            if m:
                if seek_plan and on_top_level:
                    d = m.groupdict()
                    self.tests_planned = int(d.get('end', 0))
                    seek_plan = False

                    # Stop processing if tests were found before the plan
                    #    if plan is at the end, it must be the last line
                    #    -> stop processing
                    if self.__tests_counter > 0:
                        break
                    continue
                elif not on_top_level:
                    continue

            if seek_test:
                m = RE_TEST_LINE.match(line)
                if m and on_top_level:
                    self.__tests_counter += 1
                    t_attrs = m.groupdict()
                    if t_attrs['id'] is None:
                        t_attrs['id'] = self.__tests_counter
                    t_attrs['id'] = int(t_attrs['id'])
                    if t_attrs['id'] < self.__tests_counter:
                        raise ValueError(
                            "Descending test id on line: %r" % line)
                    # according to TAP13 specs, missing tests must be handled
                    # as 'not ok'
                    # here we add the missing tests in sequence
                    while t_attrs['id'] > self.__tests_counter:
                        comment = 'DIAG: Test %s not present' % \
                            self.__tests_counter
                        self.tests.append(Test('not ok', self.__tests_counter,
                                               comment=comment))
                        self.__tests_counter += 1
                    t = Test(**t_attrs)
                    self.tests.append(t)
                    in_test = True
                    continue
                elif not on_top_level:
                    continue

            if self.strict:
                raise ValueError('Wrong TAP line: [' + raw_line + ']')

        if self.tests_planned is None:
            # TODO: raise better error than ValueError
            raise ValueError("Missing plan in the TAP source")

        if len(self.tests) != self.tests_planned:
            comment = 'DIAG: Expected %s tests, got %s' % \
                (self.tests_planned, len(self.tests))
            self.tests.append(Test('not ok', len(self.tests), comment=comment))

    def parse(self, source):
        if isinstance(source, (str, unicode)):
            self._parse(StringIO(source))
        elif hasattr(source, "__iter__"):
            self._parse(source)


if __name__ == "__main__":
    input = """
    TAP version 13
    ok 1 - Input file opened
    not ok 2 - First line of the input valid
        ---
        message: 'First line invalid'
        severity: fail
        data:
          got: 'Flirble'
          expect: 'Fnible'
        ...
    ok - Read the rest of the file
    not ok 5 - Summarized correctly # TODO Not written yet
        ---
        message: "Can't make summary yet"
        severity: todo
        ...
    ok  Description
    # Diagnostic
        ---
        message: 'Failure message'
        severity: fail
        data:
        got:
            - 1
            - 3
            - 2
        expect:
            - 1
            - 2
            - 3
    ...
    1..6
"""
    t = TAP13()
    t.parse(input)

    import pprint
    for test in t.tests:
        print(test.result, test.id, test.description, "#", test.directive,
              test.comment)
        pprint.pprint(test._yaml_buffer)
        pprint.pprint(test.yaml)