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
8 # Adapted by Tommaso Cucinotta from the original MonKey Test by
11 from __future__ import print_function
17 #from subprocess import call
20 print('Beginning keytest.py')
22 FNULL = open('/dev/null', 'w')
43 for k in range(97, 123):
46 for k in range(97, 123):
47 keycode[:0] = ["\A" + chr(k)]
49 for k in range(97, 123):
50 keycode[:0] = ["\A" + chr(k)]
52 for k in range(97, 123):
53 keycode[:0] = ["\C" + chr(k)]
55 self.keycode = keycode
60 self.count = self.count + 1
61 if self.count % 200 == 0:
63 elif self.count > self.count_max:
68 keystr = keystr + self.keycode[random.randint(1,
69 len(self.keycode)) - 1]
70 return 'KK: ' + keystr
73 class CommandSourceFromFile(CommandSource):
75 def __init__(self, filename, p):
77 self.infile = open(filename, 'r')
78 self.lines = self.infile.readlines()
82 print(p, self.p, 'self.p')
87 # Now we start randomly dropping lines, which we hope are redundant
88 # p is the probability that any given line will be removed
91 if random.uniform(0, 1) < 0.5:
92 print('randomdrop_independant\n')
93 self.randomdrop_independant()
95 print('randomdrop_slice\n')
96 self.randomdrop_slice()
97 if screenshot_out is None:
101 self.max_count = max(len(self.lines) + 20, count_atleast)
102 if len(self.lines) < 1:
103 self.lines = linesbak
105 def randomdrop_independant(self):
108 # The next couple of lines are to ensure that at least one line is dropped
110 drop = random.randint(0, len(self.lines) - 1)
112 #p = p - 1 / len(self.lines)
113 origlines = self.lines
116 if random.uniform(0, 1) < self.p:
117 print('Randomly dropping line ' + l + '\n')
124 def randomdrop_slice(self):
126 if random.uniform(0, 1) < 0.4:
127 lines.append(lines[0])
129 num_lines = len(lines)
130 max_drop = max(5, num_lines / 5)
131 num_drop = random.randint(1, 5)
132 drop_mid = random.randint(0, num_lines)
133 drop_start = max(drop_mid - num_drop / 2, 0)
134 drop_end = min(drop_start + num_drop, num_lines)
135 print(drop_start, drop_mid, drop_end)
137 del lines[drop_start:drop_end]
141 def getCommand(self):
142 if self.count >= self.max_count:
144 if self.i >= len(self.lines):
145 self.loops = self.loops + 1
146 if self.loops >= int(max_loops):
150 line = self.lines[self.i].rstrip('\n')
151 self.count = self.count + 1
155 def get_proc_pid(proc_name):
156 pid=os.popen("pidof " + proc_name).read().rstrip()
159 wlistreg = re.compile(r'^(0x[0-9a-f]{5,9})\s+[^\s]+\s+([0-9]+)\s.*$')
160 def get_proc_win_id(pid, ignoreid):
161 nlist = os.popen("wmctrl -l -p").read()
162 wlist = nlist.split("\n")
164 m = wlistreg.match(item)
169 if win_id != ignoreid:
176 fname = '/proc/' + lyx_pid + '/status'
177 return os.path.exists(fname)
180 # Interruptible os.system()
181 def intr_system(cmd, ignore_err = False):
182 print("Executing " + cmd)
184 if os.WIFSIGNALED(ret):
185 raise KeyboardInterrupt
186 if ret != 0 and not ignore_err:
187 raise BaseException("command failed:" + cmd)
190 statreg = re.compile(r'^State:.*\(([a-z]+)\)')
193 def printresstatus():
194 for line in resstatus:
196 print(" " + line.rstrip())
197 print('End of /proc-lines')
199 def lyx_status_retry(pid):
204 fname = '/proc/' + pid + '/status'
210 resstatus.extend([line])
211 m = statreg.match(line)
220 print("I/O error({0}): {1}".format(e.errno, e.strerror))
223 print("Unexpected error:", sys.exc_info()[0])
225 print('This should not happen')
231 status = lyx_status_retry(pid)
232 if status != "retry":
235 print('Retrying check for status')
239 print('Retried to read status ' + str(count) + ' times')
242 # Return true if LyX (identified via lyx_pid) is sleeping
244 return lyx_status(lyx_pid) == "sleeping"
246 # Return true if LyX (identified via lyx_pid) is zombie
248 return lyx_status(lyx_pid) == "zombie"
251 status = lyx_status(lyx_pid)
252 return (status == "dead") or (status == "zombie")
254 def wait_until_lyx_sleeping():
255 before_secs = time.time()
257 status = lyx_status(lyx_pid)
258 if status == "sleeping":
260 if (status == "dead") or (status == "zombie"):
261 print('Lyx is dead, exiting')
265 if time.time() - before_secs > 180:
266 print('Killing due to freeze (KILL_FREEZE)')
268 # Do profiling, but sysprof has no command line interface?
269 # intr_system("killall -KILL lyx")
275 def sendKeystringLocal(keystr, LYX_PID):
276 wait_until_lyx_sleeping()
277 if not screenshot_out is None:
278 print('Making Screenshot: ' + screenshot_out + ' OF ' + infilename)
280 intr_system('import -window root '+screenshot_out+str(x.count)+".png")
282 actual_delay = key_delay
283 if actual_delay == '':
284 actual_delay = def_delay
286 if qt_frontend == 'QT5':
287 xvpar.extend(["-jump-pointer", "-no-back-pointer"])
289 xvpar.extend(["-xsendevent"])
290 if lyx_other_window_name is None:
291 xvpar.extend(["-window", lyx_window_name])
293 xvpar.extend(["-window", lyx_other_window_name])
294 xvpar.extend(["-delay", actual_delay, "-text", keystr])
295 print("Sending \"" + keystr + "\"")
296 subprocess.call(xvpar, stdout = FNULL, stderr = FNULL)
299 Axreg = re.compile(r'^(.*)\\Ax([^\\]*)(.*)$')
300 returnreg = re.compile(r'(\\\[[A-Z][a-z]+\])(.*)$')
302 # recursive wrapper around sendKeystringLocal()
303 # handling \Ax-entries
304 def sendKeystringAx(line, LYX_PID):
306 saved_delay = key_delay
307 m = Axreg.match(line)
313 # since (.*) is greedy, check prefix for '\Ax' again
314 sendKeystringAx(prefix, LYX_PID)
315 sendKeystringLocal('\Ax', LYX_PID)
317 m2 = returnreg.match(rest)
322 sendKeystringLocal(content + ctrlk, LYX_PID)
323 key_delay = saved_delay
324 time.sleep(controlkey_delay)
326 sendKeystringLocal(line, LYX_PID)
329 sendKeystringLocal(content, LYX_PID)
331 sendKeystringLocal(rest, LYX_PID)
334 sendKeystringLocal(line, LYX_PID)
336 specialkeyreg = re.compile(r'(.+)(\\[AC]([a-zA-Z]|\\\[[A-Z][a-z]+\]).*)$')
337 # Split line at start of each meta or controll char
339 def sendKeystringAC(line, LYX_PID):
340 m = specialkeyreg.match(line)
344 sendKeystringAC(first, LYX_PID)
345 sendKeystringAC(second, LYX_PID)
347 sendKeystringAx(line, LYX_PID)
349 controlkeyreg = re.compile(r'^(.*\\\[[A-Z][a-z]+\])(.*\\\[[A-Z][a-z]+\])(.*)$')
350 # Make sure, only one of \[Return], \[Tab], \[Down], \[Home] etc are in one sent line
351 # e.g. split the input line on each keysym
352 def sendKeystringRT(line, LYX_PID):
353 m = controlkeyreg.match(line)
358 sendKeystringRT(first, LYX_PID)
359 time.sleep(controlkey_delay)
360 sendKeystringRT(second, LYX_PID)
361 time.sleep(controlkey_delay)
363 sendKeystringRT(third, LYX_PID)
365 sendKeystringAC(line, LYX_PID)
367 def system_retry(num_retry, cmd):
369 rtn = intr_system(cmd)
370 while ( ( i < num_retry ) and ( rtn != 0) ):
372 rtn = intr_system(cmd)
375 print("Command Failed: "+cmd)
380 #intr_system("echo x-session-manager PID: $X_PID.")
381 #intr_system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
382 ####intr_system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
383 print("lyx_window_name = " + lyx_window_name + "\n")
384 intr_system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
385 system_retry(30, "wmctrl -i -a '"+lyx_window_name+"'")
388 lyx_pid = os.environ.get('LYX_PID')
389 print('lyx_pid: ' + str(lyx_pid) + '\n')
390 infilename = os.environ.get('KEYTEST_INFILE')
391 outfilename = os.environ.get('KEYTEST_OUTFILE')
392 max_drop = os.environ.get('MAX_DROP')
393 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
394 lyx_other_window_name = None
395 screenshot_out = os.environ.get('SCREENSHOT_OUT')
396 lyx_userdir = os.environ.get('LYX_USERDIR')
398 max_loops = os.environ.get('MAX_LOOPS')
399 if max_loops is None:
402 PACKAGE = os.environ.get('PACKAGE')
403 if not PACKAGE is None:
404 print("PACKAGE = " + PACKAGE + "\n")
406 PO_BUILD_DIR = os.environ.get('PO_BUILD_DIR')
407 if not PO_BUILD_DIR is None:
408 print("PO_BUILD_DIR = " + PO_BUILD_DIR + "\n")
410 lyx = os.environ.get('LYX')
414 lyx_exe = os.environ.get('LYX_EXE')
418 xvkbd_exe = os.environ.get('XVKBD_EXE')
419 if xvkbd_exe is None:
422 qt_frontend = os.environ.get('QT_FRONTEND')
423 if qt_frontend is None:
425 if qt_frontend == 'QT5':
426 controlkey_delay = 0.01
428 controlkey_delay = 0.4
430 locale_dir = os.environ.get('LOCALE_DIR')
431 if locale_dir is None:
434 def_delay = os.environ.get('XVKBD_DELAY')
435 if def_delay is None:
436 if qt_frontend == 'QT5':
441 file_new_command = os.environ.get('FILE_NEW_COMMAND')
442 if file_new_command is None:
443 file_new_command = "\Afn"
445 ResetCommand = os.environ.get('RESET_COMMAND')
446 if ResetCommand is None:
447 ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
448 #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
450 if lyx_window_name is None:
451 lyx_window_name = 'LyX'
453 print('outfilename: ' + outfilename + '\n')
454 print('max_drop: ' + max_drop + '\n')
456 if infilename is None:
457 print('infilename is None\n')
459 print('Using x=CommandSource\n')
461 print('infilename: ' + infilename + '\n')
462 probability_we_drop_a_command = random.uniform(0, float(max_drop))
463 print('probability_we_drop_a_command: ')
464 print('%s' % probability_we_drop_a_command)
466 x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
467 print('Using x=CommandSourceFromFile\n')
469 outfile = open(outfilename, 'w')
471 if not lyx_pid is None:
473 # Next command is language dependent
474 #sendKeystringRT("\Afn", lyx_pid)
476 write_commands = True
478 lineempty = re.compile(r'^\s*$')
481 #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
486 # Do not strip trailing spaces, only check for 'empty' lines
487 if lineempty.match(c):
489 outfile.writelines(c + '\n')
492 print("Ignoring comment line: " + c)
493 elif c[0:9] == 'TestBegin':
495 lyx_pid=get_proc_pid(lyx)
497 print("Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n")
498 intr_system("killall " + lyx, True)
500 intr_system("killall -KILL " + lyx, True)
502 print("Starting LyX . . .")
503 if lyx_userdir is None:
504 intr_system(lyx_exe + c[9:] + "&")
506 intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
509 old_lyx_window_name = None
510 print("Waiting for LyX to show up . . .")
512 lyx_pid=get_proc_pid(lyx)
513 if lyx_pid != old_lyx_pid:
514 print('lyx_pid=' + lyx_pid)
515 old_lyx_pid = lyx_pid
517 lyx_window_name=get_proc_win_id(lyx_pid, "")
518 if not lyx_window_name is None:
519 if old_lyx_window_name != lyx_window_name:
520 print('lyx_win=' + lyx_window_name, '\n')
521 old_lyx_window_name = lyx_window_name
527 print('Timeout: could not start ' + lyx_exe, '\n')
531 print('lyx_pid: ' + lyx_pid)
532 print('lyx_win: ' + lyx_window_name)
533 sendKeystringLocal("\C\[Home]", lyx_pid)
534 time.sleep(controlkey_delay)
535 elif c[0:5] == 'Sleep':
536 print("Sleeping for " + c[6:] + " seconds")
537 time.sleep(float(c[6:]))
538 elif c[0:4] == 'Exec':
543 outfile = open(outfilename + '+', 'w')
545 elif c == 'RaiseLyx':
548 elif c[0:4] == 'KK: ':
550 sendKeystringRT(c[4:], lyx_pid)
552 ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
554 print('No path /proc/xxxx/status, exiting')
556 print('No path /proc/' + lyx_pid + '/status, exiting')
558 elif c[0:4] == 'KD: ':
559 key_delay = c[4:].rstrip('\n')
560 print('Setting DELAY to ' + key_delay)
563 sendKeystringRT(ResetCommand, lyx_pid)
564 elif c[0:6] == 'Assert':
566 result = intr_system(cmd)
567 failed = failed or (result != 0)
568 print("result=" + str(result) + ", failed=" + str(failed))
569 elif c[0:15] == 'TestEndWithKill':
570 cmd = c[16:].rstrip()
572 print("LyX instance not found because of crash or assert !\n")
575 print(" ------------ Forcing kill of lyx instance: " + str(lyx_pid) + " ------------")
576 # This line below is there only to allow lyx to update its log-file
577 sendKeystringLocal("\[Escape]", lyx_pid)
578 while not lyx_dead():
579 intr_system("kill -9 " + str(lyx_pid), True);
582 print("Executing " + cmd)
583 result = intr_system(cmd)
584 failed = failed or (result != 0)
585 print("result=" + str(result) + ", failed=" + str(failed))
587 print("failed=" + str(failed))
588 elif c[0:7] == 'TestEnd':
589 #lyx_other_window_name = None
591 print("LyX instance not found because of crash or assert !\n")
594 print(" ------------ Forcing quit of lyx instance: " + str(lyx_pid) + " ------------")
595 # \Ax Enter command line is sometimes blocked
596 # \[Escape] works after this
597 sendKeystringAx("\Ax\[Escape]", lyx_pid)
598 time.sleep(controlkey_delay)
599 # now we should be outside any dialog
600 # and so the function lyx-quit should work
601 sendKeystringLocal("\Cq", lyx_pid)
604 # probably waiting for Save/Discard/Abort, we select 'Discard'
605 sendKeystringRT("\[Tab]\[Return]", lyx_pid)
609 while not lyx_dead():
612 print("LyX still up, killing process and waiting for it to die...\n")
613 intr_system("kill -9 " + str(lyx_pid), True);
617 print("Executing " + cmd)
618 result = intr_system(cmd)
619 failed = failed or (result != 0)
620 print("result=" + str(result) + ", failed=" + str(failed))
622 print("failed=" + str(failed))
623 elif c[0:4] == 'Lang':
624 lang = c[5:].rstrip()
625 print("Setting LANG=" + lang)
626 os.environ['LANG'] = lang
627 os.environ['LC_ALL'] = lang
628 # If it doesn't exist, create a link <locale_dir>/<country-code>/LC_MESSAGES/lyx<version-suffix>.mo
629 # pointing to the corresponding .gmo file. Needed to let lyx find the right translation files.
630 # See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg165613.html
631 idx = lang.rfind(".")
637 print("Setting LANGUAGE=" + ccode)
638 os.environ['LANGUAGE'] = ccode
642 short_code = lang[0:idx]
645 lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
647 # on cmake-build there is no Makefile in this directory
648 # so PACKAGE has to be provided
649 if os.path.exists(lyx_dir + "/Makefile"):
650 print("Executing: grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'")
651 lyx_name = os.popen("grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'").read().rstrip()
653 print('Could not determine PACKAGE name needed for translations\n')
657 intr_system("mkdir -p " + locale_dir + "/" + ccode + "/LC_MESSAGES")
658 intr_system("rm -f " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
659 if PO_BUILD_DIR is None:
660 if lyx_dir[0:3] == "../":
661 rel_dir = "../../" + lyx_dir
664 intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
666 intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
668 print("Unrecognised Command '" + c + "'\n")
671 print("Test case terminated: ")