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