forked from GNOME/evince
-
Notifications
You must be signed in to change notification settings - Fork 0
/
behave_common_steps.py
369 lines (312 loc) · 12 KB
/
behave_common_steps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# -*- coding: UTF-8 -*-
from dogtail.utils import isA11yEnabled, enableA11y
if isA11yEnabled() is False:
enableA11y(True)
from time import time, sleep
from functools import wraps
from os import strerror, errno, system
from signal import signal, alarm, SIGALRM
from subprocess import Popen, PIPE
from behave import step,then
from gi.repository import GLib, Gio
import fcntl, os
from dogtail.rawinput import keyCombo, click, typeText, absoluteMotion, pressKey
from dogtail.tree import root, SearchError
from iniparse import ConfigParser
import traceback
from unittest import TestCase
import logging
# Create a dummy unittest class to have nice assertions
class dummy(TestCase):
def runTest(self): # pylint: disable=R0201
assert True
def wait_until(my_lambda, element, timeout=30, period=0.25):
"""
This function keeps running lambda with specified params until the result is True
or timeout is reached
Sample usages:
* wait_until(lambda x: x.name != 'Loading...', context.app)
Pause until window title is not 'Loading...'.
Return False if window title is still 'Loading...'
Throw an exception if window doesn't exist after default timeout
* wait_until(lambda element, expected: x.text == expected, element, ('Expected text'))
Wait until element text becomes the expected (passed to the lambda)
"""
exception_thrown = None
mustend = int(time()) + timeout
while int(time()) < mustend:
try:
if my_lambda(element):
return True
except Exception as e:
# If lambda has thrown the exception we'll re-raise it later
# and forget about if lambda passes
exception_thrown = e
sleep(period)
if exception_thrown:
raise exception_thrown
else:
return False
class TimeoutError(Exception):
"""
Timeout exception class for limit_execution_time_to function
"""
pass
def limit_execution_time_to(
seconds=10, error_message=strerror(errno.ETIME)):
"""
Decorator to limit function execution to specified limit
"""
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal(SIGALRM, _handle_timeout)
alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
alarm(0)
return result
return wraps(func)(wrapper)
return decorator
class App(object):
"""
This class does all basic events with the app
"""
def __init__(
self, appName, desktopFileName = None, shortcut='<Control><Q>', a11yAppName=None,
forceKill=True, parameters='', recordVideo=False):
"""
Initialize object App
appName command to run the app
shortcut default quit shortcut
a11yAppName app's a11y name is different than binary
forceKill is the app supposed to be kill before/after test?
parameters has the app any params needed to start? (only for startViaCommand)
recordVideo start gnome-shell recording while running the app
"""
self.appCommand = appName
self.shortcut = shortcut
self.forceKill = forceKill
self.parameters = parameters
self.internCommand = self.appCommand.lower()
self.a11yAppName = a11yAppName
self.recordVideo = recordVideo
self.pid = None
if desktopFileName is None:
desktopFileName = self.appCommand
self.desktopFileName = desktopFileName
# a way of overcoming overview autospawn when mouse in 1,1 from start
pressKey('Esc')
absoluteMotion(100, 100, 2)
# attempt to make a recording of the test
if self.recordVideo:
keyCombo('<Control><Alt><Shift>R')
def isRunning(self):
"""
Is the app running?
"""
if self.a11yAppName is None:
self.a11yAppName = self.internCommand
# Trap weird bus errors
for attempt in xrange(0, 30):
sleep(1)
try:
return self.a11yAppName in [x.name for x in root.applications()]
except GLib.GError:
continue
raise Exception("10 at-spi errors, seems that bus is blocked")
def getDashIconPosition(name):
"""Get a position of miniature on Overview"""
over = root.application('gnome-shell').child(name='Overview')
button = over[2].child(name=name)
(x, y) = button.position
(a, b) = button.size
return (x + a / 2, y + b / 2)
def parseDesktopFile(self):
"""
Getting all necessary data from *.dektop file of the app
"""
cmd = "rpm -qlf $(which %s)" % self.appCommand
cmd += '| grep "^/usr/share/applications/.*%s.desktop$"' % self.desktopFileName
proc = Popen(cmd, shell=True, stdout=PIPE)
# !HAVE TO check if the command and its desktop file exist
if proc.wait() != 0:
raise Exception("*.desktop file of the app not found")
output = proc.communicate()[0].rstrip()
self.desktopConfig = ConfigParser()
self.desktopConfig.read(output)
def kill(self):
"""
Kill the app via 'killall'
"""
if self.recordVideo:
keyCombo('<Control><Alt><Shift>R')
try:
self.process.kill()
except:
# Fall back to killall
Popen("killall " + self.appCommand, shell=True).wait()
def getName(self):
return self.desktopConfig.get('Desktop Entry', 'name')
def startViaCommand(self):
"""
Start the app via command
"""
if self.forceKill and self.isRunning():
self.kill()
sleep(2)
assert not self.isRunning(), "Application cannot be stopped"
self.process = Popen(self.appCommand.split() + self.parameters.split(),
stdout=PIPE, stderr=PIPE, bufsize=0)
self.pid = self.process.pid
assert self.isRunning(), "Application failed to start"
return root.application(self.a11yAppName)
def startViaMenu(self, throughCategories = False):
self.parseDesktopFile()
if self.forceKill and self.isRunning():
self.kill()
sleep(2)
assert not self.isRunning(), "Application cannot be stopped"
try:
gnomeShell = root.application('gnome-shell')
pressKey('Super_L')
sleep(6)
if throughCategories:
# menu Applications
x, y = getDashIconPosition('Show Applications')
absoluteMotion(x, y)
time.sleep(1)
click(x, y)
time.sleep(4) # time for all the oversized app icons to appear
# submenu that contains the app
submenu = gnomeShell.child(
name=self.getMenuGroups(), roleName='list item')
submenu.click()
time.sleep(4)
# the app itself
app = gnomeShell.child(
name=self.getName(), roleName='label')
app.click()
else:
typeText(self.getName())
sleep(2)
pressKey('Enter')
assert self.isRunning(), "Application failed to start"
except SearchError:
print("!!! Lookup error while passing the path")
return root.application(self.a11yAppName)
def closeViaShortcut(self):
"""
Close the app via shortcut
"""
if not self.isRunning():
raise Exception("App is not running")
keyCombo(self.shortcut)
assert not self.isRunning(), "Application cannot be stopped"
@step(u'Press "{sequence}"')
def press_button_sequence(context, sequence):
keyCombo(sequence)
sleep(0.5)
def wait_for_app_to_appear(context, app):
# Waiting for a window to appear
for attempt in xrange(0, 10):
try:
context.app.instance = root.application(app.lower())
context.app.instance.child(roleName='frame')
break
except (GLib.GError, SearchError):
sleep(1)
continue
context.execute_steps("Then %s should start" % app)
@step(u'Start {app} via {type:w}')
def start_app_via_command(context, app, type):
for attempt in xrange(0, 10):
try:
if type == 'command':
context.app.startViaCommand()
if type == 'menu':
context.app.startViaMenu()
break
except GLib.GError:
sleep(1)
if attempt == 6:
# Killall the app processes if app didn't show up after 5 seconds
os.system("pkill -f %s 2&> /dev/null" % app.lower())
os.system("python cleanup.py")
context.execute_steps("* Start %s via command" % app)
continue
@step(u'Close app via gnome panel')
def close_app_via_gnome_panel(context):
context.app.closeViaGnomePanel()
@step(u'Click "Quit" in GApplication menu')
def close_app_via_shortcut(context) :
context.app.closeViaShortcut
@step(u'Make sure that {app} is running')
def ensure_app_running(context, app):
start_app_via_command(context, app, 'command')
wait_for_app_to_appear(context, app)
logging.debug("app = %s", root.application(app.lower()))
@then(u'{app} should start')
def test_app_started(context, app):
# Dogtail seems to cache applications list
# So we should wait for exception here
try:
root.application(app.lower()).child(roleName='frame')
except SearchError:
raise RuntimeError("App '%s' is not running" % app)
@then(u"{app} shouldn't be running anymore")
def then_app_is_dead(context, app):
try:
root.application(app.lower()).child(roleName='frame')
raise RuntimeError("App '%s' is running" % app)
except SearchError:
pass
def cleanup():
# Remove cached data and settings
folders = ['~/.local/share/evolution', '~/.cache/evolution', '~/.config/evolution']
for folder in folders:
system("rm -rf %s > /dev/null" % folder)
# Clean up goa data
system("rm -rf ~/.config/goa-1.0/accounts.conf")
system("killall goa-daemon 2&> /dev/null")
# Reset GSettings
schemas = [x for x in Gio.Settings.list_schemas() if 'evolution' in x.lower()]
for schema in schemas:
system("gsettings reset-recursively %s" % schema)
# Skip warning dialog
system("gsettings set org.gnome.evolution.shell skip-warning-dialog true")
# Show switcher buttons as icons (to minimize tree scrolling)
system("gsettings set org.gnome.evolution.shell buttons-style icons")
# Skip default mailer handler dialog
system("gsettings set org.gnome.evolution.mail prompt-check-if-default-mailer false")
def check_for_errors(context):
"""Check that no error is displayed on Evolution UI"""
# Don't try to check for errors on dead app
if not context.app or context.app.dead:
return
alerts = context.app.findChildren(lambda x: x.roleName == 'alert')
if not alerts:
# alerts can also return None
return
alerts = filter(lambda x: x.showing, alerts)
if len(alerts) > 0:
labels = alerts[0].findChildren(lambda x: x.roleName == 'label')
messages = [x.name for x in labels]
if alerts[0].name != 'Error' and alerts[0].showing:
# Erase the configuration and start all over again
system("evolution --force-shutdown &> /dev/null")
# Remove previous data
folders = ['~/.local/share/evolution', '~/.cache/evolution', '~/.config/evolution']
for folder in folders:
system("rm -rf %s > /dev/null" % folder)
raise RuntimeError("Error occurred: %s" % messages)
def non_block_read(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.read()
except:
return ""