]> git.lyx.org Git - lyx.git/blob - development/autotests/keytest.py
Customization: correct some color names.
[lyx.git] / development / autotests / keytest.py
1 #!/usr/bin/python
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
7 #
8 # Adapted by Tommaso Cucinotta from the original MonKey Test by
9 # John McCabe-Dansted.
10
11 import random
12 import os
13 import re
14 import sys
15 import time
16 #from subprocess import call
17 import subprocess
18
19 print 'Beginning keytest.py'
20
21 FNULL = open('/dev/null', 'w')
22
23 key_delay = ''
24
25 class CommandSource:
26
27     def __init__(self):
28         keycode = [
29             "\[Left]",
30             '\[Right]',
31             '\[Down]',
32             '\[Up]',
33             '\[BackSpace]',
34             '\[Delete]',
35             '\[Escape]',
36             ]
37         keycode[:0] = keycode
38         keycode[:0] = keycode
39
40         keycode[:0] = ['\\']
41
42         for k in range(97, 123):
43             keycode[:0] = chr(k)
44
45         for k in range(97, 123):
46             keycode[:0] = ["\A" + chr(k)]
47
48         for k in range(97, 123):
49             keycode[:0] = ["\A" + chr(k)]
50
51         for k in range(97, 123):
52             keycode[:0] = ["\C" + chr(k)]
53
54         self.keycode = keycode
55         self.count = 0
56         self.count_max = 1999
57
58     def getCommand(self):
59         self.count = self.count + 1
60         if self.count % 200 == 0:
61             return 'RaiseLyx'
62         elif self.count > self.count_max:
63             os._exit(0)
64         else:
65             keystr = ''
66             for k in range(1, 2):
67                 keystr = keystr + self.keycode[random.randint(1,
68                         len(self.keycode)) - 1]
69             return 'KK: ' + keystr
70
71
72 class CommandSourceFromFile(CommandSource):
73
74     def __init__(self, filename, p):
75
76         self.infile = open(filename, 'r')
77         self.lines = self.infile.readlines()
78         self.infile.close()
79         linesbak = self.lines
80         self.p = p
81         print p, self.p, 'self.p'
82         self.i = 0
83         self.count = 0
84         self.loops = 0
85
86         # Now we start randomly dropping lines, which we hope are redundant
87         # p is the probability that any given line will be removed
88
89         if p > 0.001:
90             if random.uniform(0, 1) < 0.5:
91                 print 'randomdrop_independant\n'
92                 self.randomdrop_independant()
93             else:
94                 print 'randomdrop_slice\n'
95                 self.randomdrop_slice()
96         if screenshot_out is None:
97             count_atleast = 100
98         else:
99             count_atleast = 1
100         self.max_count = max(len(self.lines) + 20, count_atleast)
101         if len(self.lines) < 1:
102             self.lines = linesbak
103
104     def randomdrop_independant(self):
105         p = self.p
106
107         # The next couple of lines are to ensure that at least one line is dropped
108
109         drop = random.randint(0, len(self.lines) - 1)
110         del self.lines[drop]
111         #p = p - 1 / len(self.lines)
112         origlines = self.lines
113         self.lines = []
114         for l in origlines:
115             if random.uniform(0, 1) < self.p:
116                 print 'Randomly dropping line ' + l + '\n'
117             else:
118                 self.lines.append(l)
119         print 'LINES\n'
120         print self.lines
121         sys.stdout.flush()
122
123     def randomdrop_slice(self):
124         lines = self.lines
125         if random.uniform(0, 1) < 0.4:
126             lines.append(lines[0])
127             del 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
135         print lines
136         del lines[drop_start:drop_end]
137         print lines
138         self.lines = lines
139
140     def getCommand(self):
141         if self.count >= self.max_count:
142             os._exit(0)
143         if self.i >= len(self.lines):
144             self.loops = self.loops + 1
145             if self.loops >= int(max_loops):
146                 return None
147             self.i = 0
148             return 'Loop'
149         line = self.lines[self.i].rstrip('\n')
150         self.count = self.count + 1
151         self.i = self.i + 1
152         return line
153
154 def lyx_exists():
155     if lyx_pid is None:
156         return False
157     fname = '/proc/' + lyx_pid + '/status'
158     return os.path.exists(fname)
159
160 def lyx_sleeping():
161     fname = '/proc/' + lyx_pid + '/status'
162     f = open(fname, 'r')
163     lines = f.readlines()
164     sleeping = lines[1].find('(sleeping)') > 0
165
166     # print 'LYX_STATE', lines[1] , 'SLEEPING=', sleeping
167
168     return sleeping
169
170
171 # Interruptible os.system()
172 def intr_system(cmd, ignore_err = False):
173     print "Executing " + cmd + "\n"
174     ret = os.system(cmd)
175     if os.WIFSIGNALED(ret):
176         raise KeyboardInterrupt
177     if ret != 0 and not ignore_err:
178         raise BaseException("command failed.")
179     return ret
180
181
182 def sendKeystring(keystr, LYX_PID):
183
184     # print "sending keystring "+keystr+"\n"
185
186     if not re.match(".*\w.*", keystr):
187         print 'print .' + keystr + '.\n'
188         keystr = 'a'
189     before_secs = time.time()
190     while lyx_exists() and not lyx_sleeping():
191         time.sleep(0.02)
192         sys.stdout.flush()
193         if time.time() - before_secs > 180:
194             print 'Killing due to freeze (KILL_FREEZE)'
195
196             # Do profiling, but sysprof has no command line interface?
197             # intr_system("killall -KILL lyx")
198
199             os._exit(1)
200     if not screenshot_out is None:
201         while lyx_exists() and not lyx_sleeping():
202             time.sleep(0.02)
203             sys.stdout.flush()
204         print 'Making Screenshot: ' + screenshot_out + ' OF ' + infilename
205         time.sleep(0.2)
206         intr_system('import -window root '+screenshot_out+str(x.count)+".png")
207         time.sleep(0.1)
208     sys.stdout.flush()
209     actual_delay = key_delay
210     if actual_delay == '':
211         actual_delay = def_delay
212     xvpar = [xvkbd_exe]
213     if qt_frontend == 'QT5':
214         xvpar.extend(["-no-jump-pointer"])
215     else:
216         xvpar.extend(["-xsendevent"])
217     if xvkbd_hacked:
218         xvpar.extend(["-wait_idle", lyx_pid])
219     xvpar.extend(["-window", lyx_window_name, "-delay", actual_delay, "-text", keystr])
220     
221     subprocess.call(xvpar, stdout = FNULL, stderr = FNULL)
222
223 def system_retry(num_retry, cmd):
224     i = 0
225     rtn = intr_system(cmd)
226     while ( ( i < num_retry ) and ( rtn != 0) ):
227         i = i + 1
228         rtn = intr_system(cmd)
229         time.sleep(1)
230     if ( rtn != 0 ):
231         print "Command Failed: "+cmd
232         print " EXITING!\n"
233         os._exit(1)
234
235 def RaiseWindow():
236     #intr_system("echo x-session-manager PID: $X_PID.")
237     #intr_system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
238     ####intr_system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
239     #intr_system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
240     system_retry(30, "wmctrl -i -a '"+lyx_window_name+"'")
241
242
243 lyx_pid = os.environ.get('LYX_PID')
244 print 'lyx_pid: ' + str(lyx_pid) + '\n'
245 infilename = os.environ.get('KEYTEST_INFILE')
246 outfilename = os.environ.get('KEYTEST_OUTFILE')
247 max_drop = os.environ.get('MAX_DROP')
248 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
249 screenshot_out = os.environ.get('SCREENSHOT_OUT')
250 lyx_userdir = os.environ.get('LYX_USERDIR')
251
252 max_loops = os.environ.get('MAX_LOOPS')
253 if max_loops is None:
254     max_loops = 3
255
256 PACKAGE = os.environ.get('PACKAGE')
257 if not PACKAGE is None:
258   print "PACKAGE = " + PACKAGE + "\n"
259
260 PO_BUILD_DIR = os.environ.get('PO_BUILD_DIR')
261 if not PO_BUILD_DIR is None:
262   print "PO_BUILD_DIR = " + PO_BUILD_DIR + "\n"
263
264 lyx = os.environ.get('LYX')
265 if lyx is None:
266     lyx = "lyx"
267
268 lyx_exe = os.environ.get('LYX_EXE')
269 if lyx_exe is None:
270     lyx_exe = lyx
271
272 xvkbd_exe = os.environ.get('XVKBD_EXE')
273 if xvkbd_exe is None:
274     xvkbd_exe = "xvkbd"
275
276 xvkbd_hacked = os.environ.get('XVKBD_HACKED') != None
277 qt_frontend = os.environ.get('QT_FRONTEND')
278 if qt_frontend is None:
279     qt_frontend = 'QT4'
280
281 locale_dir = os.environ.get('LOCALE_DIR')
282 if locale_dir is None:
283     locale_dir = '.'
284
285 def_delay = os.environ.get('XVKBD_DELAY')
286 if def_delay is None:
287     def_delay = '100'
288
289 file_new_command = os.environ.get('FILE_NEW_COMMAND')
290 if file_new_command is None:
291     file_new_command = "\Afn"
292
293 ResetCommand = os.environ.get('RESET_COMMAND')
294 if ResetCommand is None:
295     ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
296     #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
297
298 if lyx_window_name is None:
299     lyx_window_name = 'LyX'
300
301 print 'outfilename: ' + outfilename + '\n'
302 print 'max_drop: ' + max_drop + '\n'
303
304 if infilename is None:
305     print 'infilename is None\n'
306     x = CommandSource()
307     print 'Using x=CommandSource\n'
308 else:
309     print 'infilename: ' + infilename + '\n'
310     probability_we_drop_a_command = random.uniform(0, float(max_drop))
311     print 'probability_we_drop_a_command: '
312     print '%s' % probability_we_drop_a_command
313     print '\n'
314     x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
315     print 'Using x=CommandSourceFromFile\n'
316
317 outfile = open(outfilename, 'w')
318
319 if not lyx_pid is None:
320     RaiseWindow()
321     sendKeystring("\Afn", lyx_pid)
322
323 write_commands = True
324 failed = False
325
326 while not failed:
327     #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
328     c = x.getCommand()
329     if c is None:
330         break
331     if c.strip() == "":
332         continue
333     outfile.writelines(c + '\n')
334     outfile.flush()
335     if c[0] == '#':
336         print "Ignoring comment line: " + c
337     elif c[0:9] == 'TestBegin':
338         print "\n"
339         lyx_pid=os.popen("pidof " + lyx).read()
340         if lyx_pid != "":
341             print "Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n"
342             intr_system("killall " + lyx, True)
343             time.sleep(0.5)
344             intr_system("killall -KILL " + lyx, True)
345         time.sleep(0.2)
346         print "Starting LyX . . ."
347         if lyx_userdir is None:
348             intr_system(lyx_exe + c[9:] + "&")
349         else:
350             intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
351         count = 5
352         while count > 0:
353             lyx_pid=os.popen("pidof " + lyx).read().rstrip()
354             if lyx_pid != "":
355                 lyx_window_name=os.popen("wmctrl -l -p | grep ' " + str(lyx_pid) +  " ' | cut -d ' ' -f 1").read().rstrip()
356                 if lyx_window_name != "":
357                     break
358             else:
359                 count = count - 1
360             print 'lyx_win: ' + lyx_window_name + '\n'
361             print "Waiting for LyX to show up . . ."
362             time.sleep(1)
363         if count <= 0:
364             print 'Timeout: could not start ' + lyx_exe, '\n'
365             sys.stdout.flush()
366             failed = True
367         print 'lyx_pid: ' + lyx_pid + '\n'
368         print 'lyx_win: ' + lyx_window_name + '\n'
369     elif c[0:5] == 'Sleep':
370         print "Sleeping for " + c[6:] + " seconds\n"
371         time.sleep(float(c[6:]))
372     elif c[0:4] == 'Exec':
373         cmd = c[5:].rstrip()
374         intr_system(cmd)
375     elif c == 'Loop':
376         outfile.close()
377         outfile = open(outfilename + '+', 'w')
378         print 'Now Looping'
379     elif c == 'RaiseLyx':
380         print 'Raising Lyx'
381         RaiseWindow()
382     elif c[0:4] == 'KK: ':
383         if lyx_exists():
384             sendKeystring(c[4:], lyx_pid)
385         else:
386             ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
387             if lyx_pid is None:
388               print 'No path /proc/xxxx/status, exiting'
389             else:
390               print 'No path /proc/' + lyx_pid + '/status, exiting'
391             os._exit(1)
392     elif c[0:4] == 'KD: ':
393         key_delay = c[4:].rstrip('\n')
394         print 'Setting DELAY to ' + key_delay + '.\n'
395     elif c == 'Loop':
396         RaiseWindow()
397         sendKeystring(ResetCommand, lyx_pid)
398     elif c[0:6] == 'Assert':
399         cmd = c[7:].rstrip()
400         result = intr_system(cmd)
401         failed = failed or (result != 0)
402         print "result=" + str(result) + ", failed=" + str(failed)
403     elif c[0:7] == 'TestEnd':
404         time.sleep(0.5)
405         if not lyx_exists():
406             print "LyX instance not found because of crash or assert !\n"
407             failed = True
408         else:
409             print "Terminating lyx instance: " + str(lyx_pid) + "\n"
410             intr_system("kill -9 " + str(lyx_pid), True);
411             while lyx_exists():
412                 print "Waiting for lyx to die...\n"
413                 time.sleep(0.5)
414         cmd = c[8:].rstrip()
415         print "Executing " + cmd
416         result = intr_system(cmd)
417         failed = failed or (result != 0)
418         print "result=" + str(result) + ", failed=" + str(failed)
419     elif c[0:4] == 'Lang':
420         lang = c[5:].rstrip()
421         print "Setting LANG=" + lang + "\n"
422         os.environ['LANG'] = lang
423         os.environ['LC_ALL'] = lang
424 # If it doesn't exist, create a link <locale_dir>/<country-code>/LC_MESSAGES/lyx<version-suffix>.mo
425 # pointing to the corresponding .gmo file. Needed to let lyx find the right translation files.
426 # See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg165613.html
427         idx = lang.rfind(".")
428         if idx != -1:
429             ccode = lang[0:idx]
430         else:
431             ccode = lang
432
433         print "Setting LANGUAGE=" + ccode + "\n"
434         os.environ['LANGUAGE'] = ccode
435
436         idx = lang.find("_")
437         if idx != -1:
438             short_code = lang[0:idx]
439         else:
440             short_code = ccode
441         lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
442         if PACKAGE is None:
443           # on cmake-build there is no Makefile in this directory
444           # so PACKAGE has to be provided
445           if os.path.exists(lyx_dir + "/Makefile"):
446             print "Executing: grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'"
447             lyx_name = os.popen("grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'").read().rstrip()
448           else:
449             print 'Could not determine PACKAGE name needed for translations\n'
450             failed = True
451         else:
452           lyx_name = PACKAGE
453         intr_system("mkdir -p " + locale_dir + "/" + ccode + "/LC_MESSAGES")
454         intr_system("rm -f " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
455         if PO_BUILD_DIR is None:
456             if lyx_dir[0:3] == "../":
457                 rel_dir = "../../" + lyx_dir
458             else:
459                 rel_dir = lyx_dir
460             intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
461         else:
462             intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
463     else:
464         print "Unrecognised Command '" + c + "'\n"
465         failed = True
466
467 print "Test case terminated: "
468 if failed:
469     print "FAIL\n"
470     os._exit(1)
471 else:
472     print "Ok\n"
473     os._exit(0)