source: tester/tester.py @ 985

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

Added support for Anaconda Windows Python running under CYGWIN

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