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