source: tester/tester.py @ 1209

Last change on this file since 1209 was 1144, checked in by sz, 4 years ago

new options:

-d, --nodiff: Don't show individual line differences, just test results
-noerr, --never-show-stderr: Never print stderr

  • Property svn:eol-style set to native
File size: 13.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, not args.nodiff)
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)) and not args.never_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, showdiff):
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                if showdiff:
92                        try:
93                                print(compare.result)
94                        except UnicodeEncodeError:
95                                print(compare.result.encode("utf-8")) #only encode as utf8 when it is actually used, but this looks incorrect and perhaps should not be needed if the console supports utf8?
96                        #sys.stdout.buffer.write(compare.result.encode("utf-8")) #prints nothing (on cygwin)
97                failed_result_filename = compare.list2_file + was_compared_to
98                if failed_result_filename == '':
99                        failed_result_filename = '_test'
100                f = open(os.path.join(globals.THISDIR, failed_result_filename + '.Failed-output'), 'w',  encoding='utf8')  # files are easier to compare than stdout
101                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...
102                f = open(os.path.join(globals.THISDIR, failed_result_filename + '.Failed-goal'), 'w',  encoding='utf8')  # files are easier to compare than stdout
103                print('\n'.join(goal), end="", file=f)
104        return compare.equal
105
106
107def remove_prefix(text, prefix):
108        return text[len(prefix):] if text.startswith(prefix) else text
109
110
111def check(stdout, output_net, output_msg, showdiff):
112        actual_out_msg = []
113        if len(output_net) > 0:  # in case of the server, there is no filtering
114                for line in stdout:
115                        actual_out_msg.append(line)
116                return compare(actual_out_msg, output_net, '', showdiff)
117        else:
118                FROMSCRIPT = "Script.Message: "
119                beginnings = tuple(["[" + v + "] " for v in ("INFO", "WARN", "ERROR", "CRITICAL")])  # there is also "DEBUG"
120                header_begin = 'VMNeuronManager.autoload: Neuro classes added: '  # header section printed when the simulator is created
121                header_end = "UserScripts.autoload: "  # ending of the header section
122                now_in_header = False
123                for line in stdout:
124                        if now_in_header:
125                                if header_end in line:  # "in" because multithreaded simulators prefix their messages with their numerical id, e.g. #12/...
126                                        now_in_header = False
127                                continue
128                        else:
129                                if header_begin in line:  # as above
130                                        now_in_header = True
131                                        continue
132                                line = remove_prefix(line, beginnings[0])  # cut out [INFO], other prefixes we want to leave as they are
133                                line = remove_prefix(line, FROMSCRIPT)  # cut out FROMSCRIPT
134                                actual_out_msg.append(line)
135                if actual_out_msg[-1] == '':  # empty line at the end which is not present in our "goal" contents
136                        actual_out_msg.pop()
137                return compare(actual_out_msg, output_msg, '', showdiff)
138
139
140def delete_file_if_present(filename):
141        print('"%s" (%s)' % (filename, "the file was present" if os.path.exists(filename) else "this file did not exist"))
142        try:
143                os.remove(filename)
144        except OSError as e:
145                if e.errno != errno.ENOENT:  # errno.ENOENT = no such file or directory
146                        raise  # re-raise exception if a different error occurred
147
148
149def reset_values():
150        global input_text, output_net, output_msg, test_name, ini, output_list, exeargs, exe_prog
151        input_text = ""
152        output_list = []
153        ini = ""
154        output_net, output_msg = [], []
155        exeargs = []
156        test_name = "no-name test"
157
158
159def is_test_active():
160        global test_name
161        if name_template == "":
162                return True
163        if re.match(name_template, test_name):
164                return True
165        return False
166
167
168def prepare_exe_with_name(name):
169        if name in globals.EXENAMES:
170                exename = copy.copy(globals.EXENAMES[name])  # without copy, the following modifications would change values in the EXENAMES table
171        else:
172                exename = [name]
173        for rule in globals.EXERULES:
174                exename[0] = re.sub(rule[0], rule[1], exename[0])
175        if CYGWIN: #somehow for anaconda under cygwin, re.sub() works incorrectly and 'anyname' with rule ('(.*)', '../\\1') yields '../anyname../'
176                exename=['../'+name]
177        return exename
178
179
180def print_exception(exc):
181        print("\n"+("-"*60),'begin exception')
182        print(exc) # some exceptions have an empty traceback, they only provide one-line exception name
183        traceback.print_exc()
184        print("-"*60,'end exception')
185
186
187def main():
188        global input_text, name_template, test_name, exe_prog, exeargs
189        name_template = ""
190        exeargs = []
191
192        parser = argparse.ArgumentParser()
193        parser.add_argument("-val", "--valgrind", help="Use valgrind", action="store_true")
194        parser.add_argument("-c", "--nocolor", help="Don't use color output", action="store_true")
195        parser.add_argument("-f", "--file", help="File name with tests", required=True)
196        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 + "'")
197        parser.add_argument("-fp", "--files-path", help="files directory, files tested by OUTFILECOMPARE are referenced relative to this directory, default is '" + globals.FILESDIR + "'")
198        parser.add_argument("-wp", "--working-path", help="working directory, test executables are launched after chdir to this directory, default is '" + globals.EXEDIR + "'")
199        parser.add_argument("-n", "--name", help="Test name (regexp)")  # e.g. '^((?!python).)*$' = these tests which don't have the word "python" in their name
200        parser.add_argument("-s", "--stop", help="Stops on first difference", action="store_true")
201        parser.add_argument("-d", "--nodiff", help="Don't show individual line differences, just test results", action="store_true")
202        parser.add_argument("-ds", "--diffslashes", help="Discriminate between slashes (consider / and \\ different)", action="store_true")
203        parser.add_argument("-err", "--always-show-stderr", help="Always print stderr (by default it is hidden if 0 errors in valgrind)", action="store_true")
204        parser.add_argument("-noerr", "--never-show-stderr", help="Never print stderr", action="store_true")
205        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
206        parser.add_argument("-p", "--platform", help="Override platform identifier (referencing platform specific files " + globals.SPEC_INSERTPLATFORMDEPENDENTFILE + "), default:sys.platform (win32,linux2)")
207        args = parser.parse_args()
208        if args.valgrind:
209                print("Using valgrind...")
210        if args.diffslashes:
211                globals.DIFFSLASHES = args.diffslashes
212        if args.file:
213                main_test_filename = args.file
214        if args.tests_path:
215                globals.THISDIR = args.tests_path
216        if args.files_path:
217                globals.FILESDIR = args.files_path
218        if args.working_path:
219                globals.EXEDIR = args.working_path
220        if args.name:
221                name_template = args.name
222        if args.exe:
223                for e in args.exe:
224                        search, replace = e.split('=', 1)
225                        globals.EXERULES.append((search, replace))
226        if args.platform:
227                globals.PLATFORM = args.platform
228
229        os.chdir(globals.EXEDIR)
230
231        globals.init_colors(args)
232
233        fin = open(os.path.join(globals.THISDIR, args.file), encoding='utf8')
234        reset_values()
235        exe_prog = "default"  # no longer in reset_values (exe: persists across tests)
236        outfile = []
237        tests_failed = 0
238        tests_total = 0
239        dotOK = ""
240        for line in fin:
241                line = globals.stripEOL(line)
242                if len(line) == 0 or line.startswith("#"):
243                        continue
244                line = line.split(":", 1)
245                # print line
246                command = line[0]
247                if command == "TESTNAME":
248                        reset_values()
249                        test_name = line[1]
250                elif command == "arg":
251                        exeargs.append(line[1])
252                elif command == "exe":
253                        exe_prog = line[1]
254                elif command == "in":
255                        input_text += line[1] + "\n"
256                elif command == "out-net":
257                        output_net.append(line[1])
258                elif command == "out-file":
259                        outfile.append(line[1])
260                elif command == "out-mesg":
261                        output_msg.append(line[1])
262                elif command == "out":
263                        output_list.append(line[1])
264                elif command == "DELETEFILENOW":
265                        if is_test_active():
266                                print("\t ", command, end=" ")
267                                delete_file_if_present(os.path.join(globals.FILESDIR, line[1]))
268                elif command == "OUTFILECLEAR":
269                        outfile = []
270                elif command == "OUTFILECOMPARE":
271                        if is_test_active():
272                                print("\t", command, '"%s"' % line[1], end=" ")
273                                try:
274                                        contents = []
275                                        with open(os.path.join(globals.FILESDIR, line[1]), 'r', encoding='utf8') as main_test_filename:
276                                                for line in main_test_filename:
277                                                        contents.append(globals.stripEOL(line))
278                                        ok = compare(contents, outfile, '_file', not args.nodiff) # +line[1]
279                                except Exception as e: # could also 'raise' for some types of exceptions if we wanted
280                                        print_exception(e)
281                                        ok = 0
282                                tests_failed += int(not ok)
283                                tests_total += 1
284                                dotOK += '.' if ok else test_name[0] if len(test_name)>0 else '?'
285                elif command == "RUNTEST":
286                        if is_test_active():
287                                print("\t", command, end=" ")
288                                try:
289                                        ok = test(args, test_name, input_text, output_net, output_msg, exe_prog, exeargs)
290                                except Exception as e: # could also 'raise' for some types of exceptions if we wanted
291                                        print_exception(e)
292                                        ok = 0
293                                tests_failed += int(not ok)
294                                tests_total += 1
295                                dotOK += '.' if ok else test_name[0] if len(test_name)>0 else '?'
296                else:
297                        raise Exception("Don't know what to do with this line in test file: ", line)
298
299        return (tests_failed, tests_total, dotOK)
300
301
302if __name__ == "__main__":
303        tests_failed, tests_total, dotOK = main()
304        print("TestsDotOK:%s(%d)" % (dotOK, tests_failed));
305        print("%d / %d failed tests" % (tests_failed, tests_total))
306        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.