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')
26 # Ignore status == "dead" if this is set. Used at the last commands after "\Cq"
29 def die(excode, text):
52 for k in range(97, 123):
55 for k in range(97, 123):
56 keycode[:0] = ["\A" + chr(k)]
58 for k in range(97, 123):
59 keycode[:0] = ["\A" + chr(k)]
61 for k in range(97, 123):
62 keycode[:0] = ["\C" + chr(k)]
64 self.keycode = keycode
69 self.count = self.count + 1
70 if self.count % 200 == 0:
72 elif self.count > self.count_max:
77 keystr = keystr + self.keycode[random.randint(1,
78 len(self.keycode)) - 1]
79 return 'KK: ' + keystr
82 class CommandSourceFromFile(CommandSource):
84 def __init__(self, filename, p):
86 self.infile = open(filename, 'r')
87 self.lines = self.infile.readlines()
91 print(p, self.p, 'self.p')
96 # Now we start randomly dropping lines, which we hope are redundant
97 # p is the probability that any given line will be removed
100 if random.uniform(0, 1) < 0.5:
101 print('randomdrop_independant\n')
102 self.randomdrop_independant()
104 print('randomdrop_slice\n')
105 self.randomdrop_slice()
106 if screenshot_out is None:
110 self.max_count = max(len(self.lines) + 20, count_atleast)
111 if len(self.lines) < 1:
112 self.lines = linesbak
114 def randomdrop_independant(self):
117 # The next couple of lines are to ensure that at least one line is dropped
119 drop = random.randint(0, len(self.lines) - 1)
121 #p = p - 1 / len(self.lines)
122 origlines = self.lines
125 if random.uniform(0, 1) < self.p:
126 print('Randomly dropping line ' + l + '\n')
133 def randomdrop_slice(self):
135 if random.uniform(0, 1) < 0.4:
136 lines.append(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)
146 del lines[drop_start:drop_end]
150 def getCommand(self):
151 if self.count >= self.max_count:
153 if self.i >= len(self.lines):
154 self.loops = self.loops + 1
155 if self.loops >= int(max_loops):
159 line = self.lines[self.i].rstrip('\n')
160 self.count = self.count + 1
167 self.control = re.compile(r'^(C[ONPRC]):\s*(.*)$')
171 def open(self, filename):
172 self.cntrname = filename
173 self.cntrfile = open(filename, 'w')
176 if not self.cntrfile is None:
177 self.cntrfile.close()
181 def addline(self, pat):
182 self.cntrfile.writelines(pat + "\n")
187 def dispatch(self, c):
188 m = self.control.match(c)
195 elif command == "CC":
198 if self.cntrfile is None:
199 print("Controlfile not initialized")
202 self.addline("Comment: " + text)
203 elif command == "CP":
204 self.addline("Simple: " + text)
205 elif command == "CR":
206 self.addline("Regex: " + text)
213 def get_proc_pid(proc_name):
214 pid=os.popen("pidof " + proc_name).read().rstrip()
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")
222 m = wlistreg.match(item)
227 if win_id != ignoreid:
234 fname = '/proc/' + lyx_pid + '/status'
235 return os.path.exists(fname)
238 # Interruptible os.system()
239 def intr_system(cmd, ignore_err = False):
240 print("Executing " + cmd)
242 if os.WIFSIGNALED(ret):
243 raise KeyboardInterrupt
244 if ret != 0 and not ignore_err:
245 raise BaseException("command failed:" + cmd)
248 statreg = re.compile(r'^State:.*\(([a-z]+)\)')
251 def printresstatus():
252 for line in resstatus:
254 print(" " + line.rstrip())
255 print('End of /proc-lines')
257 def lyx_status_retry(pid):
262 fname = '/proc/' + pid + '/status'
268 resstatus.extend([line])
269 m = statreg.match(line)
278 print("I/O error({0}): {1}".format(e.errno, e.strerror))
281 print("Unexpected error:", sys.exc_info()[0])
283 print('This should not happen')
289 status = lyx_status_retry(pid)
290 if status != "retry":
293 print('Retrying check for status')
297 print('Retried to read status ' + str(count) + ' times')
298 #print('lys_status() returning ' + status)
301 # Return true if LyX (identified via lyx_pid) is sleeping
302 def lyx_sleeping(LYX_PID):
303 return lyx_status(LYX_PID) == "sleeping"
305 # Return true if LyX (identified via lyx_pid) is zombie
306 def lyx_zombie(LYX_PID):
307 return lyx_status(LYX_PID) == "zombie"
309 def lyx_dead(LYX_PID):
310 status = lyx_status(LYX_PID)
311 return (status == "dead") or (status == "zombie")
313 def wait_until_lyx_sleeping(LYX_PID):
314 before_secs = time.time()
316 status = lyx_status(LYX_PID)
317 if status == "sleeping":
319 if (status == "dead") or (status == "zombie"):
322 print('Lyx died while waiting for status == sleeping')
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")
330 die(1,"Killing due to freeze (KILL_FREEZE)")
332 # Should be never reached
333 print('Wait for sleeping ends unexpectedly')
336 def sendKeystringLocal(keystr, LYX_PID):
337 is_sleeping = wait_until_lyx_sleeping(LYX_PID)
339 print("Not sending \"" + keystr + "\"")
341 if not screenshot_out is None:
342 print('Making Screenshot: ' + screenshot_out + ' OF ' + infilename)
344 intr_system('import -window root '+screenshot_out+str(x.count)+".png")
346 actual_delay = key_delay
347 if actual_delay == '':
348 actual_delay = def_delay
350 if qt_frontend == 'QT5':
351 xvpar.extend(["-jump-pointer", "-no-back-pointer"])
353 xvpar.extend(["-xsendevent"])
354 if lyx_other_window_name is None:
355 xvpar.extend(["-window", lyx_window_name])
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)
363 Axreg = re.compile(r'^(.*)\\Ax([^\\]*)(.*)$')
364 returnreg = re.compile(r'(\\\[[A-Z][a-z]+\])(.*)$')
366 # recursive wrapper around sendKeystringLocal()
367 # handling \Ax-entries
368 def sendKeystringAx(line, LYX_PID):
370 saved_delay = key_delay
371 m = Axreg.match(line)
377 # since (.*) is greedy, check prefix for '\Ax' again
378 sendKeystringAx(prefix, LYX_PID)
379 sendKeystringLocal('\Ax', LYX_PID)
381 m2 = returnreg.match(rest)
386 sendKeystringLocal(content + ctrlk, LYX_PID)
387 key_delay = saved_delay
388 time.sleep(controlkey_delay)
390 sendKeystringLocal(line, LYX_PID)
393 sendKeystringLocal(content, LYX_PID)
395 sendKeystringLocal(rest, LYX_PID)
398 sendKeystringLocal(line, LYX_PID)
400 specialkeyreg = re.compile(r'(.+)(\\[AC]([a-zA-Z]|\\\[[A-Z][a-z]+\]).*)$')
401 # Split line at start of each meta or controll char
403 def sendKeystringAC(line, LYX_PID):
404 m = specialkeyreg.match(line)
408 sendKeystringAC(first, LYX_PID)
409 sendKeystringAC(second, LYX_PID)
411 sendKeystringAx(line, LYX_PID)
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)
422 sendKeystringRT(first, LYX_PID)
423 time.sleep(controlkey_delay)
424 sendKeystringRT(second, LYX_PID)
425 time.sleep(controlkey_delay)
427 sendKeystringRT(third, LYX_PID)
429 sendKeystringAC(line, LYX_PID)
431 def system_retry(num_retry, cmd):
433 rtn = intr_system(cmd)
434 while ( ( i < num_retry ) and ( rtn != 0) ):
436 rtn = intr_system(cmd)
439 print("Command Failed: "+cmd)
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+"'")
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')
461 max_loops = os.environ.get('MAX_LOOPS')
462 if max_loops is None:
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'])
471 PACKAGE = os.environ.get('PACKAGE')
472 if not PACKAGE is None:
473 print("PACKAGE = " + PACKAGE + "\n")
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")
479 lyx = os.environ.get('LYX')
483 lyx_exe = os.environ.get('LYX_EXE')
487 xvkbd_exe = os.environ.get('XVKBD_EXE')
488 if xvkbd_exe is None:
491 qt_frontend = os.environ.get('QT_FRONTEND')
492 if qt_frontend is None:
494 if qt_frontend == 'QT5':
495 controlkey_delay = 0.01
497 controlkey_delay = 0.4
499 locale_dir = os.environ.get('LOCALE_DIR')
500 if locale_dir is None:
503 def_delay = os.environ.get('XVKBD_DELAY')
504 if def_delay is None:
505 if qt_frontend == 'QT5':
510 file_new_command = os.environ.get('FILE_NEW_COMMAND')
511 if file_new_command is None:
512 file_new_command = "\Afn"
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"
519 if lyx_window_name is None:
520 lyx_window_name = 'LyX'
522 print('outfilename: ' + outfilename + '\n')
523 print('max_drop: ' + max_drop + '\n')
525 if infilename is None:
526 print('infilename is None\n')
528 print('Using x=CommandSource\n')
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)
535 x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
536 print('Using x=CommandSourceFromFile\n')
538 outfile = open(outfilename, 'w')
540 if not lyx_pid is None:
542 # Next command is language dependent
543 #sendKeystringRT("\Afn", lyx_pid)
545 write_commands = True
547 lineempty = re.compile(r'^\s*$')
548 marked = ControlFile()
550 #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
555 # Do not strip trailing spaces, only check for 'empty' lines
556 if lineempty.match(c):
558 outfile.writelines(c + '\n')
560 if marked.dispatch(c):
563 print("Ignoring comment line: " + c)
564 elif c[0:9] == 'TestBegin':
566 lyx_pid=get_proc_pid(lyx)
568 print("Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n")
569 intr_system("killall " + lyx, True)
571 intr_system("killall -KILL " + lyx, True)
573 print("Starting LyX . . .")
574 if lyx_userdir is None:
575 intr_system(lyx_exe + c[9:] + "&")
577 intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
580 old_lyx_window_name = None
581 print("Waiting for LyX to show up . . .")
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
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
598 print('Timeout: could not start ' + lyx_exe, '\n')
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':
615 outfile = open(outfilename + '+', 'w')
617 elif c == 'RaiseLyx':
620 elif c[0:4] == 'KK: ':
622 sendKeystringRT(c[4:], lyx_pid)
624 ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
626 die(1, 'No path /proc/xxxx/status, exiting')
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)
634 sendKeystringRT(ResetCommand, lyx_pid)
635 elif c[0:6] == 'Assert':
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':
642 cmd = c[16:].rstrip()
643 if lyx_dead(lyx_pid):
644 print("LyX instance not found because of crash or assert !\n")
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)
651 while not lyx_dead(lyx_pid):
652 intr_system("kill -9 " + str(lyx_pid), True);
655 print("Executing " + cmd)
656 result = intr_system(cmd)
657 failed = failed or (result != 0)
658 print("result=" + str(result) + ", failed=" + str(failed))
660 print("failed=" + str(failed))
661 elif c[0:7] == 'TestEnd':
663 #lyx_other_window_name = None
664 if lyx_dead(lyx_pid):
665 print("LyX instance not found because of crash or assert !\n")
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)
678 is_sleeping = wait_until_lyx_sleeping(lyx_pid)
679 print("Leaved wait TestEnd")
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
686 # probably waiting for Save/Discard/Abort, we select 'Discard'
687 sendKeystringRT("\[Tab]\[Return]", lyx_pid)
691 while not lyx_dead(lyx_pid):
694 print("LyX still up, killing process and waiting for it to die...\n")
695 intr_system("kill -9 " + str(lyx_pid), True);
699 print("Executing " + cmd)
700 result = intr_system(cmd)
701 failed = failed or (result != 0)
702 print("result=" + str(result) + ", failed=" + str(failed))
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(".")
719 print("Setting LANGUAGE=" + ccode)
720 os.environ['LANGUAGE'] = ccode
724 short_code = lang[0:idx]
727 lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
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()
735 print('Could not determine PACKAGE name needed for translations\n')
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
746 intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
748 intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
750 print("Unrecognised Command '" + c + "'\n")
753 print("Test case terminated: ")