-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy path_applicationmanagement.py
More file actions
492 lines (382 loc) · 18.5 KB
/
Copy path_applicationmanagement.py
File metadata and controls
492 lines (382 loc) · 18.5 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# -*- coding: utf-8 -*-
import os
import robot
import inspect
from appium import webdriver
from appium.options.common import AppiumOptions
from AppiumLibrary.utils import ApplicationCache
from .keywordgroup import KeywordGroup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
class _ApplicationManagementKeywords(KeywordGroup):
def __init__(self):
self._cache = ApplicationCache()
self._timeout_in_secs = float(5)
# Public, open and close
def close_application(self):
"""Closes the current application and also close webdriver session."""
self._debug('Closing application with session id %s' % self._current_application().session_id)
self._cache.close()
def close_all_applications(self):
"""Closes all open applications.
This keyword is meant to be used in test or suite teardown to
make sure all the applications are closed before the test execution
finishes.
After this keyword, the application indices returned by `Open Application`
are reset and start from `1`.
"""
self._debug('Closing all applications')
self._cache.close_all()
def open_application(self, remote_url, alias=None, **kwargs):
"""Opens a new application to given Appium server.
Capabilities of appium server, Android and iOS,
Please check https://appium.io/docs/en/2.1/cli/args/
| *Option* | *Man.* | *Description* |
| remote_url | Yes | Appium server url |
| alias | no | alias |
| strict_ssl | No | allows you to send commands to an invalid certificate host like a self-signed one. |
Examples:
| Open Application | http://localhost:4723/wd/hub | alias=Myapp1 | platformName=iOS | platformVersion=7.0 | deviceName='iPhone Simulator' | app=your.app |
| Open Application | http://localhost:4723/wd/hub | alias=Myapp1 | platformName=iOS | platformVersion=7.0 | deviceName='iPhone Simulator' | app=your.app | strict_ssl=False |
| Open Application | http://localhost:4723/wd/hub | platformName=Android | platformVersion=4.2.2 | deviceName=192.168.56.101:5555 | app=${CURDIR}/demoapp/OrangeDemoApp.apk | appPackage=com.netease.qa.orangedemo | appActivity=MainActivity |
"""
strict_ssl = False
if "strict_ssl" in kwargs.keys():
strict_ssl = kwargs.pop("strict_ssl")
self._debug(f"strict_ssl found as {strict_ssl}")
desired_caps = AppiumOptions().load_capabilities(caps=kwargs)
application = webdriver.Remote(str(remote_url), options=desired_caps, strict_ssl=strict_ssl)
self._debug('Opened application with session id %s' % application.session_id)
return self._cache.register(application, alias)
def switch_application(self, index_or_alias):
"""Switches the active application by index or alias.
`index_or_alias` is either application index (an integer) or alias
(a string). Index is got as the return value of `Open Application`.
This keyword returns the index of the previous active application,
which can be used to switch back to that application later.
Example:
| ${appium1}= | Open Application | http://localhost:4723/wd/hub | alias=MyApp1 | platformName=iOS | platformVersion=7.0 | deviceName='iPhone Simulator' | app=your.app |
| ${appium2}= | Open Application | http://localhost:4755/wd/hub | alias=MyApp2 | platformName=iOS | platformVersion=7.0 | deviceName='iPhone Simulator' | app=your.app |
| Click Element | sendHello | # Executed on appium running at localhost:4755 |
| Switch Application | ${appium1} | # Switch using index |
| Click Element | ackHello | # Executed on appium running at localhost:4723 |
| Switch Application | MyApp2 | # Switch using alias |
| Page Should Contain Text | ackHello Received | # Executed on appium running at localhost:4755 |
"""
old_index = self._cache.current_index
if index_or_alias is None:
self._cache.close()
else:
self._cache.switch(index_or_alias)
return old_index
def launch_application(self):
"""*DEPRECATED!!* in selenium v4, use `Activate Application` keyword.
Launch application. Application can be launched while Appium session running.
This keyword can be used to launch application during test case or between test cases.
This keyword works while `Open Application` has a test running. This is good practice to `Launch Application`
and `Quit Application` between test cases. As Suite Setup is `Open Application`, `Test Setup` can be used to `Launch Application`
Example (syntax is just a representation, refer to RF Guide for usage of Setup/Teardown):
| [Setup Suite] |
| | Open Application | http://localhost:4723/wd/hub | platformName=Android | deviceName=192.168.56.101:5555 | app=${CURDIR}/demoapp/OrangeDemoApp.apk |
| [Test Setup] |
| | Launch Application |
| | | <<<test execution>>> |
| | | <<<test execution>>> |
| [Test Teardown] |
| | Quit Application |
| [Suite Teardown] |
| | Close Application |
See `Quit Application` for quiting application but keeping Appium sesion running.
"""
driver = self._current_application()
driver.launch_app()
def quit_application(self):
"""*DEPRECATED!!* in selenium v4, check `Close Application` keyword.
Close application. Application can be quit while Appium session is kept alive.
This keyword can be used to close application during test case or between test cases.
See `Launch Application` for an explanation.
"""
driver = self._current_application()
driver.close_app()
def reset_application(self):
"""*DEPRECATED!!* in selenium v4, check `Terminate Application` keyword.
Reset application. Open Application can be reset while Appium session is kept alive.
"""
driver = self._current_application()
driver.reset()
def remove_application(self, application_id):
""" Removes the application that is identified with an application id
Example:
| Remove Application | com.netease.qa.orangedemo |
"""
driver = self._current_application()
driver.remove_app(application_id)
def get_appium_timeout(self):
"""Gets the timeout in seconds that is used by various keywords.
See `Set Appium Timeout` for an explanation."""
return robot.utils.secs_to_timestr(self._timeout_in_secs)
def set_appium_timeout(self, seconds):
"""Sets the timeout in seconds used by various keywords.
There are several `Wait ...` keywords that take timeout as an
argument. All of these timeout arguments are optional. The timeout
used by all of them can be set globally using this keyword.
The previous timeout value is returned by this keyword and can
be used to set the old value back later. The default timeout
is 5 seconds, but it can be altered in `importing`.
Example:
| ${orig timeout} = | Set Appium Timeout | 15 seconds |
| Open page that loads slowly |
| Set Appium Timeout | ${orig timeout} |
"""
old_timeout = self.get_appium_timeout()
self._timeout_in_secs = robot.utils.timestr_to_secs(seconds)
return old_timeout
def get_appium_sessionId(self):
"""Returns the current session ID as a reference"""
self._info("Appium Session ID: " + self._current_application().session_id)
return self._current_application().session_id
def get_source(self):
"""Returns the entire source of the current page."""
return self._current_application().page_source
def log_source(self, loglevel='INFO'):
"""Logs and returns the entire html source of the current page or frame.
The `loglevel` argument defines the used log level. Valid log levels are
`WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging).
"""
ll = loglevel.upper()
if ll == 'NONE':
return ''
else:
if "run_keyword_and_ignore_error" not in [check_error_ignored[3] for check_error_ignored in inspect.stack()]:
source = self._current_application().page_source
self._log(source, ll)
return source
else:
return ''
def execute_script(self, script, **kwargs):
"""
Execute a variety of native, mobile commands that aren't associated
with a specific endpoint. See [https://appium.io/docs/en/commands/mobile-command/|Appium Mobile Command]
for more details.
Example:
| &{scrollGesture} | create dictionary | left=${50} | top=${150} | width=${50} | height=${200} | direction=down | percent=${100} |
| Sleep | 1 |
| Execute Script | mobile: scrollGesture | &{scrollGesture} |
Updated in AppiumLibrary 2
"""
if kwargs:
self._info(f"Provided dictionary: {kwargs}")
return self._current_application().execute_script(script, kwargs)
def execute_async_script(self, script, **kwargs):
"""
Inject a snippet of Async-JavaScript into the page for execution in the
context of the currently selected frame (Web context only).
The executed script is assumed to be asynchronous and must signal that is done by
invoking the provided callback, which is always provided as the final argument to the
function.
The value to this callback will be returned to the client.
Check `Execute Script` for example kwargs usage
Updated in AppiumLibrary 2
"""
if kwargs:
self._info(f"Provided dictionary: {kwargs}")
return self._current_application().execute_async_script(script, kwargs)
def execute_adb_shell(self, command, *args):
"""
Execute ADB shell commands
Android only.
- _command_ - The ABD shell command
- _args_ - Arguments to send to command
Returns the exit code of ADB shell.
Requires server flag --relaxed-security to be set on Appium server.
"""
return self._current_application().execute_script('mobile: shell', {
'command': command,
'args': list(args)
})
def execute_adb_shell_timeout(self, command, timeout, *args):
"""
Execute ADB shell commands
Android only.
- _command_ - The ABD shell command
- _timeout_ - Timeout to be applied to command
- _args_ - Arguments to send to command
Returns the exit code of ADB shell.
Requires server flag --relaxed-security to be set on Appium server.
"""
return self._current_application().execute_script('mobile: shell', {
'command': command,
'args': list(args),
'timeout': timeout
})
def go_back(self):
"""Goes one step backward in the browser history."""
self._current_application().back()
def lock(self, seconds=5):
"""
Lock the device for a certain period of time. iOS only.
"""
self._current_application().lock(robot.utils.timestr_to_secs(seconds))
def background_app(self, seconds=5):
"""*DEPRECATED!!* use `Background Application` instead.
Puts the application in the background on the device for a certain
duration.
"""
self._current_application().background_app(seconds)
def background_application(self, seconds=5):
"""
Puts the application in the background on the device for a certain
duration.
"""
self._current_application().background_app(seconds)
def activate_application(self, app_id):
"""
Activates the application if it is not running or is running in the background.
Args:
- app_id - BundleId for iOS. Package name for Android.
New in AppiumLibrary v2
"""
self._current_application().activate_app(app_id)
def terminate_application(self, app_id, timeout=500):
"""
Terminate the given app on the device
Args:
- app_id - BundleId for iOS. Package name for Android.
- timeout - Timeout for the terminate operation in milliseconds (default 500)
New in AppiumLibrary v2
"""
return self._current_application().terminate_app(app_id, timeout=timeout)
def stop_application(self, app_id, timeout=5000, include_stderr=True):
"""
Stop the given app on the device
Android only. New in AppiumLibrary v2
"""
self._current_application().execute_script('mobile: shell', {
'command': 'am force-stop',
'args': [app_id],
'includeStderr': include_stderr,
'timeout': timeout
})
def touch_id(self, match=True):
"""
Simulate Touch ID on iOS Simulator
`match` (boolean) whether the simulated fingerprint is valid (default true)
New in AppiumLibrary 1.5
"""
self._current_application().touch_id(match)
def toggle_touch_id_enrollment(self):
"""
Toggle Touch ID enrolled state on iOS Simulator
New in AppiumLibrary 1.5
"""
self._current_application().toggle_touch_id_enrollment()
def shake(self):
"""
Shake the device
"""
self._current_application().shake()
def portrait(self):
"""
Set the device orientation to PORTRAIT
"""
self._rotate('PORTRAIT')
def landscape(self):
"""
Set the device orientation to LANDSCAPE
"""
self._rotate('LANDSCAPE')
def get_current_context(self):
"""Get current context."""
return self._current_application().current_context
def get_contexts(self):
"""Get available contexts."""
print(self._current_application().contexts)
return self._current_application().contexts
def get_window_height(self):
"""Get current device height.
Example:
| ${width} | Get Window Width |
| ${height} | Get Window Height |
| Click A Point | ${width} | ${height} |
New in AppiumLibrary 1.4.5
"""
return self._current_application().get_window_size()['height']
def get_window_width(self):
"""Get current device width.
Example:
| ${width} | Get Window Width |
| ${height} | Get Window Height |
| Click A Point | ${width} | ${height} |
New in AppiumLibrary 1.4.5
"""
return self._current_application().get_window_size()['width']
def switch_to_context(self, context_name):
"""Switch to a new context"""
self._current_application().switch_to.context(context_name)
def switch_to_frame(self, frame):
"""
Switches focus to the specified frame, by index, name, or webelement.
Example:
| Go To Url | http://www.xxx.com |
| Switch To Frame | iframe_name|
| Click Element | xpath=//*[@id="online-btn"] |
"""
self._current_application().switch_to.frame(frame)
def switch_to_parent_frame(self):
"""
Switches focus to the parent context. If the current context is the top
level browsing context, the context remains unchanged.
"""
self._current_application().switch_to.parent_frame()
def switch_to_window(self, window_name):
"""
Switch to a new webview window if the application contains multiple webviews
"""
self._current_application().switch_to.window(window_name)
def go_to_url(self, url):
"""
Opens URL in default web browser.
Example:
| Open Application | http://localhost:4755/wd/hub | platformName=iOS | platformVersion=7.0 | deviceName='iPhone Simulator' | browserName=Safari |
| Go To URL | http://m.webapp.com |
"""
self._current_application().get(url)
def get_capability(self, capability_name):
"""
Return the desired capability value by desired capability name
"""
try:
capability = self._current_application().capabilities[capability_name]
except Exception as e:
raise e
return capability
def get_window_title(self):
"""Get the current Webview window title."""
return self._current_application().title
def get_window_url(self):
"""Get the current Webview window URL."""
return self._current_application().current_url
def get_windows(self):
"""Get available Webview windows."""
print(self._current_application().window_handles)
return self._current_application().window_handles
# Private
def _current_application(self):
if not self._cache.current:
raise RuntimeError('No application is open')
return self._cache.current
def _get_platform(self):
try:
platform_name = self._current_application().capabilities['platformName']
except Exception as e:
raise e
return platform_name.lower()
def _is_platform(self, platform):
platform_name = self._get_platform()
return platform.lower() == platform_name
def _is_ios(self):
return self._is_platform('ios')
def _is_android(self):
return self._is_platform('android')
def _rotate(self, orientation):
driver = self._current_application()
driver.orientation = orientation