[go: up one dir, main page]

File: driver.py

package info (click to toggle)
relational 3.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,168 kB
  • sloc: python: 2,984; makefile: 101
file content (285 lines) | stat: -rwxr-xr-x 8,569 bytes parent folder | download | duplicates (2)
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/usr/bin/env python3
# Relational
# Copyright (C) 2010-2020  Salvo "LtWorf" Tomaselli
#
# Relational 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 3 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, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import os
from sys import exit
import sys
import traceback

from relational import relation, parser, optimizer
from xtermcolor import colorize


COLOR_RED = 0xff0000
COLOR_GREEN = 0x00ff00
COLOR_MAGENTA = 0xff00ff
COLOR_CYAN = 0x00ffff

print(relation)

rels = {}
examples_path = 'samples/'
tests_path = 'tests_dir/'


def readfile(fname):
    '''Reads a file as string and returns its content'''
    with open(fname, encoding='utf-8') as fd:
        expr = fd.read()
        return expr


def load_relations():
    '''Loads all the relations present in the directory indicated in the
    examples_path variable and stores them in the rels dictionary'''
    print("Loading relations")
    for i in os.listdir(examples_path):
        if i.endswith('.csv'):  # It's a relation, loading it

            # Naming the relation
            relname = i[:-4]

            print("Loading relation %s with name %s..." % (i, relname))

            rels[relname] = relation.Relation.load_csv('%s%s' % (examples_path, i))
            print('done')


def execute_tests():

    py_bad = 0
    py_good = 0
    py_tot = 0
    q_bad = 0
    q_good = 0
    q_tot = 0
    ex_bad = 0
    ex_good = 0
    ex_tot = 0
    f_tot = 0
    f_good = 0
    f_bad = 0

    for i in os.listdir(tests_path):
        if i.endswith('.query'):
            q_tot += 1
            if run_test(i[:-6]):
                q_good += 1
            else:
                q_bad += 1
        elif i.endswith('.python'):
            py_tot += 1
            if run_py_test(i[:-7]):
                py_good += 1
            else:
                py_bad += 1
        elif i.endswith('.py'):
            ex_tot += 1
            if run_exec_test(i[:-3]):
                ex_good += 1
            else:
                ex_bad += 1
        elif i.endswith('.fail'):
            f_tot += 1
            if run_fail_test(i[:-5]):
                f_good += 1
            else:
                f_bad += 1

    print(colorize("Resume of the results", COLOR_CYAN))

    print(colorize("Query tests", COLOR_MAGENTA))
    print("Total test count: %d" % q_tot)
    print("Passed tests: %d" % q_good)
    if q_bad > 0:
        print(colorize("Failed tests count: %d" % q_bad, COLOR_RED))

    print(colorize("Python tests", COLOR_MAGENTA))
    print("Total test count: %d" % py_tot)
    print("Passed tests: %d" % py_good)
    if py_bad > 0:
        print(colorize("Failed tests count: %d" % py_bad, COLOR_RED))

    print(colorize("Execute Python tests", COLOR_MAGENTA))
    print("Total test count: %d" % ex_tot)
    print("Passed tests: %d" % ex_good)
    if ex_bad > 0:
        print(colorize("Failed tests count: %d" % ex_bad, COLOR_RED))

    print(colorize("Execute fail tests", COLOR_MAGENTA))
    print("Total test count: %d" % f_tot)
    print("Passed tests: %d" % f_good)
    if f_bad > 0:
        print(colorize("Failed tests count: %d" % f_bad, COLOR_RED))

    print(colorize("Total results", COLOR_CYAN))
    if f_bad + q_bad + py_bad + ex_bad == 0:
        print(colorize("No failed tests", COLOR_GREEN))
        return 0
    else:
        print(colorize("There are %d failed tests" %
               (f_bad + py_bad + q_bad + ex_bad), COLOR_RED))
        return 1


def run_exec_test(testname):
    '''Runs a python test, which executes code directly rather than queries'''
    print("Running python test: " + colorize(testname, COLOR_MAGENTA))

    glob = rels.copy()
    exp_result = {}

    expr = readfile('%s%s.py' % (tests_path, testname))

    try:
        exec(expr, glob)  # Evaluating the expression
        print(colorize('Test passed', COLOR_GREEN))
        return True
    except Exception as e:
        print(colorize('ERROR', COLOR_RED))
        print(colorize('=====================================', COLOR_RED))
        traceback.print_exc(file=sys.stdout)
        print(colorize('=====================================', COLOR_RED))
        return False


def run_py_test(testname):
    '''Runs a python test, which evaluates expressions directly rather than queries'''
    print("Running expression python test: " +
           colorize(testname, COLOR_MAGENTA))
    exp_result = None
    result = None
    try:

        expr = readfile('%s%s.python' % (tests_path, testname))
        result = eval(expr, rels)

        expr = readfile('%s%s.result' % (tests_path, testname))
        exp_result = eval(expr, rels)

        if result == exp_result:
            print(colorize('Test passed', COLOR_GREEN))
            return True
    except:
        pass

    print(colorize('ERROR', COLOR_RED))
    print(colorize('=====================================', COLOR_RED))
    print("Expected %s" % exp_result.pretty_string(tty=True))
    print("Got %s" % result.pretty_string(tty=True))
    print(colorize('=====================================', COLOR_RED))
    return False

def run_fail_test(testname):
    '''Runs a test, which executes a query that is supposed to fail'''
    print("Running fail test: " + colorize(testname, COLOR_MAGENTA))

    query = readfile('%s%s.fail' % (tests_path, testname)).strip()
    test_succeed = True

    try:
        expr = parser.parse(query)
        expr(rels)
        test_succeed = False
    except:
        pass

    try:
        o_query = optimizer.optimize_all(query, rels)
        o_expr = parser.parse(o_query)
        o_expr(rels)
        test_succeed = False
    except:
        pass

    try:
        c_expr = parser.tree(query).toCode()
        eval(c_expr, rels)
        test_succeed = False
    except:
        pass

    if test_succeed:
        print(colorize('Test passed', COLOR_GREEN))
    else:
        print(colorize('Test failed (by not raising any exception)', COLOR_RED))
    return test_succeed

def run_test(testname):
    '''Runs a specific test executing the file
    testname.query
    and comparing the result with
    testname.result
    The query will be executed both unoptimized and
    optimized'''
    print("Running test: " + colorize(testname, COLOR_MAGENTA))

    query = None
    expr = None
    o_query = None
    o_expr = None
    result_rel = None
    result = None
    o_result = None

    try:
        result_rel = relation.Relation.load('%s%s.result' % (tests_path, testname))

        query = readfile('%s%s.query' % (tests_path, testname)).strip()
        o_query = optimizer.optimize_all(query, rels)

        expr = parser.parse(query)
        result = expr(rels)

        o_expr = parser.parse(o_query)
        o_result = o_expr(rels)

        c_expr = parser.tree(query).toCode()
        c_result = eval(c_expr, rels)

        if (o_result == result_rel) and (result == result_rel) and (c_result == result_rel):
            print(colorize('Test passed', COLOR_GREEN))
            return True
    except Exception as inst:
        traceback.print_exc(file=sys.stdout)
        print(inst)
        pass
    print(colorize('ERROR', COLOR_RED))
    print("Query: %s -> %s" % (query, expr))
    print("Optimized query: %s -> %s" % (o_query, o_expr))
    print(colorize('=====================================', COLOR_RED))
    print(colorize("Expected result", COLOR_GREEN))
    print(result_rel.pretty_string(tty=True))
    print(colorize("Result", COLOR_RED))
    print(result.pretty_string(tty=True))
    print(colorize("Optimized result", COLOR_RED))
    print(o_result.pretty_string(tty=True))
    print(colorize("optimized result match %s" %
           str(result_rel == o_result), COLOR_MAGENTA))
    print(colorize("result match %s" %
           str(result == result_rel), COLOR_MAGENTA))
    print(colorize('=====================================', COLOR_RED))
    return False


if __name__ == '__main__':
    print("-> Starting testsuite for relational")
    load_relations()
    print("-> Starting tests")
    exit(execute_tests())