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[ONPpRrC]):\s*(.*)$')
168 self.fileformat = re.compile(r'^((\>\>?)[,\s]\s*)?([^\s]+)\s*$')
172 def open(self, filename):
173 if not self.cntrfile is None:
174 self.cntrfile.close()
177 m = self.fileformat.match(filename)
180 filename = m.group(3)
187 self.cntrname = filename
189 self.cntrfile = open(filename, 'a')
191 self.cntrfile = open(filename, 'w')
194 if not self.cntrfile is None:
195 self.cntrfile.close()
198 # make the method below 'private'
199 def __addline(self, pat):
200 self.cntrfile.writelines(pat + "\n")
205 def dispatch(self, c):
206 m = self.control.match(c)
213 elif command == "CC":
216 if self.cntrfile is None:
217 print("Controlfile not initialized")
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)
230 die(1,"Error, Unrecognised Command '" + command + "'")
234 def get_proc_pid(proc_name):
235 pid=os.popen("pidof " + proc_name).read().rstrip()
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")
243 m = wlistreg.match(item)
248 if win_id != ignoreid:
255 fname = '/proc/' + lyx_pid + '/status'
256 return os.path.exists(fname)
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
265 if os.WIFSIGNALED(ret):
266 raise KeyboardInterrupt
267 if ret != 0 and not ignore_err:
268 raise BaseException("command failed:" + cmd)
271 statreg = re.compile(r'^State:.*\(([a-z]+)\)')
274 def printresstatus():
275 for line in resstatus:
277 print(" " + line.rstrip())
278 print('End of /proc-lines')
280 def lyx_status_retry(pid):
285 fname = '/proc/' + pid + '/status'
291 resstatus.extend([line])
292 m = statreg.match(line)
301 print("I/O error({0}): {1}".format(e.errno, e.strerror))
304 print("Unexpected error:", sys.exc_info()[0])
306 print('This should not happen')
312 status = lyx_status_retry(pid)
313 if status != "retry":
316 print('Retrying check for status')
320 print('Retried to read status ' + str(count) + ' times')
321 #print('lys_status() returning ' + status)
324 # Return true if LyX (identified via lyx_pid) is sleeping
325 def lyx_sleeping(LYX_PID):
326 return lyx_status(LYX_PID) == "sleeping"
328 # Return true if LyX (identified via lyx_pid) is zombie
329 def lyx_zombie(LYX_PID):
330 return lyx_status(LYX_PID) == "zombie"
332 def lyx_dead(LYX_PID):
333 status = lyx_status(LYX_PID)
334 return (status == "dead") or (status == "zombie")
336 def wait_until_lyx_sleeping(LYX_PID):
337 before_secs = time.time()
339 status = lyx_status(LYX_PID)
340 if status == "sleeping":
342 if (status == "dead") or (status == "zombie"):
345 print('Lyx died while waiting for status == sleeping')
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")
353 die(1,"Killing due to freeze (KILL_FREEZE)")
355 # Should be never reached
356 print('Wait for sleeping ends unexpectedly')
359 def sendKeystringLocal(keystr, LYX_PID):
360 is_sleeping = wait_until_lyx_sleeping(LYX_PID)
362 print("Not sending \"" + keystr + "\"")
364 if not screenshot_out is None:
365 print('Making Screenshot: ' + screenshot_out + ' OF ' + infilename)
367 intr_system('import -window root '+screenshot_out+str(x.count)+".png")
369 actual_delay = key_delay
370 if actual_delay == '':
371 actual_delay = def_delay
373 if qt_frontend == 'QT5':
374 xvpar.extend(["-jump-pointer", "-no-back-pointer"])
376 xvpar.extend(["-xsendevent"])
377 if lyx_other_window_name is None:
378 xvpar.extend(["-window", lyx_window_name])
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)
386 Axreg = re.compile(r'^(.*)\\Ax([^\\]*)(.*)$')
387 returnreg = re.compile(r'(\\\[[A-Z][a-z0-9]+\])(.*)$')
389 # recursive wrapper around sendKeystringLocal()
390 # handling \Ax-entries
391 def sendKeystringAx(line, LYX_PID):
393 saved_delay = key_delay
394 m = Axreg.match(line)
400 # since (.*) is greedy, check prefix for '\Ax' again
401 sendKeystringAx(prefix, LYX_PID)
402 sendKeystringLocal('\Ax', LYX_PID)
404 m2 = returnreg.match(rest)
409 sendKeystringLocal(content + ctrlk, LYX_PID)
410 key_delay = saved_delay
411 time.sleep(controlkey_delay)
413 sendKeystringLocal(line, LYX_PID)
416 sendKeystringLocal(content, LYX_PID)
418 sendKeystringLocal(rest, LYX_PID)
421 sendKeystringLocal(line, LYX_PID)
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
426 def sendKeystringAC(line, LYX_PID):
427 m = specialkeyreg.match(line)
431 sendKeystringAC(first, LYX_PID)
432 sendKeystringAC(second, LYX_PID)
434 sendKeystringAx(line, LYX_PID)
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)
445 sendKeystringRT(first, LYX_PID)
446 time.sleep(controlkey_delay)
447 sendKeystringRT(second, LYX_PID)
448 time.sleep(controlkey_delay)
450 sendKeystringRT(third, LYX_PID)
452 sendKeystringAC(line, LYX_PID)
454 def system_retry(num_retry, cmd):
456 rtn = intr_system(cmd)
457 while ( ( i < num_retry ) and ( rtn != 0) ):
459 rtn = intr_system(cmd)
462 print("Command Failed: "+cmd)
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+"'")
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')
484 max_loops = os.environ.get('MAX_LOOPS')
485 if max_loops is None:
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'])
494 PACKAGE = os.environ.get('PACKAGE')
495 if not PACKAGE is None:
496 print("PACKAGE = " + PACKAGE + "\n")
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")
502 lyx = os.environ.get('LYX')
506 lyx_exe = os.environ.get('LYX_EXE')
510 xvkbd_exe = os.environ.get('XVKBD_EXE')
511 if xvkbd_exe is None:
514 qt_frontend = os.environ.get('QT_FRONTEND')
515 if qt_frontend is None:
517 if qt_frontend == 'QT5':
518 controlkey_delay = 0.01
520 controlkey_delay = 0.4
522 locale_dir = os.environ.get('LOCALE_DIR')
523 if locale_dir is None:
526 def_delay = os.environ.get('XVKBD_DELAY')
527 if def_delay is None:
528 if qt_frontend == 'QT5':
533 file_new_command = os.environ.get('FILE_NEW_COMMAND')
534 if file_new_command is None:
535 file_new_command = "\Afn"
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"
542 if lyx_window_name is None:
543 lyx_window_name = 'LyX'
545 print('outfilename: ' + outfilename + '\n')
546 print('max_drop: ' + max_drop + '\n')
548 if infilename is None:
549 print('infilename is None\n')
551 print('Using x=CommandSource\n')
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)
558 x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
559 print('Using x=CommandSourceFromFile\n')
561 outfile = open(outfilename, 'w')
563 if not lyx_pid is None:
565 # Next command is language dependent
566 #sendKeystringRT("\Afn", lyx_pid)
568 write_commands = True
570 lineempty = re.compile(r'^\s*$')
571 marked = ControlFile()
573 #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
578 # Do not strip trailing spaces, only check for 'empty' lines
579 if lineempty.match(c):
581 outfile.writelines(c + '\n')
583 if marked.dispatch(c):
586 print("Ignoring comment line: " + c)
587 elif c[0:9] == 'TestBegin':
589 lyx_pid=get_proc_pid(lyx)
591 print("Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n")
592 intr_system("killall " + lyx, True)
594 intr_system("killall -KILL " + lyx, True)
596 print("Starting LyX . . .")
597 if lyx_userdir is None:
598 intr_system(lyx_exe + c[9:] + "&")
600 intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
603 old_lyx_window_name = None
604 print("Waiting for LyX to show up . . .")
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
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
621 print('Timeout: could not start ' + lyx_exe, '\n')
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':
638 outfile = open(outfilename + '+', 'w')
640 elif c == 'RaiseLyx':
643 elif c[0:4] == 'KK: ':
645 sendKeystringRT(c[4:], lyx_pid)
647 ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
649 die(1, 'No path /proc/xxxx/status, exiting')
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)
657 sendKeystringRT(ResetCommand, lyx_pid)
658 elif c[0:6] == 'Assert':
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':
665 cmd = c[16:].rstrip()
666 if lyx_dead(lyx_pid):
667 print("LyX instance not found because of crash or assert !\n")
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)
674 while not lyx_dead(lyx_pid):
675 intr_system("kill -9 " + str(lyx_pid), True);
678 print("Executing " + cmd)
679 result = intr_system(cmd)
680 failed = failed or (result != 0)
681 print("result=" + str(result) + ", failed=" + str(failed))
683 print("failed=" + str(failed))
684 elif c[0:7] == 'TestEnd':
686 #lyx_other_window_name = None
687 if lyx_dead(lyx_pid):
688 print("LyX instance not found because of crash or assert !\n")
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)
700 is_sleeping = wait_until_lyx_sleeping(lyx_pid)
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
707 # probably waiting for Save/Discard/Abort, we select 'Discard'
708 sendKeystringRT("\[Tab]\[Return]", lyx_pid)
712 while not lyx_dead(lyx_pid):
715 print("LyX still up, killing process and waiting for it to die...\n")
716 intr_system("kill -9 " + str(lyx_pid), True);
720 print("Executing " + cmd)
721 result = intr_system(cmd)
722 failed = failed or (result != 0)
723 print("result=" + str(result) + ", failed=" + str(failed))
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(".")
740 print("Setting LANGUAGE=" + ccode)
741 os.environ['LANGUAGE'] = ccode
745 short_code = lang[0:idx]
748 lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
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()
756 print('Could not determine PACKAGE name needed for translations\n')
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
767 intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
769 intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
771 print("Unrecognised Command '" + c + "'\n")
774 print("Test case terminated: ")