]> git.lyx.org Git - features.git/blob - development/autotests/keytest.py
keytests: Wrong check for empty key in associative array
[features.git] / development / autotests / keytest.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # This script generates hundreds of random keypresses per second,
4 #  and sends them to the lyx window
5 # It requires xvkbd and wmctrl
6 # It generates a log of the KEYCODES it sends as development/keystest/out/KEYCODES
7 #
8 # Adapted by Tommaso Cucinotta from the original MonKey Test by
9 # John McCabe-Dansted.
10
11 from __future__ import print_function
12 import random
13 import os
14 import re
15 import sys
16 import time
17 import tempfile
18 import shutil
19
20 #from subprocess import call
21 import subprocess
22
23 print('Beginning keytest.py')
24
25 FNULL = open('/dev/null', 'w')
26
27 key_delay = ''
28 bindings = {}
29
30 # Ignore status == "dead" if this is set. Used at the last commands after "\Cq"
31 dead_expected = False
32
33 def die(excode, text):
34     if text != "":
35         print(text)
36     sys.stdout.flush()
37     os._exit(excode)
38
39 class CommandSource:
40
41     def __init__(self):
42         keycode = [
43             "\[Left]",
44             '\[Right]',
45             '\[Down]',
46             '\[Up]',
47             '\[BackSpace]',
48             '\[Delete]',
49             '\[Escape]',
50             ]
51         keycode[:0] = keycode
52         keycode[:0] = keycode
53
54         keycode[:0] = ['\\']
55
56         for k in range(97, 123):
57             keycode[:0] = chr(k)
58
59         for k in range(97, 123):
60             keycode[:0] = ["\A" + chr(k)]
61
62         for k in range(97, 123):
63             keycode[:0] = ["\A" + chr(k)]
64
65         for k in range(97, 123):
66             keycode[:0] = ["\C" + chr(k)]
67
68         self.keycode = keycode
69         self.count = 0
70         self.count_max = 1999
71
72     def getCommand(self):
73         self.count = self.count + 1
74         if self.count % 200 == 0:
75             return 'RaiseLyx'
76         elif self.count > self.count_max:
77             die(0, "")
78         else:
79             keystr = ''
80             for k in range(1, 2):
81                 keystr = keystr + self.keycode[random.randint(1,
82                         len(self.keycode)) - 1]
83             return 'KK: ' + keystr
84
85
86 class CommandSourceFromFile(CommandSource):
87
88     def __init__(self, filename, p):
89
90         self.infile = open(filename, 'r')
91         self.lines = self.infile.readlines()
92         self.infile.close()
93         linesbak = self.lines
94         self.p = p
95         print(p, self.p, 'self.p')
96         self.i = 0
97         self.count = 0
98         self.loops = 0
99
100         # Now we start randomly dropping lines, which we hope are redundant
101         # p is the probability that any given line will be removed
102
103         if p > 0.001:
104             if random.uniform(0, 1) < 0.5:
105                 print('randomdrop_independant\n')
106                 self.randomdrop_independant()
107             else:
108                 print('randomdrop_slice\n')
109                 self.randomdrop_slice()
110         if screenshot_out is None:
111             count_atleast = 100
112         else:
113             count_atleast = 1
114         self.max_count = max(len(self.lines) + 20, count_atleast)
115         if len(self.lines) < 1:
116             self.lines = linesbak
117
118     def randomdrop_independant(self):
119         p = self.p
120
121         # The next couple of lines are to ensure that at least one line is dropped
122
123         drop = random.randint(0, len(self.lines) - 1)
124         del self.lines[drop]
125         #p = p - 1 / len(self.lines)
126         origlines = self.lines
127         self.lines = []
128         for l in origlines:
129             if random.uniform(0, 1) < self.p:
130                 print('Randomly dropping line ' + l + '\n')
131             else:
132                 self.lines.append(l)
133         print('LINES\n')
134         print(self.lines)
135         sys.stdout.flush()
136
137     def randomdrop_slice(self):
138         lines = self.lines
139         if random.uniform(0, 1) < 0.4:
140             lines.append(lines[0])
141             del lines[0]
142         num_lines = len(lines)
143         max_drop = max(5, num_lines / 5)
144         num_drop = random.randint(1, 5)
145         drop_mid = random.randint(0, num_lines)
146         drop_start = max(drop_mid - num_drop / 2, 0)
147         drop_end = min(drop_start + num_drop, num_lines)
148         print(drop_start, drop_mid, drop_end)
149         print(lines)
150         del lines[drop_start:drop_end]
151         print(lines)
152         self.lines = lines
153
154     def getCommand(self):
155         if self.count >= self.max_count:
156             die(0, "")
157         if self.i >= len(self.lines):
158             self.loops = self.loops + 1
159             if self.loops >= int(max_loops):
160                 return None
161             self.i = 0
162             return 'Loop'
163         line = self.lines[self.i].rstrip('\n')
164         self.count = self.count + 1
165         self.i = self.i + 1
166         return line
167
168 class ControlFile:
169
170     def __init__(self):
171         self.control = re.compile(r'^(C[ONPpRrC]):\s*(.*)$')
172         self.fileformat = re.compile(r'^((\>\>?)[,\s]\s*)?([^\s]+)\s*$')
173         self.cntrname = None
174         self.cntrfile = None
175
176     def open(self, filename):
177         if not self.cntrfile is None:
178             self.cntrfile.close()
179             self.cntrfile = None
180             self.cntrname = None
181         m = self.fileformat.match(filename)
182         if m:
183             type = m.group(2)
184             filename = m.group(3)
185             if type == '>>':
186                 append = True
187             else:
188                 append = False
189         else:
190             append = False
191         self.cntrname = filename
192         if append:
193             self.cntrfile = open(filename, 'a')
194         else:
195             self.cntrfile = open(filename, 'w')
196
197     def close(self):
198         if not self.cntrfile is None:
199             self.cntrfile.close()
200             self.cntrfile = None
201             self.cntrname = None
202     # make the method below 'private'
203     def __addline(self, pat):
204         self.cntrfile.writelines(pat + "\n")
205
206     def getfname(self):
207         return self.cntrname
208
209     def dispatch(self, c):
210         m = self.control.match(c)
211         if not m:
212             return False
213         command = m.group(1)
214         text = m.group(2)
215         if command == "CO":
216             self.open(text);
217         elif command == "CC":
218             self.close()
219         else:
220             if not self.cntrfile is None:
221                 if command == "CN":
222                     self.__addline("Comment: " + text)
223                 elif command == "CP":
224                     self.__addline("Simple: " + text)
225                 elif command == "Cp":
226                     self.__addline("ErrSimple: " + text)
227                 elif command == "CR":
228                     self.__addline("Regex: " + text)
229                 elif command == "Cr":
230                     self.__addline("ErrRegex: " + text)
231                 else:
232                     die(1,"Error, Unrecognised Command '" + command + "'")
233         return True
234
235
236 def get_proc_pid(proc_name):
237     pid=os.popen("pidof " + proc_name).read().rstrip()
238     return pid
239
240 wlistreg = re.compile(r'^(0x[0-9a-f]{5,9})\s+[^\s]+\s+([0-9]+)\s.*$')
241 def get_proc_win_id(pid, ignoreid):
242     nlist = os.popen("wmctrl -l -p").read()
243     wlist = nlist.split("\n")
244     for item in wlist:
245         m = wlistreg.match(item)
246         if m:
247             win_id = m.group(1)
248             win_pid = m.group(2)
249             if win_pid == pid:
250                 if win_id != ignoreid:
251                     return win_id
252     return None
253
254 def lyx_exists():
255     if lyx_pid is None:
256         return False
257     fname = '/proc/' + lyx_pid + '/status'
258     return os.path.exists(fname)
259
260
261 # Interruptible os.system()
262 def intr_system(cmd, ignore_err = False):
263     print("Executing " + cmd)
264     # Assure the output of cmd does not overhaul
265     sys.stdout.flush()
266     ret = os.system(cmd)
267     if os.WIFSIGNALED(ret):
268         raise KeyboardInterrupt
269     if ret != 0 and not ignore_err:
270         raise BaseException("command failed:" + cmd)
271     return ret
272
273 statreg = re.compile(r'^State:.*\(([a-z]+)\)')
274
275 resstatus = []
276 def printresstatus():
277     for line in resstatus:
278         line = line.rstrip()
279         print("    " + line.rstrip())
280     print('End of /proc-lines')
281
282 def lyx_status_retry(pid):
283     resstatus = []
284     if pid is None:
285         print('Pid is None')
286         return "dead"
287     fname = '/proc/' + pid + '/status'
288     status = "dead"
289     try:
290         f = open(fname)
291         found = False
292         for line in f:
293             resstatus.extend([line])
294             m = statreg.match(line)
295             if m:
296                 status = m.group(1)
297                 found = True
298         f.close()
299         if not found:
300             return "retry"
301         return status
302     except IOError as e:
303         print("I/O error({0}): {1}".format(e.errno, e.strerror))
304         return "dead"
305     except:
306         print("Unexpected error:", sys.exc_info()[0])
307         return "dead"
308     print('This should not happen')
309     return status
310
311 def lyx_status(pid):
312     count = 0
313     while 1:
314         status = lyx_status_retry(pid)
315         if status != "retry":
316             break
317         if count == 0:
318             print('Retrying check for status')
319         count += 1
320         time.sleep(0.01)
321     if count > 1:
322         print('Retried to read status ' + str(count) + ' times')
323     #print('lys_status() returning ' + status)
324     return status
325
326 # Return true if LyX (identified via lyx_pid) is sleeping
327 def lyx_sleeping(LYX_PID):
328     return lyx_status(LYX_PID) == "sleeping"
329
330 # Return true if LyX (identified via lyx_pid) is zombie
331 def lyx_zombie(LYX_PID):
332     return lyx_status(LYX_PID) == "zombie"
333
334 def lyx_dead(LYX_PID):
335     status = lyx_status(LYX_PID)
336     return (status == "dead") or (status == "zombie")
337
338 def wait_until_lyx_sleeping(LYX_PID):
339     before_secs = time.time()
340     while True:
341         status = lyx_status(LYX_PID)
342         if status == "sleeping":
343             return True
344         if (status == "dead") or (status == "zombie"):
345             printresstatus()
346             if dead_expected:
347                 print('Lyx died while waiting for status == sleeping')
348                 return False
349             else:
350                 die(1,"Lyx is dead, exiting")
351         if time.time() - before_secs > 180:
352             # Do profiling, but sysprof has no command line interface?
353             # intr_system("killall -KILL lyx")
354             printresstatus()
355             die(1,"Killing due to freeze (KILL_FREEZE)")
356         time.sleep(0.02)
357     # Should be never reached
358     print('Wait for sleeping ends unexpectedly')
359     return False
360
361 def sendKeystringLocal(keystr, LYX_PID):
362     is_sleeping = wait_until_lyx_sleeping(LYX_PID)
363     if not is_sleeping:
364         print("Not sending \"" + keystr + "\"")
365         return
366     if not screenshot_out is None:
367         print('Making Screenshot: ' + screenshot_out + ' OF ' + infilename)
368         time.sleep(0.2)
369         intr_system('import -window root '+screenshot_out+str(x.count)+".png")
370         time.sleep(0.1)
371     actual_delay = key_delay
372     if actual_delay == '':
373         actual_delay = def_delay
374     xvpar = [xvkbd_exe]
375     if qt_frontend == 'QT5':
376         xvpar.extend(["-jump-pointer", "-no-back-pointer"])
377     else:
378         xvpar.extend(["-xsendevent"])
379     if lyx_other_window_name is None:
380         xvpar.extend(["-window", lyx_window_name])
381     else:
382         xvpar.extend(["-window", lyx_other_window_name])
383     xvpar.extend(["-delay", actual_delay, "-text", keystr])
384     print("Sending \"" + keystr + "\"")
385     subprocess.call(xvpar, stdout = FNULL, stderr = FNULL)
386     sys.stdout.flush()
387
388 Axreg = re.compile(r'^(.*)\\Ax([^\\]*)(.*)$')
389 returnreg = re.compile(r'(\\\[[A-Z][a-z0-9]+\])(.*)$')
390
391 # recursive wrapper around sendKeystringLocal()
392 # handling \Ax-entries
393 def sendKeystringAx(line, LYX_PID):
394     global key_delay
395     saved_delay = key_delay
396     m = Axreg.match(line)
397     if m:
398         prefix = m.group(1)
399         content = m.group(2)
400         rest = m.group(3);
401         if prefix != "":
402             # since (.*) is greedy, check prefix for '\Ax' again
403             sendKeystringAx(prefix, LYX_PID)
404         sendKeystringLocal('\Ax', LYX_PID)
405         time.sleep(0.1)
406         m2 = returnreg.match(rest)
407         if m2:
408             line = m2.group(2)
409             ctrlk = m2.group(1)
410             key_delay = "1"
411             sendKeystringLocal(content + ctrlk, LYX_PID)
412             key_delay = saved_delay
413             time.sleep(controlkey_delay)
414             if line != "":
415                 sendKeystringLocal(line, LYX_PID)
416         else:
417             if content != "":
418                 sendKeystringLocal(content, LYX_PID)
419             if rest != "":
420                 sendKeystringLocal(rest, LYX_PID)
421     else:
422         if line != "":
423             sendKeystringLocal(line, LYX_PID)
424
425 specialkeyreg = re.compile(r'(.+)(\\[AC]([a-zA-Z]|\\\[[A-Z][a-z0-9]+\]).*)$')
426 # Split line at start of each meta or controll char
427
428 def sendKeystringAC(line, LYX_PID):
429     m = specialkeyreg.match(line)
430     if m:
431         first = m.group(1)
432         second = m.group(2)
433         sendKeystringAC(first, LYX_PID)
434         sendKeystringAC(second, LYX_PID)
435     else:
436         sendKeystringAx(line, LYX_PID)
437
438 controlkeyreg = re.compile(r'^(.*\\\[[A-Z][a-z0-9]+\])(.*\\\[[A-Z][a-z0-9]+\])(.*)$')
439 # Make sure, only one of \[Return], \[Tab], \[Down], \[Home] etc are in one sent line
440 # e.g. split the input line on each keysym
441 def sendKeystringRT(line, LYX_PID):
442     m = controlkeyreg.match(line)
443     if m:
444         first = m.group(1)
445         second = m.group(2)
446         third = m.group(3)
447         sendKeystringRT(first, LYX_PID)
448         time.sleep(controlkey_delay)
449         sendKeystringRT(second, LYX_PID)
450         time.sleep(controlkey_delay)
451         if third != "":
452             sendKeystringRT(third, LYX_PID)
453     else:
454         sendKeystringAC(line, LYX_PID)
455
456 def system_retry(num_retry, cmd):
457     i = 0
458     rtn = intr_system(cmd, True)
459     while ( ( i < num_retry ) and ( rtn != 0) ):
460         i = i + 1
461         rtn = intr_system(cmd, True)
462         time.sleep(1)
463     if ( rtn != 0 ):
464         print("Command Failed: "+cmd)
465         die(1," EXITING!")
466
467 def RaiseWindow():
468     #intr_system("echo x-session-manager PID: $X_PID.")
469     #intr_system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
470     ####intr_system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
471     print("lyx_window_name = " + lyx_window_name + "\n")
472     intr_system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
473     system_retry(30, "wmctrl -i -a '"+lyx_window_name+"'")
474
475 shortcut_entry = re.compile(r'^\s*"([^"]+)"\s*\"([^"]+)\"')
476 def UseShortcut(c):
477     m = shortcut_entry.match(c)
478     if m:
479         sh = m.group(1)
480         fkt = m.group(2)
481         bindings[sh] = fkt
482     else:
483         die(1, "cad shortcut spec(" + c + ")")
484
485 def PrepareShortcuts():
486     bind = re.compile(r'^\s*\\bind\s+"([^"]+)"')
487     if lyx_userdir_ver is None:
488         dir = lyx_userdir
489     else:
490         dir = lyx_userdir_ver
491     if not dir is None:
492         tmp = tempfile.NamedTemporaryFile(suffix='.bind', delete=False)
493         try:
494             old = open(dir + '/bind/user.bind', 'r')
495         except IOError as e:
496             old = None
497         if not old is None:
498             lines = old.read().split("\n")
499             old.close()
500             bindfound = False
501             for line in lines:
502                 m = bind.match(line)
503                 if m:
504                     bindfound = True
505                     val = m.group(1)
506                     if val in bindings:
507                         if bindings[val] != "":
508                             tmp.write("\\bind \"" + val + "\" \"" + bindings[val] + "\"\n")
509                             bindings[val] = ""
510                     else:
511                         tmp.write(line + '\n')
512                 elif not bindfound:
513                     tmp.write(line + '\n')
514         else:
515             tmp.writelines(
516                 '## This file is used for keytests only\n\n' +
517                 'Format 4\n\n'
518             )
519         for val in bindings:
520             if not bindings[val] is None:
521                 if  bindings[val] != "":
522                     tmp.write("\\bind \"" + val + "\" \"" + bindings[val] + "\"\n")
523                     bindings[val] = ""
524         tmp.close()
525         shutil.move(tmp.name, dir + '/bind/user.bind')
526     else:
527         print("User dir not specified")
528
529 lyx_pid = os.environ.get('LYX_PID')
530 print('lyx_pid: ' + str(lyx_pid) + '\n')
531 infilename = os.environ.get('KEYTEST_INFILE')
532 outfilename = os.environ.get('KEYTEST_OUTFILE')
533 max_drop = os.environ.get('MAX_DROP')
534 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
535 lyx_other_window_name = None
536 screenshot_out = os.environ.get('SCREENSHOT_OUT')
537 lyx_userdir = os.environ.get('LYX_USERDIR')
538 lyx_userdir_ver = os.environ.get('LYX_USERDIR_23x')
539
540 max_loops = os.environ.get('MAX_LOOPS')
541 if max_loops is None:
542     max_loops = 3
543
544 extra_path = os.environ.get('EXTRA_PATH')
545 if not extra_path is None:
546   os.environ['PATH'] = extra_path + os.pathsep + os.environ['PATH']
547   print("Added " + extra_path + " to path")
548   print(os.environ['PATH'])
549
550 PACKAGE = os.environ.get('PACKAGE')
551 if not PACKAGE is None:
552   print("PACKAGE = " + PACKAGE + "\n")
553
554 PO_BUILD_DIR = os.environ.get('PO_BUILD_DIR')
555 if not PO_BUILD_DIR is None:
556   print("PO_BUILD_DIR = " + PO_BUILD_DIR + "\n")
557
558 lyx = os.environ.get('LYX')
559 if lyx is None:
560     lyx = "lyx"
561
562 lyx_exe = os.environ.get('LYX_EXE')
563 if lyx_exe is None:
564     lyx_exe = lyx
565
566 xvkbd_exe = os.environ.get('XVKBD_EXE')
567 if xvkbd_exe is None:
568     xvkbd_exe = "xvkbd"
569
570 qt_frontend = os.environ.get('QT_FRONTEND')
571 if qt_frontend is None:
572     qt_frontend = 'QT4'
573 if qt_frontend == 'QT5':
574     controlkey_delay = 0.01
575 else:
576     controlkey_delay = 0.4
577
578 locale_dir = os.environ.get('LOCALE_DIR')
579 if locale_dir is None:
580     locale_dir = '.'
581
582 def_delay = os.environ.get('XVKBD_DELAY')
583 if def_delay is None:
584     if qt_frontend == 'QT5':
585         def_delay = '1'
586     else:
587         def_delay = '1'
588
589 file_new_command = os.environ.get('FILE_NEW_COMMAND')
590 if file_new_command is None:
591     file_new_command = "\Afn"
592
593 ResetCommand = os.environ.get('RESET_COMMAND')
594 if ResetCommand is None:
595     ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
596     #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
597
598 if lyx_window_name is None:
599     lyx_window_name = 'LyX'
600
601 print('outfilename: ' + outfilename + '\n')
602 print('max_drop: ' + max_drop + '\n')
603
604 if infilename is None:
605     print('infilename is None\n')
606     x = CommandSource()
607     print('Using x=CommandSource\n')
608 else:
609     print('infilename: ' + infilename + '\n')
610     probability_we_drop_a_command = random.uniform(0, float(max_drop))
611     print('probability_we_drop_a_command: ')
612     print('%s' % probability_we_drop_a_command)
613     print('\n')
614     x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
615     print('Using x=CommandSourceFromFile\n')
616
617 outfile = open(outfilename, 'w')
618
619 if not lyx_pid is None:
620     RaiseWindow()
621     # Next command is language dependent
622     #sendKeystringRT("\Afn", lyx_pid)
623
624 write_commands = True
625 failed = False
626 lineempty = re.compile(r'^\s*$')
627 marked = ControlFile()
628 while not failed:
629     #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
630     c = x.getCommand()
631     if c is None:
632         break
633
634     # Do not strip trailing spaces, only check for 'empty' lines
635     if lineempty.match(c):
636         continue
637     outfile.writelines(c + '\n')
638     outfile.flush()
639     if marked.dispatch(c):
640         continue
641     if c[0] == '#':
642         print("Ignoring comment line: " + c)
643     elif c[0:9] == 'TestBegin':
644         print("\n")
645         lyx_pid=get_proc_pid(lyx)
646         if lyx_pid != "":
647             print("Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n")
648             intr_system("killall " + lyx, True)
649             time.sleep(0.5)
650             intr_system("killall -KILL " + lyx, True)
651             time.sleep(0.2)
652         print("Starting LyX . . .")
653         if lyx_userdir is None:
654             intr_system(lyx_exe + c[9:] + "&")
655         else:
656             intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
657         count = 10
658         old_lyx_pid = "-7"
659         old_lyx_window_name = None
660         print("Waiting for LyX to show up . . .")
661         while count > 0:
662             lyx_pid=get_proc_pid(lyx)
663             if lyx_pid != old_lyx_pid:
664                 print('lyx_pid=' + lyx_pid)
665                 old_lyx_pid = lyx_pid
666             if lyx_pid != "":
667                 lyx_window_name=get_proc_win_id(lyx_pid, "")
668                 if not lyx_window_name is None:
669                     if old_lyx_window_name != lyx_window_name:
670                         print('lyx_win=' + lyx_window_name, '\n')
671                         old_lyx_window_name = lyx_window_name
672                     break
673             else:
674                 count = count - 1
675             time.sleep(0.5)
676         if count <= 0:
677             print('Timeout: could not start ' + lyx_exe, '\n')
678             sys.stdout.flush()
679             failed = True
680         else:
681             print('lyx_pid: ' + lyx_pid)
682             print('lyx_win: ' + lyx_window_name)
683             dead_expected = False
684             sendKeystringLocal("\C\[Home]", lyx_pid)
685             time.sleep(controlkey_delay)
686     elif c[0:5] == 'Sleep':
687         print("Sleeping for " + c[6:] + " seconds")
688         time.sleep(float(c[6:]))
689     elif c[0:4] == 'Exec':
690         cmd = c[5:].rstrip()
691         intr_system(cmd)
692     elif c == 'Loop':
693         outfile.close()
694         outfile = open(outfilename + '+', 'w')
695         print('Now Looping')
696     elif c == 'RaiseLyx':
697         print('Raising Lyx')
698         RaiseWindow()
699     elif c == 'PrepareShortcuts':
700         print('Preparing usefull sortcuts for tests')
701         PrepareShortcuts()
702     elif c[0:12] == 'UseShortcut ':
703         UseShortcut(c[12:])
704     elif c[0:4] == 'KK: ':
705         if lyx_exists():
706             sendKeystringRT(c[4:], lyx_pid)
707         else:
708             ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
709             if lyx_pid is None:
710               die(1, 'No path /proc/xxxx/status, exiting')
711             else:
712               die(1, 'No path /proc/' + lyx_pid + '/status, exiting')
713     elif c[0:4] == 'KD: ':
714         key_delay = c[4:].rstrip('\n')
715         print('Setting DELAY to ' + key_delay)
716     elif c == 'Loop':
717         RaiseWindow()
718         sendKeystringRT(ResetCommand, lyx_pid)
719     elif c[0:6] == 'Assert':
720         cmd = c[7:].rstrip()
721         result = intr_system(cmd, True)
722         failed = failed or (result != 0)
723         print("result=" + str(result) + ", failed=" + str(failed))
724     elif c[0:15] == 'TestEndWithKill':
725         marked.close()
726         cmd = c[16:].rstrip()
727         if lyx_dead(lyx_pid):
728             print("LyX instance not found because of crash or assert !\n")
729             failed = True
730         else:
731             print("    ------------    Forcing kill of lyx instance: " + str(lyx_pid) + "    ------------")
732             # This line below is there only to allow lyx to update its log-file
733             sendKeystringLocal("\[Escape]", lyx_pid)
734             dead_expected = True
735             while not lyx_dead(lyx_pid):
736                 intr_system("kill -9 " + str(lyx_pid), True);
737                 time.sleep(0.5)
738             if cmd != "":
739                 print("Executing " + cmd)
740                 result = intr_system(cmd, True)
741                 failed = failed or (result != 0)
742                 print("result=" + str(result) + ", failed=" + str(failed))
743             else:
744                 print("failed=" + str(failed))
745     elif c[0:7] == 'TestEnd':
746          #lyx_other_window_name = None
747         if lyx_dead(lyx_pid):
748             print("LyX instance not found because of crash or assert !\n")
749             marked.close()
750             failed = True
751         else:
752             print("    ------------    Forcing quit of lyx instance: " + str(lyx_pid) + "    ------------")
753             # \[Escape]+ should work as RESET focus to main window
754             sendKeystringAx("\[Escape]\[Escape]\[Escape]\[Escape]", lyx_pid)
755             time.sleep(controlkey_delay)
756             # now we should be outside any dialog
757             # and so the function lyx-quit should work
758             sendKeystringLocal("\Cq", lyx_pid)
759             marked.dispatch('CP: action=lyx-quit')
760             marked.close()
761             time.sleep(0.5)
762             dead_expected = True
763             is_sleeping = wait_until_lyx_sleeping(lyx_pid)
764             if is_sleeping:
765                 print('wait_until_lyx_sleeping() indicated "sleeping"')
766                 # For a short time lyx-status is 'sleeping', even if it is nearly dead.
767                 # Without the wait below, the \[Tab]-char is sent to nirvana
768                 # causing a 'beep'
769                 time.sleep(0.5)
770                 # probably waiting for Save/Discard/Abort, we select 'Discard'
771                 sendKeystringRT("\[Tab]\[Return]", lyx_pid)
772                 lcount = 0
773             else:
774                 lcount = 1
775             while not lyx_dead(lyx_pid):
776                 lcount = lcount + 1
777                 if lcount > 20:
778                     print("LyX still up, killing process and waiting for it to die...\n")
779                     intr_system("kill -9 " + str(lyx_pid), True);
780                 time.sleep(0.5)
781         cmd = c[8:].rstrip()
782         if cmd != "":
783             print("Executing " + cmd)
784             result = intr_system(cmd, True)
785             failed = failed or (result != 0)
786             print("result=" + str(result) + ", failed=" + str(failed))
787         else:
788             print("failed=" + str(failed))
789     elif c[0:4] == 'Lang':
790         lang = c[5:].rstrip()
791         print("Setting LANG=" + lang)
792         os.environ['LANG'] = lang
793         os.environ['LC_ALL'] = lang
794 # If it doesn't exist, create a link <locale_dir>/<country-code>/LC_MESSAGES/lyx<version-suffix>.mo
795 # pointing to the corresponding .gmo file. Needed to let lyx find the right translation files.
796 # See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg165613.html
797         idx = lang.rfind(".")
798         if idx != -1:
799             ccode = lang[0:idx]
800         else:
801             ccode = lang
802
803         print("Setting LANGUAGE=" + ccode)
804         os.environ['LANGUAGE'] = ccode
805
806         idx = lang.find("_")
807         if idx != -1:
808             short_code = lang[0:idx]
809         else:
810             short_code = ccode
811         lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
812         if PACKAGE is None:
813           # on cmake-build there is no Makefile in this directory
814           # so PACKAGE has to be provided
815           if os.path.exists(lyx_dir + "/Makefile"):
816             print("Executing: grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'")
817             lyx_name = os.popen("grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'").read().rstrip()
818           else:
819             print('Could not determine PACKAGE name needed for translations\n')
820             failed = True
821         else:
822           lyx_name = PACKAGE
823         intr_system("mkdir -p " + locale_dir + "/" + ccode + "/LC_MESSAGES")
824         intr_system("rm -f " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
825         if PO_BUILD_DIR is None:
826             if lyx_dir[0:3] == "../":
827                 rel_dir = "../../" + lyx_dir
828             else:
829                 rel_dir = lyx_dir
830             intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
831         else:
832             intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
833     else:
834         print("Unrecognised Command '" + c + "'\n")
835         failed = True
836
837 print("Test case terminated: ")
838 if failed:
839     die(1,"FAIL")
840 else:
841     die(0, "Ok")