source: tester/tester.py @ 994

Last change on this file since 994 was 994, checked in by Maciej Komosinski, 4 years ago

Cosmetic

  • Property svn:eol-style set to native
File size: 12.1 KB
Line 
1import os, os.path, sys, platform, re, copy
2import traceback # for custom printing of exception trace/stack
3import errno  # for delete_file_if_present()
4import argparse
5from subprocess import Popen, PIPE
6from time import sleep
7import telnetlib
8
9# detecting CYGWIN with anaconda windows python is tricky, as all standard methods consider they are running under Windows/win32/nt.
10# Consequently, os.linesep is set incorrectly to '\r\n', so we resort to environment variable to fix this. Note that this would
11# likely give incorrect results for python installed under cygwin, so if ever needed, we should diffrentiate these two situations.
12#print(platform.system())
13#print(sys.platform)
14#for a,b in os.environ.items(): #prints all environment variables...
15#       if 'cyg' in a or 'cyg' in b: #...that contain 'cyg' and therefore may be useful for detecting that we are running under cygwin
16#               print(a,b)
17CYGWIN='HOME' in os.environ and 'cygwin' in os.environ['HOME']
18if CYGWIN:
19        os.linesep='\n' #fix wrong value (suitable for Windows)
20
21
22import comparison  # our source
23import globals  # our source
24
25
26
27
28def test(args, test_name, input, output_net, output_msg, exe_prog, exeargs):
29        print(test_name, end=" ")
30        command = prepare_exe_with_name(exe_prog)
31        command += exeargs
32        if len(output_net) > 0:
33                command += globals.EXENETMODE
34        if args.valgrind:
35                command = globals.EXEVALGRINDMODE + command
36
37        p = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
38
39        if len(output_net) > 0:
40                sleep(10 if args.valgrind else 1)  # time for the server to warm up
41                tn = telnetlib.Telnet("localhost", 9009)
42                tn.write(bytes(input, "UTF-8"))
43                sleep(2)  # time for the server to respond...
44                # if we had a command in the frams server protocol to close the connection gracefully, then we could use read_all() instead of the trick with sleep()+read_very_eager()+close()
45                stdnet = tn.read_very_eager().decode().split("\n")  # the server uses "\n" as the end-of-line character on each platform
46                tn.close()  # after this, the server is supposed to close by itself (the -N option)
47                input = ""
48        # under Windows, p.stderr.read() and p.stdout.read() block while the process works, under linux it may be different
49        # http://stackoverflow.com/questions/3076542/how-can-i-read-all-availably-data-from-subprocess-popen-stdout-non-blocking?rq=1
50        # http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python
51        # p.terminate() #this was required when the server did not have the -N option
52        # stderrdata=p.stderr.read() #fortunately it is possible to reclaim (a part of?) stream contents after the process is killed... under Windows this is the ending of the stream
53
54        (stdoutdata, stderrdata) = p.communicate(bytes(input, "UTF-8"))  # the server process ends...
55        stdoutdata = stdoutdata.decode()  # bytes to str
56        stderrdata = stderrdata.decode()  # bytes to str
57        # p.stdin.write(we) #this is not recommended because buffers can overflow and the process will hang up (and indeed it does under Windows) - so communicate() is recommended
58        # stdout = p.stdout.read()
59        # p.terminate()
60
61        # print repr(input)
62        # print repr(stdoutdata)
63
64        stdout = stdoutdata.split(os.linesep)
65        # print stdout
66        stderr = stderrdata.split(os.linesep)
67        ok = check(stdnet if len(output_net) > 0 else stdout, output_list if len(output_list) > 0 else output_net, output_msg)
68
69        if p.returncode != 0 and p.returncode is not None:
70                print("  ", p.returncode, "<- returned code")
71
72        if len(stderrdata) > 0:
73                print("   (stderr has %d lines)" % len(stderr))
74                # valgrind examples:
75                # ==2176== ERROR SUMMARY: 597 errors from 50 contexts (suppressed: 35 from 8)
76                # ==3488== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 35 from 8)
77                if (not args.valgrind) or ("ERROR SUMMARY:" in stderrdata and " 0 errors" not in stderrdata) or (args.always_show_stderr):
78                        print(stderrdata)
79
80        if not ok and args.stop:
81                sys.exit("First test failure, stopping early.")
82        return ok
83
84
85def compare(jest, goal, was_compared_to):
86        compare = comparison.Comparison(jest, goal)
87        if compare.equal:
88                print("\r", globals.ANSI_SETGREEN + " ok" + globals.ANSI_RESET)
89        else:
90                print("\r", globals.ANSI_SETRED + " FAIL\7" + globals.ANSI_RESET)
91                print(compare.result)
92                failed_result_filename = compare.list2_file + was_compared_to
93                if failed_result_filename == '':
94                        failed_result_filename = '_test'
95                f = open(os.path.join(globals.THISDIR, failed_result_filename + '.Failed-output'), 'w')  # files are easier to compare than stdout
96                print('\n'.join(jest)+'\n', end="", file=f) # not sure why one last empty line is always lost (or one too much is expected?), adding here...
97                f = open(os.path.join(globals.THISDIR, failed_result_filename + '.Failed-goal'), 'w')  # files are easier to compare than stdout
98                print('\n'.join(goal), end="", file=f)
99        return compare.equal
100
101
102def remove_prefix(text, prefix):
103        return text[len(prefix):] if text.startswith(prefix) else text
104
105
106def check(stdout, output_net, output_msg):
107        actual_out_msg = []
108        if len(output_net) > 0:  # in case of the server, there is no filtering
109                for line in stdout:
110                        actual_out_msg.append(line)
111                return compare(actual_out_msg, output_net, '')
112        else:
113                FROMSCRIPT = "Script.Message: "
114                beginnings = tuple(["[" + v + "] " for v in ("INFO", "WARN", "ERROR", "CRITICAL")])  # there is also "DEBUG"
115                header_begin = 'VMNeuronManager.autoload: Neuro classes added: '  # header section printed when the simulator is created
116                header_end = "UserScripts.autoload: "  # ending of the header section
117                now_in_header = False
118                for line in stdout:
119                        if now_in_header:
120                                if header_end in line:  # "in" because multithreaded simulators prefix their messages with their numerical id, e.g. #12/...
121                                        now_in_header = False
122                                continue
123                        else:
124                                if header_begin in line:  # as above
125                                        now_in_header = True
126                                        continue
127                                line = remove_prefix(line, beginnings[0])  # cut out [INFO], other prefixes we want to leave as they are
128                                line = remove_prefix(line, FROMSCRIPT)  # cut out FROMSCRIPT
129                                actual_out_msg.append(line)
130                if actual_out_msg[-1] == '':  # empty line at the end which is not present in our "goal" contents
131                        actual_out_msg.pop()
132                return compare(actual_out_msg, output_msg, '')
133
134
135def delete_file_if_present(filename):
136        print('"%s" (%s)' % (filename, "the file was present" if os.path.exists(filename) else "this file did not exist"))
137        try:
138                os.remove(filename)
139        except OSError as e:
140                if e.errno != errno.ENOENT:  # errno.ENOENT = no such file or directory
141                        raise  # re-raise exception if a different error occurred
142
143
144def reset_values():
145        global input_text, output_net, output_msg, test_name, ini, output_list, exeargs, exe_prog
146        input_text = ""
147        output_list = []
148        ini = ""
149        output_net, output_msg = [], []
150        exeargs = []
151        test_name = "no-name test"
152
153
154def is_test_active():
155        global test_name
156        if name_template == "":
157                return True
158        if re.match(name_template, test_name):
159                return True
160        return False
161
162
163def prepare_exe_with_name(name):
164        if name in globals.EXENAMES:
165                exename = copy.copy(globals.EXENAMES[name])  # without copy, the following modifications would change values in the EXENAMES table
166        else:
167                exename = [name]
168        for rule in globals.EXERULES:
169                exename[0] = re.sub(rule[0], rule[1], exename[0])
170        if CYGWIN: #somehow for anaconda under cygwin, re.sub() works incorrectly and 'anyname' with rule ('(.*)', '../\\1') yields '../anyname../'
171                exename=['../'+name]
172        return exename
173
174
175def print_exception():
176        print("\n"+("-"*60),'begin exception')
177        traceback.print_exc()
178        print("-"*60,'end exception')
179
180
181def main():
182        global input_text, name_template, test_name, exe_prog, exeargs
183        name_template = ""
184        exeargs = []
185
186        parser = argparse.ArgumentParser()
187        parser.add_argument("-val", "--valgrind", help="Use valgrind", action="store_true")
188        parser.add_argument("-c", "--nocolor", help="Don't use color output", action="store_true")
189        parser.add_argument("-f", "--file", help="File name with tests", required=True)
190        parser.add_argument("-tp", "--tests-path", help="tests directory, files containing test definitions, inputs and outputs are relative to this directory, default is '" + globals.THISDIR + "'")
191        parser.add_argument("-fp", "--files-path", help="files directory, files tested by OUTFILECOMPARE are referenced relative to this directory, default is '" + globals.FILESDIR + "'")
192        parser.add_argument("-wp", "--working-path", help="working directory, test executables are launched after chdir to this directory, default is '" + globals.EXEDIR + "'")
193        parser.add_argument("-n", "--name", help="Test name (regexp)")  # e.g. '^((?!python).)*$' = these tests which don't have the word "python" in their name
194        parser.add_argument("-s", "--stop", help="Stops on first difference", action="store_true")
195        parser.add_argument("-ds", "--diffslashes", help="Discriminate between slashes (consider / and \\ different)", action="store_true")
196        parser.add_argument("-err", "--always-show-stderr", help="Always print stderr (by default it is hidden if 0 errors in valgrind)", action="store_true")
197        parser.add_argument("-e", "--exe", help="Regexp 'search=replace' rule(s) transforming executable name(s) into paths (eg. '(.*)=path/to/\\1.exe')", action='append')  # in the example, double backslash is just for printing
198        parser.add_argument("-p", "--platform", help="Override platform identifier (referencing platform specific files " + globals.SPEC_INSERTPLATFORMDEPENDENTFILE + "), default:sys.platform (win32,linux2)")
199        args = parser.parse_args()
200        if args.valgrind:
201                print("Using valgrind...")
202        if args.diffslashes:
203                globals.DIFFSLASHES = args.diffslashes
204        if args.file:
205                main_test_filename = args.file
206        if args.tests_path:
207                globals.THISDIR = args.tests_path
208        if args.files_path:
209                globals.FILESDIR = args.files_path
210        if args.working_path:
211                globals.EXEDIR = args.working_path
212        if args.name:
213                name_template = args.name
214        if args.exe:
215                for e in args.exe:
216                        search, replace = e.split('=', 1)
217                        globals.EXERULES.append((search, replace))
218        if args.platform:
219                globals.PLATFORM = args.platform
220
221        os.chdir(globals.EXEDIR)
222
223        globals.init_colors(args)
224
225        fin = open(os.path.join(globals.THISDIR, args.file))
226        reset_values()
227        exe_prog = "default"  # no longer in reset_values (exe: persists across tests)
228        outfile = []
229        tests_failed = 0
230        tests_total = 0
231        for line in fin:
232                line = globals.stripEOL(line)
233                if len(line) == 0 or line.startswith("#"):
234                        continue
235                line = line.split(":", 1)
236                # print line
237                command = line[0]
238                if command == "TESTNAME":
239                        reset_values()
240                        test_name = line[1]
241                elif command == "arg":
242                        exeargs.append(line[1])
243                elif command == "exe":
244                        exe_prog = line[1]
245                elif command == "in":
246                        input_text += line[1] + "\n"
247                elif command == "out-net":
248                        output_net.append(line[1])
249                elif command == "out-file":
250                        outfile.append(line[1])
251                elif command == "out-mesg":
252                        output_msg.append(line[1])
253                elif command == "out":
254                        output_list.append(line[1])
255                elif command == "DELETEFILENOW":
256                        if is_test_active():
257                                print("\t ", command, end=" ")
258                                delete_file_if_present(os.path.join(globals.FILESDIR, line[1]))
259                elif command == "OUTFILECLEAR":
260                        outfile = []
261                elif command == "OUTFILECOMPARE":
262                        if is_test_active():
263                                print("\t", command, '"%s"' % line[1], end=" ")
264                                try:
265                                        contents = []
266                                        with open(os.path.join(globals.FILESDIR, line[1]), 'r') as main_test_filename:
267                                                for line in main_test_filename:
268                                                        contents.append(globals.stripEOL(line))
269                                        ok = compare(contents, outfile, '_file') # +line[1]
270                                except Exception as e: # could also 'raise' for some types of exceptions if we wanted
271                                        print_exception()
272                                        ok = 0
273                                tests_failed += int(not ok)
274                                tests_total += 1
275                elif command == "RUNTEST":
276                        if is_test_active():
277                                print("\t", command, end=" ")
278                                try:
279                                        ok = test(args, test_name, input_text, output_net, output_msg, exe_prog, exeargs)
280                                except Exception as e: # could also 'raise' for some types of exceptions if we wanted
281                                        print_exception()
282                                        ok = 0
283                                tests_failed += int(not ok)
284                                tests_total += 1
285                else:
286                        raise Exception("Don't know what to do with this line in test file: ", line)
287
288        return (tests_failed, tests_total)
289
290
291if __name__ == "__main__":
292        tests_failed, tests_total = main()
293        print("%d / %d failed tests" % (tests_failed, tests_total))
294        sys.exit(tests_failed)  # return the number of failed tests as exit code ("error level") to shell
Note: See TracBrowser for help on using the repository browser.