test_dsl.py 5.11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python3

"""test_dsl.py - tests of the dsl-module of DHParser 


Author: Eckhart Arnold <arnold@badw.de>

Copyright 2017 Bavarian Academy of Sciences and Humanities

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.
"""

23
24
import os
import sys
Eckhart Arnold's avatar
Eckhart Arnold committed
25
sys.path.extend(['../', './'])
26

27
from DHParser.parser import Grammar, Compiler
28
from DHParser.error import is_error
29
from DHParser.dsl import compile_on_disk, run_compiler, compileEBNF, grammar_provider, \
30
    load_compiler_suite
Eckhart Arnold's avatar
Eckhart Arnold committed
31
32
33
34
35
36
37
38
39
40
41
42

ARITHMETIC_EBNF = """
    @ whitespace = linefeed
    formula = [ //~ ] expr
    expr = expr ("+"|"-") term | term
    term = term ("*"|"/") factor | factor
    factor = /[0-9]+/~
    # example:  "5 + 3 * 4"
    """

class TestCompileFunctions:
    def test_compileEBNF(self):
43
        parser_src = compileEBNF(ARITHMETIC_EBNF)
44
        assert isinstance(parser_src, str), str(type(parser_src))
45
        assert parser_src.find('DSLGrammar') >= 0
46
        parser_src = compileEBNF(ARITHMETIC_EBNF, branding="CustomDSL")
47
        assert isinstance(parser_src, str), str(type(parser_src))
48
        assert parser_src.find('CustomDSLGrammar') >= 0
49
        factory = grammar_provider(ARITHMETIC_EBNF, branding="TestDSL")
50
51
        assert callable(factory)
        parser = factory()
52
53
54
        result = parser("5 + 3 * 4")
        assert not result.error_flag
        result = parser("5A + 4B ** 4C")
55
        assert is_error(result.error_flag)
56

57

58
59
class TestCompilerGeneration:
    trivial_lang = """
60
        text = { word | WSPC } "." [/\s/]
61
        word = /\w+/
62
        WSPC = /\s+/
63
        """
64
    tmp = 'test/tmp/' if os.path.isdir('test/') else ('tmp/')
65
    trivial_text = u"""Es war ein Koenig in Thule.\n"""
66
    grammar_name = tmp + "TestCompilerGeneration.ebnf"
67
    compiler_name = tmp + "TestCompilerGenerationCompiler.py"
68
69
    text_name = tmp + "TestCompilerGeneration_text.txt"
    result_name = tmp + "TestCompilerGeneration_text.xml"
70
71

    def setup(self):
72
73
        if not os.path.exists(self.tmp):
            os.mkdir(self.tmp)
74
75
76
77
78
79
        with open(self.grammar_name, "w") as f:
            f.write(self.trivial_lang)
        with open(self.text_name, "w") as f:
            f.write(self.trivial_text)

    def teardown(self):
80
81
82
        for name in (self.grammar_name, self.compiler_name, self.text_name, self.result_name):
            if os.path.exists(name):
                os.remove(name)
Eckhart Arnold's avatar
Eckhart Arnold committed
83
84
85
86
87
88
89
90
91
92
        if os.path.exists('LOGS'):
            files = os.listdir('LOGS')
            flag = False
            for file in files:
                if file.startswith('TestCompilerGenerationCompiler') or file == "info.txt":
                    os.remove(os.path.join('LOGS', file))
                else:
                    flag = True
            if not flag:
                os.rmdir('LOGS')
93
94
95
96
97
        pycachedir = os.path.join(self.tmp,'__pycache__')
        if os.path.exists(pycachedir):
            for fname in os.listdir(pycachedir):
                os.remove(os.path.join(pycachedir, fname))
            os.rmdir(pycachedir)
98
99
        if os.path.exists(self.tmp):
            os.rmdir(self.tmp)
Eckhart Arnold's avatar
Eckhart Arnold committed
100

101

102
103
104
105
106
107
108
109
    def test_load_compiler_suite(self):
        src = compileEBNF(self.trivial_lang, "Trivial")
        scanner, parser, transformer, compiler = load_compiler_suite(src)
        scanner = scanner()
        parser = parser()
        transformer = transformer()
        compiler = compiler()
        assert callable(scanner)
110
        assert isinstance(parser, Grammar)
111
        assert callable(transformer)
112
        assert isinstance(compiler, Compiler)
113

114
115
116
117
118
119
120
121
122
123
124
125
126
    def test_compiling_functions(self):
        # test if cutting and reassembling of compiler suite works:
        errors = compile_on_disk(self.grammar_name)
        assert not errors
        with open(self.compiler_name, 'r') as f:
            compiler_suite = f.read()
        errors = compile_on_disk(self.grammar_name)
        assert not errors
        with open(self.compiler_name, 'r') as f:
            compiler_suite_2nd_run = f.read()
        assert compiler_suite == compiler_suite_2nd_run

        # test compiling with a generated compiler suite
127
        # assert is_filename(self.text_name)
128
129
130
131
132
        errors = compile_on_disk(self.text_name, self.compiler_name)
        assert not errors, str(errors)
        assert os.path.exists(self.result_name)
        with open(self.result_name, 'r') as f:
            output = f.read()
133

134
135
136
        # test compiling in memory
        result = run_compiler(self.trivial_text, self.compiler_name)
        assert output == result.as_xml(), str(result)
137

138
        sys.path.append(self.tmp)
139
140
        from TestCompilerGenerationCompiler import compile_src
        result, errors, ast = compile_src(self.trivial_text)
141
142
143


if __name__ == "__main__":
144
    from DHParser.testing import runner
145
    runner("", globals())