testing.py 12 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""testing.py - test support for DHParser based grammars and compilers

Copyright 2016  by Eckhart Arnold (arnold@badw.de)
                Bavarian Academy of Sciences an Humanities (badw.de)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.  See the License for the specific language governing
permissions and limitations under the License.
"""
18
import collections
19
import configparser
20
import copy
di68kap's avatar
di68kap committed
21
import inspect
22
23
import json
import os
24
25
26
27
try:
    import regex as re
except ImportError:
    import re
28

29
from DHParser import error_messages
30
from DHParser.toolkit import is_logging
Eckhart Arnold's avatar
Eckhart Arnold committed
31
from DHParser.syntaxtree import mock_syntax_tree, oneliner_sxpr
32

33
__all__ = ('unit_from_configfile',
34
35
36
37
38
39
40
           'unit_from_json',
           'unit_from_file',
           'get_report',
           'grammar_unit',
           'grammar_suite',
           'runner')

41
UNIT_STAGES = {'match', 'fail', 'ast', 'cst', '__ast__', '__cst__'}
42
43


44
def unit_from_configfile(config_filename):
45
46
    """
    Reads a grammar unit test from a config file.
47
    """
48
    cfg = configparser.ConfigParser(interpolation=None)
49
    cfg.read(config_filename)
50
51
    OD = collections.OrderedDict
    unit = OD()
52
53
    for section in cfg.sections():
        symbol, stage = section.split(':')
54
55
        if stage not in UNIT_STAGES:
            if symbol in UNIT_STAGES:
56
57
                symbol, stage = stage, symbol
            else:
58
                raise ValueError('Test stage %s not in: ' % (stage, str(UNIT_STAGES)))
59
        for testkey, testcode in cfg[section].items():
60
61
62
63
            if testcode[:3] + testcode[-3:] in {"''''''", '""""""'}:
                testcode = testcode[3:-3]
            elif testcode[:1] + testcode[-1:] in {"''", '""'}:
                testcode = testcode[1:-1]
64
            unit.setdefault(symbol, OD()).setdefault(stage, OD())[testkey] = testcode
65
66
    # print(json.dumps(unit, sort_keys=True, indent=4))
    return unit
67

68

69
def unit_from_json(json_filename):
70
71
    """
    Reads a grammar unit test from a json file.
72
    """
73
    with open(json_filename, 'r') as f:
74
75
76
77
78
79
80
        unit = json.load(f)
    for symbol in unit:
        for stage in unit[symbol]:
            if stage not in UNIT_STAGES:
                raise ValueError('Test stage %s not in: ' % (stage, str(UNIT_STAGES)))
    return unit

81
# TODO: add support for yaml, cson, toml
82
83


84
def unit_from_file(filename):
85
86
    """
    Reads a grammar unit test from a file. The format of the file is
87
88
    determined by the ending of its name.
    """
89
90
91
92
    if filename.endswith(".json"):
        return unit_from_json(filename)
    elif filename.endswith(".ini"):
        return unit_from_configfile(filename)
93
    else:
94
        raise ValueError("Unknown unit test file type: " + filename[filename.rfind('.'):])
95
96


97
def get_report(test_unit):
98
99
    """
    Returns a text-report of the results of a grammar unit test.
100
    """
101
102
103
104
    def indent(txt):
        lines = txt.split('\n')
        lines[0] = '    ' + lines[0]
        return "\n    ".join(lines)
105
106
107
108
109
110
111
112
    report = []
    for parser_name, tests in test_unit.items():
        heading = 'Test of parser: "%s"' % parser_name
        report.append('\n\n%s\n%s\n' % (heading, '=' * len(heading)))
        for test_name, test_code in tests.get('match', dict()).items():
            heading = 'Match-test "%s"' % test_name
            report.append('\n%s\n%s\n' % (heading, '-' * len(heading)))
            report.append('### Test-code:')
113
            report.append(indent(test_code))
114
115
116
117
118
            error = tests.get('__err__', {}).get(test_name, "")
            if error:
                report.append('\n### Error:')
                report.append(error)
            ast = tests.get('__ast__', {}).get(test_name, None)
119
120
121
            cst = tests.get('__cst__', {}).get(test_name, None)
            if cst and (not ast or cst == ast):
                report.append('\n### CST')
122
                report.append(indent(cst.as_sxpr()))
123
            elif ast:
124
                report.append('\n### AST')
125
                report.append(indent(ast.as_sxpr()))
126
127
128
    return '\n'.join(report)


129
def grammar_unit(test_unit, parser_factory, transformer_factory, report=True, verbose=False):
130
131
    """
    Unit tests for a grammar-parser and ast transformations.
132
    """
133
    if isinstance(test_unit, str):
134
        unit_dir, unit_name = os.path.split(os.path.splitext(test_unit)[0])
135
        test_unit = unit_from_file(test_unit)
136
    else:
137
        unit_dir = ""
138
        unit_name = str(id(test_unit))
139
140
    if verbose:
        print("\nUnit: " + unit_name)
141
142
143
    errata = []
    parser = parser_factory()
    transform = transformer_factory()
144
145
    for parser_name, tests in test_unit.items():
        assert set(tests.keys()).issubset(UNIT_STAGES)
146
147
        if verbose:
            print('  Match-Tests for parser "' + parser_name + '"')
148
        for test_name, test_code in tests.get('match', dict()).items():
149
150
151
            if verbose:
                infostr = '    match-test "' + test_name + '" ... '
                errflag = len(errata)
152
            cst = parser(test_code, parser_name)
153
            cst.log("match_%s_%s.cst" % (parser_name, test_name))
154
            tests.setdefault('__cst__', {})[test_name] = cst
155
            if "ast" in tests or report:
156
157
158
                ast = copy.deepcopy(cst)
                transform(ast)
                tests.setdefault('__ast__', {})[test_name] = ast
159
                ast.log("match_%s_%s.ast" % (parser_name, test_name))
160
            if cst.error_flag:
161
                errata.append('Match test "%s" for parser "%s" failed:\n\tExpr.:  %s\n\n\t%s' %
162
                              (test_name, parser_name, '\n\t'.join(test_code.split('\n')),
163
164
                               '\n\t'.join(m.replace('\n', '\n\t\t') for m in
                                           error_messages(test_code, cst.collect_errors()))))
165
                tests.setdefault('__err__', {})[test_name] = errata[-1]
166
167
                # write parsing-history log only in case of failure!
                parser.log_parsing_history__("match_%s_%s.log" % (parser_name, test_name))
168
169
            elif "cst" in tests and mock_syntax_tree(tests["cst"][test_name]) != cst:
                    errata.append('Concrete syntax tree test "%s" for parser "%s" failed:\n%s' %
170
                                  (test_name, parser_name, cst.as_sxpr()))
171
172
173
174
175
176
            elif "ast" in tests:
                compare = mock_syntax_tree(tests["ast"][test_name])
                if compare != ast:
                    errata.append('Abstract syntax tree test "%s" for parser "%s" failed:'
                                  '\n\tExpr.:     %s\n\tExpected:  %s\n\tReceived:  %s'
                                  % (test_name, parser_name, '\n\t'.join(test_code.split('\n')),
Eckhart Arnold's avatar
Eckhart Arnold committed
177
178
                                     oneliner_sxpr(compare.as_sxpr()),
                                     oneliner_sxpr(ast.as_sxpr())))
179
                    tests.setdefault('__err__', {})[test_name] = errata[-1]
180
            if verbose:
181
                print(infostr + ("OK" if len(errata) == errflag else "FAIL"))
182

183
        if verbose and 'fail' in tests:
184
            print('  Fail-Tests for parser "' + parser_name + '"')
185
        for test_name, test_code in tests.get('fail', dict()).items():
186
187
188
            if verbose:
                infostr = '    fail-test  "' + test_name + '" ... '
                errflag = len(errata)
189
            cst = parser(test_code, parser_name)
190
191
            # doesn't make sense to write cst for fail-tests
            # cst.log("fail_%s_%s.cst" % (parser_name, test_name))
192
193
194
            if not cst.error_flag:
                errata.append('Fail test "%s" for parser "%s" yields match instead of '
                              'expected failure!' % (test_name, parser_name))
195
                tests.setdefault('__err__', {})[test_name] = errata[-1]
196
197
                # write parsing-history log only in case of test-failure
                parser.log_parsing_history__("fail_%s_%s.log" % (parser_name, test_name))
198
199
            if verbose:
                print(infostr + "OK" if len(errata) == errflag else "FAIL")
200

201
202
    # write test-report
    if report:
203
        report_dir = "REPORT"
204
205
        if not os.path.exists(report_dir):
            os.mkdir(report_dir)
206
        with open(os.path.join(report_dir, unit_name + '.md'), 'w') as f:
207
            f.write(get_report(test_unit))
208

209
210
211
    return errata


212
def grammar_suite(directory, parser_factory, transformer_factory, ignore_unknown_filetypes=False,
213
                  report=True, verbose=False):
214
215
    """
    Runs all grammar unit tests in a directory. A file is considered a test
216
217
218
    unit, if it has the word "test" in its name.
    """
    all_errors = collections.OrderedDict()
219
220
    if verbose:
        print("\nScanning test-directory: " + directory)
221
222
223
    save_cwd = os.getcwd()
    os.chdir(directory)
    for filename in sorted(os.listdir()):
224
225
        if filename.lower().find("test") >= 0:
            try:
226
227
                if verbose:
                    print("\nRunning grammar tests from: " + filename)
228
229
                errata = grammar_unit(filename, parser_factory,
                                      transformer_factory, report, verbose)
230
231
232
                if errata:
                    all_errors[filename] = errata
            except ValueError as e:
233
                if not ignore_unknown_filetypes or str(e).find("Unknown") < 0:
234
                    raise e
235
    os.chdir(save_cwd)
236
237
238
239
240
241
242
    error_report = []
    if all_errors:
        for filename in all_errors:
            error_report.append('Errors found by unit test "%s":' % filename)
            for error in all_errors[filename]:
                error_report.append('\t' + '\n\t'.join(error.split('\n')))
    if error_report:
243
        return ('Test suite "%s" revealed some errors:\n\n' % directory) + '\n'.join(error_report)
244
245
246
    return ''


247
def runner(tests, namespace):
248
249
    """
    Runs all or some selected Python unit tests found in the
250
251
    namespace. To run all tests in a module, call 
    ``runner("", globals())`` from within that module.
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270

    Args:
        tests: Either a string or a list of strings that contains the
            names of test or test classes. Each test and, in the case
            of a test class, all tests within the test class will be
            run.
        namespace: The namespace for running the test, usually 
            ``globals()`` should be used.
            
    Example:
        class TestSomething()
            def setup(self):
                pass
            def teardown(self):
                pass
            def test_something(self):
                pass
                
        if __name__ == "__main__":
di68kap's avatar
di68kap committed
271
            from DHParser.testing import runner
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
            runner("", globals())        
    """
    def instantiate(cls_name):
        exec("obj = " + cls_name + "()", namespace)
        obj = namespace["obj"]
        if "setup" in dir(obj):
            obj.setup()
        return obj

    if tests:
        if isinstance(tests, str):
            tests = tests.split(" ")
    else:
        # collect all test classes, in case no methods or classes have been passed explicitly
        tests = []
        for name in namespace.keys():
            if name.lower().startswith('test') and inspect.isclass(namespace[name]):
                tests.append(name)

    obj = None
    for test in tests:
        try:
            if test.find('.') >= 0:
                cls_name, method_name = test.split('.')
                obj = instantiate(cls_name)
                print("Running " + cls_name + "." + method_name)
                exec('obj.' + method_name + '()')
            else:
                obj = instantiate(test)
                for name in dir(obj):
                    if name.lower().startswith("test"):
                        print("Running " + test + "." + name)
                        exec('obj.' + name + '()')
        finally:
            if "teardown" in dir(obj):
                obj.teardown()