testing.py 15 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 Node, error_messages
30
from DHParser.toolkit import compact_sexpr, is_logging
31
32
from DHParser.syntaxtree import MockParser
from DHParser.ebnf import grammar_changed
33
from DHParser.dsl import compile_on_disk
34

35
36
37
38
39
40
41
42
43
44
__all__ = ('mock_syntax_tree',
           'recompile_grammar',
           'unit_from_configfile',
           'unit_from_json',
           'unit_from_file',
           'get_report',
           'grammar_unit',
           'grammar_suite',
           'runner')

45
46

def mock_syntax_tree(sexpr):
47
48
    """
    Generates a tree of nodes from an S-expression.
49
50

    Example: 
51
    >>> mock_syntax_tree("(a (b c))").as_sxpr()
52
    '(a\\n    (b\\n        "c"\\n    )\\n)'
53
54
55
56
57
58
    """
    def next_block(s):
        s = s.strip()
        while s[0] != ')':
            if s[0] != '(': raise ValueError('"(" expected, not ' + s[:10])
            # assert s[0] == '(', s
59
            level = 1
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
            i = 1
            while level > 0:
                if s[i] == '(':
                    level += 1
                elif s[i] == ')':
                    level -= 1
                i += 1
            yield s[:i]
            s = s[i:].strip()

    sexpr = sexpr.strip()
    if sexpr[0] != '(': raise ValueError('"(" expected, not ' + sexpr[:10])
    # assert sexpr[0] == '(', sexpr
    sexpr = sexpr[1:].strip()
    m = re.match('[\w:]+', sexpr)
    name, class_name = (sexpr[:m.end()].split(':') + [''])[:2]
    sexpr = sexpr[m.end():].strip()
    if sexpr[0] == '(':
        result = tuple(mock_syntax_tree(block) for block in next_block(sexpr))
    else:
        lines = []
        while sexpr and sexpr[0] != ')':
            for qm in ['"""', "'''", '"', "'"]:
                m = re.match(qm + r'.*?' + qm, sexpr)
                if m:
                    i = len(qm)
                    lines.append(sexpr[i:m.end() - i])
                    sexpr = sexpr[m.end():].strip()
                    break
            else:
                m = re.match(r'(?:(?!\)).)*', sexpr)
                lines.append(sexpr[:m.end()])
                sexpr = sexpr[m.end():]
        result = "\n".join(lines)
    return Node(MockParser(name, ':' + class_name), result)


97
def recompile_grammar(ebnf_filename, force=False) -> bool:
98
99
    """
    Recompiles an ebnf-grammar if necessary, that is if either no
100
    corresponding 'XXXXCompiler.py'-file exists or if that file is
101
102
103
104
105
106
107
    outdated.
    
    Parameters:
        ebnf_filename(str):  The filename of the ebnf-source of the 
            grammar. In case this is a directory and not a file all
            files within this directory ending with .ebnf will be 
            compiled.
108
109
        force(bool):  If False (default), the grammar will only be
            recompiled if it has been changed.
110
111
    """
    if os.path.isdir(ebnf_filename):
112
        success = True
113
114
        for entry in os.listdir(ebnf_filename):
            if entry.lower().endswith('.ebnf') and os.path.isfile(entry):
115
116
                success = success and recompile_grammar(entry, force)
        return success
117
118

    base, ext = os.path.splitext(ebnf_filename)
119
    compiler_name = base + 'Compiler.py'
120
    error_file_name = base + '_ebnf_ERRORS.txt'
121
    errors = []
122
    if (not os.path.exists(compiler_name) or force or
123
124
125
126
127
        grammar_changed(compiler_name, ebnf_filename)):
        # print("recompiling parser for: " + ebnf_filename)
        errors = compile_on_disk(ebnf_filename)
        if errors:
            # print("Errors while compiling: " + ebnf_filename + '!')
128
            with open(error_file_name, 'w') as f:
129
130
131
                for e in errors:
                    f.write(e)
                    f.write('\n')
132
            return False
133

134
135
    if not errors and os.path.exists(error_file_name):
        os.remove(error_file_name)
136
    return True
137

138

139
UNIT_STAGES = {'match', 'fail', 'ast', 'cst', '__ast__', '__cst__'}
140
141


142
def unit_from_configfile(config_filename):
143
144
    """
    Reads a grammar unit test from a config file.
145
    """
146
    cfg = configparser.ConfigParser(interpolation=None)
147
    cfg.read(config_filename)
148
149
    OD = collections.OrderedDict
    unit = OD()
150
151
    for section in cfg.sections():
        symbol, stage = section.split(':')
152
153
        if stage not in UNIT_STAGES:
            if symbol in UNIT_STAGES:
154
155
                symbol, stage = stage, symbol
            else:
156
                raise ValueError('Test stage %s not in: ' % (stage, str(UNIT_STAGES)))
157
        for testkey, testcode in cfg[section].items():
158
159
160
161
            if testcode[:3] + testcode[-3:] in {"''''''", '""""""'}:
                testcode = testcode[3:-3]
            elif testcode[:1] + testcode[-1:] in {"''", '""'}:
                testcode = testcode[1:-1]
162
            unit.setdefault(symbol, OD()).setdefault(stage, OD())[testkey] = testcode
163
164
    # print(json.dumps(unit, sort_keys=True, indent=4))
    return unit
165

166

167
def unit_from_json(json_filename):
168
169
    """
    Reads a grammar unit test from a json file.
170
    """
171
    with open(json_filename, 'r') as f:
172
173
174
175
176
177
178
        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

179
# TODO: add support for yaml, cson, toml
180
181


182
def unit_from_file(filename):
183
184
    """
    Reads a grammar unit test from a file. The format of the file is
185
186
    determined by the ending of its name.
    """
187
188
189
190
    if filename.endswith(".json"):
        return unit_from_json(filename)
    elif filename.endswith(".ini"):
        return unit_from_configfile(filename)
191
    else:
192
        raise ValueError("Unknown unit test file type: " + filename[filename.rfind('.'):])
193
194


195
def get_report(test_unit):
196
197
    """
    Returns a text-report of the results of a grammar unit test.
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    """
    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:')
            report.append(test_code)
            error = tests.get('__err__', {}).get(test_name, "")
            if error:
                report.append('\n### Error:')
                report.append(error)
            ast = tests.get('__ast__', {}).get(test_name, None)
213
214
215
            cst = tests.get('__cst__', {}).get(test_name, None)
            if cst and (not ast or cst == ast):
                report.append('\n### CST')
216
                report.append(cst.as_sxpr())
217
            elif ast:
218
                report.append('\n### AST')
219
                report.append(ast.as_sxpr())
220
221
222
    return '\n'.join(report)


223
def grammar_unit(test_unit, parser_factory, transformer_factory, report=True, verbose=False):
224
225
    """
    Unit tests for a grammar-parser and ast transformations.
226
    """
227
    if isinstance(test_unit, str):
228
        unit_dir, unit_name = os.path.split(os.path.splitext(test_unit)[0])
229
        test_unit = unit_from_file(test_unit)
230
    else:
231
        unit_dir = ""
232
        unit_name = str(id(test_unit))
233
234
    if verbose:
        print("\nUnit: " + unit_name)
235
236
237
    errata = []
    parser = parser_factory()
    transform = transformer_factory()
238
239
    for parser_name, tests in test_unit.items():
        assert set(tests.keys()).issubset(UNIT_STAGES)
240
241
        if verbose:
            print('  Match-Tests for parser "' + parser_name + '"')
242
        for test_name, test_code in tests.get('match', dict()).items():
243
244
245
            if verbose:
                infostr = '    match-test "' + test_name + '" ... '
                errflag = len(errata)
246
            cst = parser(test_code, parser_name)
247
248
            if is_logging():
                cst.log("match_%s_%s.cst" % (parser_name, test_name))
249
                parser.log_parsing_history__("match_%s_%s.log" % (parser_name, test_name))
250
            tests.setdefault('__cst__', {})[test_name] = cst
251
            if "ast" in tests or report:
252
253
254
                ast = copy.deepcopy(cst)
                transform(ast)
                tests.setdefault('__ast__', {})[test_name] = ast
255
256
                if is_logging():
                    ast.log("match_%s_%s.ast" % (parser_name, test_name))
257
            if cst.error_flag:
258
                errata.append('Match test "%s" for parser "%s" failed:\n\tExpr.:  %s\n\n\t%s' %
259
                              (test_name, parser_name, '\n\t'.join(test_code.split('\n')),
260
261
                               '\n\t'.join(m.replace('\n', '\n\t\t') for m in
                                           error_messages(test_code, cst.collect_errors()))))
262
                tests.setdefault('__err__', {})[test_name] = errata[-1]
263
264
            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' %
265
                                  (test_name, parser_name, cst.as_sxpr()))
266
267
268
269
270
271
            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')),
272
273
                                     compact_sexpr(compare.as_sxpr()),
                                     compact_sexpr(ast.as_sxpr())))
274
                    tests.setdefault('__err__', {})[test_name] = errata[-1]
275
            if verbose:
276
                print(infostr + ("OK" if len(errata) == errflag else "FAIL"))
277

278
        if verbose and 'fail' in tests:
279
            print('  Fail-Tests for parser "' + parser_name + '"')
280
        for test_name, test_code in tests.get('fail', dict()).items():
281
282
283
            if verbose:
                infostr = '    fail-test  "' + test_name + '" ... '
                errflag = len(errata)
284
            cst = parser(test_code, parser_name)
285
286
            if is_logging():
                cst.log("fail_%s_%s.cst" % (parser_name, test_name))
287
                parser.log_parsing_history__("fail_%s_%s.log" % (parser_name, test_name))
288
289
290
            if not cst.error_flag:
                errata.append('Fail test "%s" for parser "%s" yields match instead of '
                              'expected failure!' % (test_name, parser_name))
291
                tests.setdefault('__err__', {})[test_name] = errata[-1]
292
293
            if verbose:
                print(infostr + "OK" if len(errata) == errflag else "FAIL")
294

295
296
    # write test-report
    if report:
297
298
299
300
        report_dir = os.path.join(unit_dir, "REPORT")
        if not os.path.exists(report_dir):
            os.mkdir(report_dir)
        with open(os.path.join(report_dir, unit_name + '.report'), 'w') as f:
301
            f.write(get_report(test_unit))
302

303
304
305
    return errata


306
def grammar_suite(directory, parser_factory, transformer_factory, ignore_unknown_filetypes=False,
307
                  report=True, verbose=False):
308
309
    """
    Runs all grammar unit tests in a directory. A file is considered a test
310
311
312
    unit, if it has the word "test" in its name.
    """
    all_errors = collections.OrderedDict()
313
314
    if verbose:
        print("\nScanning test-directory: " + directory)
315
316
317
    for filename in sorted(os.listdir(directory)):
        if filename.lower().find("test") >= 0:
            try:
318
319
                if verbose:
                    print("\nRunning grammar tests from: " + filename)
320
                errata = grammar_unit(os.path.join(directory, filename),
321
                                      parser_factory, transformer_factory, report, verbose)
322
323
324
                if errata:
                    all_errors[filename] = errata
            except ValueError as e:
325
                if not ignore_unknown_filetypes or str(e).find("Unknown") < 0:
326
327
328
329
330
331
332
333
                    raise e
    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:
334
        return ('Test suite "%s" revealed some errors:\n\n' % directory) + '\n'.join(error_report)
335
336
337
    return ''


338
def runner(tests, namespace):
339
340
    """
    Runs all or some selected Python unit tests found in the
341
342
    namespace. To run all tests in a module, call 
    ``runner("", globals())`` from within that module.
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361

    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
362
            from DHParser.testing import runner
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
            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()