test_dsl.py 5.34 KB
Newer Older
eckhart's avatar
eckhart committed
1
#!/usr/bin/python
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

"""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
28
from DHParser.parse import Grammar
from DHParser import Compiler
29
from DHParser.error import is_error
30
from DHParser.dsl import compile_on_disk, run_compiler, compileEBNF, grammar_provider, \
31
    load_compiler_suite
32
from DHParser.toolkit import concurrent_ident
Eckhart Arnold's avatar
Eckhart Arnold committed
33
34
35
36
37
38
39
40
41
42
43
44

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):
45
        parser_src = compileEBNF(ARITHMETIC_EBNF)
46
        assert isinstance(parser_src, str), str(type(parser_src))
47
        assert parser_src.find('DSLGrammar') >= 0
48
        parser_src = compileEBNF(ARITHMETIC_EBNF, branding="CustomDSL")
49
        assert isinstance(parser_src, str), str(type(parser_src))
50
        assert parser_src.find('CustomDSLGrammar') >= 0
51
        factory = grammar_provider(ARITHMETIC_EBNF, branding="TestDSL")
52
53
        assert callable(factory)
        parser = factory()
54
        result = parser("5 + 3 * 4")
55
        assert not result.error_flag, str(result.collect_errors())
56
        result = parser("5A + 4B ** 4C")
57
        assert is_error(result.error_flag)
58

59

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

    def setup(self):
75
76
        if not os.path.exists(self.tmp):
            os.mkdir(self.tmp)
77
78
79
80
81
82
        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):
83
84
85
        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
86
87
88
89
90
91
92
93
94
95
        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')
96
97
98
99
100
        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)
101
102
        if os.path.exists(self.tmp):
            os.rmdir(self.tmp)
Eckhart Arnold's avatar
Eckhart Arnold committed
103

104

105
106
107
108
109
110
111
112
    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)
113
        assert isinstance(parser, Grammar)
114
        assert callable(transformer)
115
        assert isinstance(compiler, Compiler)
116

117
118
119
120
121
122
123
124
125
126
127
128
129
    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
130
        # assert is_filename(self.text_name)
131
132
133
134
135
        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()
136

137
138
139
        # test compiling in memory
        result = run_compiler(self.trivial_text, self.compiler_name)
        assert output == result.as_xml(), str(result)
140

141
        sys.path.append(self.tmp)
142
        from TestCompilerGenerationCompiler import compile_src
143
        # print(compile_src)
144
        result, errors, ast = compile_src(self.trivial_text)
145
146
147


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