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
16 #from subprocess import call
19 print 'Beginning keytest.py'
21 FNULL = open('/dev/null', 'w')
42 for k in range(97, 123):
45 for k in range(97, 123):
46 keycode[:0] = ["\A" + chr(k)]
48 for k in range(97, 123):
49 keycode[:0] = ["\A" + chr(k)]
51 for k in range(97, 123):
52 keycode[:0] = ["\C" + chr(k)]
54 self.keycode = keycode
59 self.count = self.count + 1
60 if self.count % 200 == 0:
62 elif self.count > self.count_max:
67 keystr = keystr + self.keycode[random.randint(1,
68 len(self.keycode)) - 1]
69 return 'KK: ' + keystr
72 class CommandSourceFromFile(CommandSource):
74 def __init__(self, filename, p):
76 self.infile = open(filename, 'r')
77 self.lines = self.infile.readlines()
81 print p, self.p, 'self.p'
86 # Now we start randomly dropping lines, which we hope are redundant
87 # p is the probability that any given line will be removed
90 if random.uniform(0, 1) < 0.5:
91 print 'randomdrop_independant\n'
92 self.randomdrop_independant()
94 print 'randomdrop_slice\n'
95 self.randomdrop_slice()
96 if screenshot_out is None:
100 self.max_count = max(len(self.lines) + 20, count_atleast)
101 if len(self.lines) < 1:
102 self.lines = linesbak
104 def randomdrop_independant(self):
107 # The next couple of lines are to ensure that at least one line is dropped
109 drop = random.randint(0, len(self.lines) - 1)
111 #p = p - 1 / len(self.lines)
112 origlines = self.lines
115 if random.uniform(0, 1) < self.p:
116 print 'Randomly dropping line ' + l + '\n'
123 def randomdrop_slice(self):
125 if random.uniform(0, 1) < 0.4:
126 lines.append(lines[0])
128 num_lines = len(lines)
129 max_drop = max(5, num_lines / 5)
130 num_drop = random.randint(1, 5)
131 drop_mid = random.randint(0, num_lines)
132 drop_start = max(drop_mid - num_drop / 2, 0)
133 drop_end = min(drop_start + num_drop, num_lines)
134 print drop_start, drop_mid, drop_end
136 del lines[drop_start:drop_end]
140 def getCommand(self):
141 if self.count >= self.max_count:
143 if self.i >= len(self.lines):
144 self.loops = self.loops + 1
145 if self.loops >= int(max_loops):
149 line = self.lines[self.i].rstrip('\n')
150 self.count = self.count + 1
157 fname = '/proc/' + lyx_pid + '/status'
158 return os.path.exists(fname)
161 fname = '/proc/' + lyx_pid + '/status'
163 lines = f.readlines()
164 sleeping = lines[1].find('(sleeping)') > 0
166 # print 'LYX_STATE', lines[1] , 'SLEEPING=', sleeping
171 # Interruptible os.system()
172 def intr_system(cmd, ignore_err = False):
173 print "Executing " + cmd + "\n"
175 if os.WIFSIGNALED(ret):
176 raise KeyboardInterrupt
177 if ret != 0 and not ignore_err:
178 raise BaseException("command failed.")
182 def sendKeystring(keystr, LYX_PID):
184 # print "sending keystring "+keystr+"\n"
186 if not re.match(".*\w.*", keystr):
187 print 'print .' + keystr + '.\n'
189 before_secs = time.time()
190 while lyx_exists() and not lyx_sleeping():
193 if time.time() - before_secs > 180:
194 print 'Killing due to freeze (KILL_FREEZE)'
196 # Do profiling, but sysprof has no command line interface?
197 # intr_system("killall -KILL lyx")
200 if not screenshot_out is None:
201 while lyx_exists() and not lyx_sleeping():
204 print 'Making Screenshot: ' + screenshot_out + ' OF ' + infilename
206 intr_system('import -window root '+screenshot_out+str(x.count)+".png")
209 actual_delay = key_delay
210 if actual_delay == '':
211 actual_delay = def_delay
213 subprocess.call([xvkbd_exe, "-xsendevent", "-window", lyx_window_name,
214 "-delay", actual_delay, "-text", keystr], stdout = FNULL, stderr = FNULL)
216 subprocess.call([xvkbd_exe, "-no_root", "-wait_idle", lyx_pid,
217 "-xsendevent", "-window", lyx_window_name,
218 "-delay", actual_delay, "-text", keystr], stdout = FNULL, stderr = FNULL)
220 def system_retry(num_retry, cmd):
222 rtn = intr_system(cmd)
223 while ( ( i < num_retry ) and ( rtn != 0) ):
225 rtn = intr_system(cmd)
228 print "Command Failed: "+cmd
233 #intr_system("echo x-session-manager PID: $X_PID.")
234 #intr_system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
235 ####intr_system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
236 #intr_system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
237 system_retry(30, "wmctrl -i -a '"+lyx_window_name+"'")
240 lyx_pid = os.environ.get('LYX_PID')
241 print 'lyx_pid: ' + str(lyx_pid) + '\n'
242 infilename = os.environ.get('KEYTEST_INFILE')
243 outfilename = os.environ.get('KEYTEST_OUTFILE')
244 max_drop = os.environ.get('MAX_DROP')
245 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
246 screenshot_out = os.environ.get('SCREENSHOT_OUT')
247 lyx_userdir = os.environ.get('LYX_USERDIR')
249 max_loops = os.environ.get('MAX_LOOPS')
250 if max_loops is None:
253 PACKAGE = os.environ.get('PACKAGE')
254 if not PACKAGE is None:
255 print "PACKAGE = " + PACKAGE + "\n"
257 PO_BUILD_DIR = os.environ.get('PO_BUILD_DIR')
258 if not PO_BUILD_DIR is None:
259 print "PO_BUILD_DIR = " + PO_BUILD_DIR + "\n"
261 lyx = os.environ.get('LYX')
265 lyx_exe = os.environ.get('LYX_EXE')
269 xvkbd_exe = os.environ.get('XVKBD_EXE')
270 if xvkbd_exe is None:
273 xvkbd_hacked = os.environ.get('XVKBD_HACKED') != None
275 locale_dir = os.environ.get('LOCALE_DIR')
276 if locale_dir is None:
279 def_delay = os.environ.get('XVKBD_DELAY')
280 if def_delay is None:
283 file_new_command = os.environ.get('FILE_NEW_COMMAND')
284 if file_new_command is None:
285 file_new_command = "\Afn"
287 ResetCommand = os.environ.get('RESET_COMMAND')
288 if ResetCommand is None:
289 ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
290 #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
292 if lyx_window_name is None:
293 lyx_window_name = 'LyX'
295 print 'outfilename: ' + outfilename + '\n'
296 print 'max_drop: ' + max_drop + '\n'
298 if infilename is None:
299 print 'infilename is None\n'
301 print 'Using x=CommandSource\n'
303 print 'infilename: ' + infilename + '\n'
304 probability_we_drop_a_command = random.uniform(0, float(max_drop))
305 print 'probability_we_drop_a_command: '
306 print '%s' % probability_we_drop_a_command
308 x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
309 print 'Using x=CommandSourceFromFile\n'
311 outfile = open(outfilename, 'w')
313 if not lyx_pid is None:
315 sendKeystring("\Afn", lyx_pid)
317 write_commands = True
321 #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
327 outfile.writelines(c + '\n')
330 print "Ignoring comment line: " + c
331 elif c[0:9] == 'TestBegin':
333 lyx_pid=os.popen("pidof " + lyx).read()
335 print "Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n"
336 intr_system("killall " + lyx, True)
338 intr_system("killall -KILL " + lyx, True)
340 print "Starting LyX . . ."
341 if lyx_userdir is None:
342 intr_system(lyx_exe + c[9:] + "&")
344 intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
347 lyx_pid=os.popen("pidof " + lyx).read().rstrip()
349 lyx_window_name=os.popen("wmctrl -l -p | grep ' " + str(lyx_pid) + " ' | cut -d ' ' -f 1").read().rstrip()
350 if lyx_window_name != "":
354 print 'lyx_win: ' + lyx_window_name + '\n'
355 print "Waiting for LyX to show up . . ."
358 print 'Timeout: could not start ' + lyx_exe, '\n'
361 print 'lyx_pid: ' + lyx_pid + '\n'
362 print 'lyx_win: ' + lyx_window_name + '\n'
363 elif c[0:5] == 'Sleep':
364 print "Sleeping for " + c[6:] + " seconds\n"
365 time.sleep(float(c[6:]))
366 elif c[0:4] == 'Exec':
371 outfile = open(outfilename + '+', 'w')
373 elif c == 'RaiseLyx':
376 elif c[0:4] == 'KK: ':
378 sendKeystring(c[4:], lyx_pid)
380 ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
382 print 'No path /proc/xxxx/status, exiting'
384 print 'No path /proc/' + lyx_pid + '/status, exiting'
386 elif c[0:4] == 'KD: ':
387 key_delay = c[4:].rstrip('\n')
388 print 'Setting DELAY to ' + key_delay + '.\n'
391 sendKeystring(ResetCommand, lyx_pid)
392 elif c[0:6] == 'Assert':
394 result = intr_system(cmd)
395 failed = failed or (result != 0)
396 print "result=" + str(result) + ", failed=" + str(failed)
397 elif c[0:7] == 'TestEnd':
400 print "LyX instance not found because of crash or assert !\n"
403 print "Terminating lyx instance: " + str(lyx_pid) + "\n"
404 intr_system("kill -9 " + str(lyx_pid), True);
406 print "Waiting for lyx to die...\n"
409 print "Executing " + cmd
410 result = intr_system(cmd)
411 failed = failed or (result != 0)
412 print "result=" + str(result) + ", failed=" + str(failed)
413 elif c[0:4] == 'Lang':
414 lang = c[5:].rstrip()
415 print "Setting LANG=" + lang + "\n"
416 os.environ['LANG'] = lang
417 os.environ['LC_ALL'] = lang
418 # If it doesn't exist, create a link <locale_dir>/<country-code>/LC_MESSAGES/lyx<version-suffix>.mo
419 # pointing to the corresponding .gmo file. Needed to let lyx find the right translation files.
420 # See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg165613.html
421 idx = lang.rfind(".")
427 print "Setting LANGUAGE=" + ccode + "\n"
428 os.environ['LANGUAGE'] = ccode
432 short_code = lang[0:idx]
435 lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
437 # on cmake-build there is no Makefile in this directory
438 # so PACKAGE has to be provided
439 if os.path.exists(lyx_dir + "/Makefile"):
440 print "Executing: grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'"
441 lyx_name = os.popen("grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'").read().rstrip()
443 print 'Could not determine PACKAGE name needed for translations\n'
447 intr_system("mkdir -p " + locale_dir + "/" + ccode + "/LC_MESSAGES")
448 intr_system("rm -f " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
449 if PO_BUILD_DIR is None:
450 if lyx_dir[0:3] == "../":
451 rel_dir = "../../" + lyx_dir
454 intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
456 intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
458 print "Unrecognised Command '" + c + "'\n"
461 print "Test case terminated: "