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"
46 for k in range(97, 123):
49 for k in range(97, 123):
50 keycode[:0] = ["\A" + chr(k)]
52 for k in range(97, 123):
53 keycode[:0] = ["\A" + chr(k)]
55 for k in range(97, 123):
56 keycode[:0] = ["\C" + chr(k)]
58 self.keycode = keycode
63 self.count = self.count + 1
64 if self.count % 200 == 0:
66 elif self.count > self.count_max:
71 keystr = keystr + self.keycode[random.randint(1,
72 len(self.keycode)) - 1]
73 return 'KK: ' + keystr
76 class CommandSourceFromFile(CommandSource):
78 def __init__(self, filename, p):
80 self.infile = open(filename, 'r')
81 self.lines = self.infile.readlines()
85 print(p, self.p, 'self.p')
90 # Now we start randomly dropping lines, which we hope are redundant
91 # p is the probability that any given line will be removed
94 if random.uniform(0, 1) < 0.5:
95 print('randomdrop_independant\n')
96 self.randomdrop_independant()
98 print('randomdrop_slice\n')
99 self.randomdrop_slice()
100 if screenshot_out is None:
104 self.max_count = max(len(self.lines) + 20, count_atleast)
105 if len(self.lines) < 1:
106 self.lines = linesbak
108 def randomdrop_independant(self):
111 # The next couple of lines are to ensure that at least one line is dropped
113 drop = random.randint(0, len(self.lines) - 1)
115 #p = p - 1 / len(self.lines)
116 origlines = self.lines
119 if random.uniform(0, 1) < self.p:
120 print('Randomly dropping line ' + l + '\n')
127 def randomdrop_slice(self):
129 if random.uniform(0, 1) < 0.4:
130 lines.append(lines[0])
132 num_lines = len(lines)
133 max_drop = max(5, num_lines / 5)
134 num_drop = random.randint(1, 5)
135 drop_mid = random.randint(0, num_lines)
136 drop_start = max(drop_mid - num_drop / 2, 0)
137 drop_end = min(drop_start + num_drop, num_lines)
138 print(drop_start, drop_mid, drop_end)
140 del lines[drop_start:drop_end]
144 def getCommand(self):
145 if self.count >= self.max_count:
147 if self.i >= len(self.lines):
148 self.loops = self.loops + 1
149 if self.loops >= int(max_loops):
153 line = self.lines[self.i].rstrip('\n')
154 self.count = self.count + 1
158 def get_proc_pid(proc_name):
159 pid=os.popen("pidof " + proc_name).read().rstrip()
162 wlistreg = re.compile(r'^(0x[0-9a-f]{5,9})\s+[^\s]+\s+([0-9]+)\s.*$')
163 def get_proc_win_id(pid, ignoreid):
164 nlist = os.popen("wmctrl -l -p").read()
165 wlist = nlist.split("\n")
167 m = wlistreg.match(item)
172 if win_id != ignoreid:
179 fname = '/proc/' + lyx_pid + '/status'
180 return os.path.exists(fname)
183 # Interruptible os.system()
184 def intr_system(cmd, ignore_err = False):
185 print("Executing " + cmd)
187 if os.WIFSIGNALED(ret):
188 raise KeyboardInterrupt
189 if ret != 0 and not ignore_err:
190 raise BaseException("command failed:" + cmd)
193 statreg = re.compile(r'^State:.*\(([a-z]+)\)')
196 def printresstatus():
197 for line in resstatus:
199 print(" " + line.rstrip())
200 print('End of /proc-lines')
202 def lyx_status_retry(pid):
207 fname = '/proc/' + pid + '/status'
213 resstatus.extend([line])
214 m = statreg.match(line)
223 print("I/O error({0}): {1}".format(e.errno, e.strerror))
226 print("Unexpected error:", sys.exc_info()[0])
228 print('This should not happen')
234 status = lyx_status_retry(pid)
235 if status != "retry":
238 print('Retrying check for status')
242 print('Retried to read status ' + str(count) + ' times')
243 #print('lys_status() returning ' + status)
246 # Return true if LyX (identified via lyx_pid) is sleeping
247 def lyx_sleeping(LYX_PID):
248 return lyx_status(LYX_PID) == "sleeping"
250 # Return true if LyX (identified via lyx_pid) is zombie
251 def lyx_zombie(LYX_PID):
252 return lyx_status(LYX_PID) == "zombie"
254 def lyx_dead(LYX_PID):
255 status = lyx_status(LYX_PID)
256 return (status == "dead") or (status == "zombie")
258 def wait_until_lyx_sleeping(LYX_PID):
259 before_secs = time.time()
261 status = lyx_status(LYX_PID)
262 if status == "sleeping":
264 if (status == "dead") or (status == "zombie"):
268 print('Lyx died while waiting for status == sleeping')
271 print('Lyx is dead, exiting')
273 if time.time() - before_secs > 180:
274 print('Killing due to freeze (KILL_FREEZE)')
276 # Do profiling, but sysprof has no command line interface?
277 # intr_system("killall -KILL lyx")
282 # Should be never reached
283 print('Wait for sleeping ends unexpectedly')
286 def sendKeystringLocal(keystr, LYX_PID):
287 is_sleeping = wait_until_lyx_sleeping(LYX_PID)
289 print("Not sending \"" + keystr + "\"")
291 if not screenshot_out is None:
292 print('Making Screenshot: ' + screenshot_out + ' OF ' + infilename)
294 intr_system('import -window root '+screenshot_out+str(x.count)+".png")
296 actual_delay = key_delay
297 if actual_delay == '':
298 actual_delay = def_delay
300 if qt_frontend == 'QT5':
301 xvpar.extend(["-jump-pointer", "-no-back-pointer"])
303 xvpar.extend(["-xsendevent"])
304 if lyx_other_window_name is None:
305 xvpar.extend(["-window", lyx_window_name])
307 xvpar.extend(["-window", lyx_other_window_name])
308 xvpar.extend(["-delay", actual_delay, "-text", keystr])
309 print("Sending \"" + keystr + "\"")
310 subprocess.call(xvpar, stdout = FNULL, stderr = FNULL)
313 Axreg = re.compile(r'^(.*)\\Ax([^\\]*)(.*)$')
314 returnreg = re.compile(r'(\\\[[A-Z][a-z]+\])(.*)$')
316 # recursive wrapper around sendKeystringLocal()
317 # handling \Ax-entries
318 def sendKeystringAx(line, LYX_PID):
320 saved_delay = key_delay
321 m = Axreg.match(line)
327 # since (.*) is greedy, check prefix for '\Ax' again
328 sendKeystringAx(prefix, LYX_PID)
329 sendKeystringLocal('\Ax', LYX_PID)
331 m2 = returnreg.match(rest)
336 sendKeystringLocal(content + ctrlk, LYX_PID)
337 key_delay = saved_delay
338 time.sleep(controlkey_delay)
340 sendKeystringLocal(line, LYX_PID)
343 sendKeystringLocal(content, LYX_PID)
345 sendKeystringLocal(rest, LYX_PID)
348 sendKeystringLocal(line, LYX_PID)
350 specialkeyreg = re.compile(r'(.+)(\\[AC]([a-zA-Z]|\\\[[A-Z][a-z]+\]).*)$')
351 # Split line at start of each meta or controll char
353 def sendKeystringAC(line, LYX_PID):
354 m = specialkeyreg.match(line)
358 sendKeystringAC(first, LYX_PID)
359 sendKeystringAC(second, LYX_PID)
361 sendKeystringAx(line, LYX_PID)
363 controlkeyreg = re.compile(r'^(.*\\\[[A-Z][a-z]+\])(.*\\\[[A-Z][a-z]+\])(.*)$')
364 # Make sure, only one of \[Return], \[Tab], \[Down], \[Home] etc are in one sent line
365 # e.g. split the input line on each keysym
366 def sendKeystringRT(line, LYX_PID):
367 m = controlkeyreg.match(line)
372 sendKeystringRT(first, LYX_PID)
373 time.sleep(controlkey_delay)
374 sendKeystringRT(second, LYX_PID)
375 time.sleep(controlkey_delay)
377 sendKeystringRT(third, LYX_PID)
379 sendKeystringAC(line, LYX_PID)
381 def system_retry(num_retry, cmd):
383 rtn = intr_system(cmd)
384 while ( ( i < num_retry ) and ( rtn != 0) ):
386 rtn = intr_system(cmd)
389 print("Command Failed: "+cmd)
394 #intr_system("echo x-session-manager PID: $X_PID.")
395 #intr_system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
396 ####intr_system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
397 print("lyx_window_name = " + lyx_window_name + "\n")
398 intr_system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
399 system_retry(30, "wmctrl -i -a '"+lyx_window_name+"'")
402 lyx_pid = os.environ.get('LYX_PID')
403 print('lyx_pid: ' + str(lyx_pid) + '\n')
404 infilename = os.environ.get('KEYTEST_INFILE')
405 outfilename = os.environ.get('KEYTEST_OUTFILE')
406 max_drop = os.environ.get('MAX_DROP')
407 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
408 lyx_other_window_name = None
409 screenshot_out = os.environ.get('SCREENSHOT_OUT')
410 lyx_userdir = os.environ.get('LYX_USERDIR')
412 max_loops = os.environ.get('MAX_LOOPS')
413 if max_loops is None:
416 extra_path = os.environ.get('EXTRA_PATH')
417 if not extra_path is None:
418 os.environ['PATH'] = extra_path + os.pathsep + os.environ['PATH']
419 print("Added " + extra_path + " to path")
420 print(os.environ['PATH'])
422 PACKAGE = os.environ.get('PACKAGE')
423 if not PACKAGE is None:
424 print("PACKAGE = " + PACKAGE + "\n")
426 PO_BUILD_DIR = os.environ.get('PO_BUILD_DIR')
427 if not PO_BUILD_DIR is None:
428 print("PO_BUILD_DIR = " + PO_BUILD_DIR + "\n")
430 lyx = os.environ.get('LYX')
434 lyx_exe = os.environ.get('LYX_EXE')
438 xvkbd_exe = os.environ.get('XVKBD_EXE')
439 if xvkbd_exe is None:
442 qt_frontend = os.environ.get('QT_FRONTEND')
443 if qt_frontend is None:
445 if qt_frontend == 'QT5':
446 controlkey_delay = 0.01
448 controlkey_delay = 0.4
450 locale_dir = os.environ.get('LOCALE_DIR')
451 if locale_dir is None:
454 def_delay = os.environ.get('XVKBD_DELAY')
455 if def_delay is None:
456 if qt_frontend == 'QT5':
461 file_new_command = os.environ.get('FILE_NEW_COMMAND')
462 if file_new_command is None:
463 file_new_command = "\Afn"
465 ResetCommand = os.environ.get('RESET_COMMAND')
466 if ResetCommand is None:
467 ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
468 #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
470 if lyx_window_name is None:
471 lyx_window_name = 'LyX'
473 print('outfilename: ' + outfilename + '\n')
474 print('max_drop: ' + max_drop + '\n')
476 if infilename is None:
477 print('infilename is None\n')
479 print('Using x=CommandSource\n')
481 print('infilename: ' + infilename + '\n')
482 probability_we_drop_a_command = random.uniform(0, float(max_drop))
483 print('probability_we_drop_a_command: ')
484 print('%s' % probability_we_drop_a_command)
486 x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
487 print('Using x=CommandSourceFromFile\n')
489 outfile = open(outfilename, 'w')
491 if not lyx_pid is None:
493 # Next command is language dependent
494 #sendKeystringRT("\Afn", lyx_pid)
496 write_commands = True
498 lineempty = re.compile(r'^\s*$')
501 #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
506 # Do not strip trailing spaces, only check for 'empty' lines
507 if lineempty.match(c):
509 outfile.writelines(c + '\n')
512 print("Ignoring comment line: " + c)
513 elif c[0:9] == 'TestBegin':
515 lyx_pid=get_proc_pid(lyx)
517 print("Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n")
518 intr_system("killall " + lyx, True)
520 intr_system("killall -KILL " + lyx, True)
522 print("Starting LyX . . .")
523 if lyx_userdir is None:
524 intr_system(lyx_exe + c[9:] + "&")
526 intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
529 old_lyx_window_name = None
530 print("Waiting for LyX to show up . . .")
532 lyx_pid=get_proc_pid(lyx)
533 if lyx_pid != old_lyx_pid:
534 print('lyx_pid=' + lyx_pid)
535 old_lyx_pid = lyx_pid
537 lyx_window_name=get_proc_win_id(lyx_pid, "")
538 if not lyx_window_name is None:
539 if old_lyx_window_name != lyx_window_name:
540 print('lyx_win=' + lyx_window_name, '\n')
541 old_lyx_window_name = lyx_window_name
547 print('Timeout: could not start ' + lyx_exe, '\n')
551 print('lyx_pid: ' + lyx_pid)
552 print('lyx_win: ' + lyx_window_name)
553 dead_expected = False
554 sendKeystringLocal("\C\[Home]", lyx_pid)
555 time.sleep(controlkey_delay)
556 elif c[0:5] == 'Sleep':
557 print("Sleeping for " + c[6:] + " seconds")
558 time.sleep(float(c[6:]))
559 elif c[0:4] == 'Exec':
564 outfile = open(outfilename + '+', 'w')
566 elif c == 'RaiseLyx':
569 elif c[0:4] == 'KK: ':
571 sendKeystringRT(c[4:], lyx_pid)
573 ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
575 print('No path /proc/xxxx/status, exiting')
577 print('No path /proc/' + lyx_pid + '/status, exiting')
579 elif c[0:4] == 'KD: ':
580 key_delay = c[4:].rstrip('\n')
581 print('Setting DELAY to ' + key_delay)
584 sendKeystringRT(ResetCommand, lyx_pid)
585 elif c[0:6] == 'Assert':
587 result = intr_system(cmd)
588 failed = failed or (result != 0)
589 print("result=" + str(result) + ", failed=" + str(failed))
590 elif c[0:15] == 'TestEndWithKill':
591 cmd = c[16:].rstrip()
592 if lyx_dead(lyx_pid):
593 print("LyX instance not found because of crash or assert !\n")
596 print(" ------------ Forcing kill of lyx instance: " + str(lyx_pid) + " ------------")
597 # This line below is there only to allow lyx to update its log-file
598 sendKeystringLocal("\[Escape]", lyx_pid)
600 while not lyx_dead(lyx_pid):
601 intr_system("kill -9 " + str(lyx_pid), True);
604 print("Executing " + cmd)
605 result = intr_system(cmd)
606 failed = failed or (result != 0)
607 print("result=" + str(result) + ", failed=" + str(failed))
609 print("failed=" + str(failed))
610 elif c[0:7] == 'TestEnd':
611 #lyx_other_window_name = None
612 if lyx_dead(lyx_pid):
613 print("LyX instance not found because of crash or assert !\n")
616 print(" ------------ Forcing quit of lyx instance: " + str(lyx_pid) + " ------------")
617 # \Ax Enter command line is sometimes blocked
618 # \[Escape] works after this
619 sendKeystringAx("\Ax\[Escape]", lyx_pid)
620 time.sleep(controlkey_delay)
621 # now we should be outside any dialog
622 # and so the function lyx-quit should work
623 sendKeystringLocal("\Cq", lyx_pid)
626 is_sleeping = wait_until_lyx_sleeping(lyx_pid)
628 print('wait_until_lyx_sleeping() indicated "sleeping"')
629 # For a short time lyx-status is 'sleeping', even if it is nearly dead.
630 # Without the wait below, the \[Tab]-char is sent to nirvana
633 # probably waiting for Save/Discard/Abort, we select 'Discard'
634 sendKeystringRT("\[Tab]\[Return]", lyx_pid)
638 while not lyx_dead(lyx_pid):
641 print("LyX still up, killing process and waiting for it to die...\n")
642 intr_system("kill -9 " + str(lyx_pid), True);
646 print("Executing " + cmd)
647 result = intr_system(cmd)
648 failed = failed or (result != 0)
649 print("result=" + str(result) + ", failed=" + str(failed))
651 print("failed=" + str(failed))
652 elif c[0:4] == 'Lang':
653 lang = c[5:].rstrip()
654 print("Setting LANG=" + lang)
655 os.environ['LANG'] = lang
656 os.environ['LC_ALL'] = lang
657 # If it doesn't exist, create a link <locale_dir>/<country-code>/LC_MESSAGES/lyx<version-suffix>.mo
658 # pointing to the corresponding .gmo file. Needed to let lyx find the right translation files.
659 # See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg165613.html
660 idx = lang.rfind(".")
666 print("Setting LANGUAGE=" + ccode)
667 os.environ['LANGUAGE'] = ccode
671 short_code = lang[0:idx]
674 lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
676 # on cmake-build there is no Makefile in this directory
677 # so PACKAGE has to be provided
678 if os.path.exists(lyx_dir + "/Makefile"):
679 print("Executing: grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'")
680 lyx_name = os.popen("grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'").read().rstrip()
682 print('Could not determine PACKAGE name needed for translations\n')
686 intr_system("mkdir -p " + locale_dir + "/" + ccode + "/LC_MESSAGES")
687 intr_system("rm -f " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
688 if PO_BUILD_DIR is None:
689 if lyx_dir[0:3] == "../":
690 rel_dir = "../../" + lyx_dir
693 intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
695 intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
697 print("Unrecognised Command '" + c + "'\n")
700 print("Test case terminated: ")