forked from appium/python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebdriver.py
More file actions
377 lines (315 loc) · 14 KB
/
webdriver.py
File metadata and controls
377 lines (315 loc) · 14 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
#!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-lines,too-many-public-methods,too-many-statements,no-self-use
import copy
from typing import Any, Dict, List, Optional, TypeVar, Union
from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.command import Command as RemoteCommand
from selenium.webdriver.remote.remote_connection import RemoteConnection
from appium.common.logger import logger
from appium.webdriver.common.mobileby import MobileBy
from .appium_connection import AppiumConnection
from .errorhandler import MobileErrorHandler
from .extensions.action_helpers import ActionHelpers
from .extensions.android.activities import Activities
from .extensions.android.common import Common
from .extensions.android.display import Display
from .extensions.android.gsm import Gsm
from .extensions.android.network import Network
from .extensions.android.performance import Performance
from .extensions.android.power import Power
from .extensions.android.sms import Sms
from .extensions.android.system_bars import SystemBars
from .extensions.applications import Applications
from .extensions.clipboard import Clipboard
from .extensions.context import Context
from .extensions.device_time import DeviceTime
from .extensions.execute_driver import ExecuteDriver
from .extensions.execute_mobile_command import ExecuteMobileCommand
from .extensions.hw_actions import HardwareActions
from .extensions.images_comparison import ImagesComparison
from .extensions.ime import IME
from .extensions.keyboard import Keyboard
from .extensions.location import Location
from .extensions.log_event import LogEvent
from .extensions.remote_fs import RemoteFS
from .extensions.screen_record import ScreenRecord
from .extensions.search_context import AppiumSearchContext
from .extensions.session import Session
from .extensions.settings import Settings
from .mobilecommand import MobileCommand as Command
from .switch_to import MobileSwitchTo
from .webelement import WebElement as MobileWebElement
# From remote/webdriver.py
_W3C_CAPABILITY_NAMES = frozenset([
'acceptInsecureCerts',
'browserName',
'browserVersion',
'platformName',
'pageLoadStrategy',
'proxy',
'setWindowRect',
'timeouts',
'unhandledPromptBehavior',
])
# From remote/webdriver.py
_OSS_W3C_CONVERSION = {
'acceptSslCerts': 'acceptInsecureCerts',
'version': 'browserVersion',
'platform': 'platformName'
}
_EXTENSION_CAPABILITY = ':'
_FORCE_MJSONWP = 'forceMjsonwp'
# override
# Add appium prefix for the non-W3C capabilities
def _make_w3c_caps(caps: Dict) -> Dict[str, List[Dict[str, Any]]]:
appium_prefix = 'appium:'
caps = copy.deepcopy(caps)
profile = caps.get('firefox_profile')
first_match = {}
if caps.get('proxy') and caps['proxy'].get('proxyType'):
caps['proxy']['proxyType'] = caps['proxy']['proxyType'].lower()
for k, v in caps.items():
if v and k in _OSS_W3C_CONVERSION:
first_match[_OSS_W3C_CONVERSION[k]] = v.lower() if k == 'platform' else v
if k in _W3C_CAPABILITY_NAMES or _EXTENSION_CAPABILITY in k:
first_match[k] = v
else:
if not k.startswith(appium_prefix):
first_match[appium_prefix + k] = v
if profile:
moz_opts = first_match.get('moz:firefoxOptions', {})
# If it's already present, assume the caller did that intentionally.
if 'profile' not in moz_opts:
# Don't mutate the original capabilities.
new_opts = copy.deepcopy(moz_opts)
new_opts['profile'] = profile
first_match['moz:firefoxOptions'] = new_opts
return {'firstMatch': [first_match]}
T = TypeVar('T', bound='WebDriver')
class WebDriver(
AppiumSearchContext,
ActionHelpers,
Activities,
Applications,
Clipboard,
Context,
Common,
DeviceTime,
Display,
ExecuteDriver,
ExecuteMobileCommand,
Gsm,
HardwareActions,
ImagesComparison,
IME,
Keyboard,
Location,
LogEvent,
Network,
Performance,
Power,
RemoteFS,
ScreenRecord,
Session,
Settings,
Sms,
SystemBars
):
def __init__(self, command_executor: str = 'http://127.0.0.1:4444/wd/hub',
desired_capabilities: Optional[Dict] = None, browser_profile: str = None, proxy: str = None, keep_alive: bool = True, direct_connection: bool = False):
super().__init__(
AppiumConnection(command_executor, keep_alive=keep_alive),
desired_capabilities,
browser_profile,
proxy
)
if hasattr(self, 'command_executor'):
self._addCommands()
self.error_handler = MobileErrorHandler()
self._switch_to = MobileSwitchTo(self)
if direct_connection:
self._update_command_executor(keep_alive=keep_alive)
# add new method to the `find_by_*` pantheon
By.IOS_UIAUTOMATION = MobileBy.IOS_UIAUTOMATION
By.IOS_PREDICATE = MobileBy.IOS_PREDICATE
By.IOS_CLASS_CHAIN = MobileBy.IOS_CLASS_CHAIN
By.ANDROID_UIAUTOMATOR = MobileBy.ANDROID_UIAUTOMATOR
By.ANDROID_VIEWTAG = MobileBy.ANDROID_VIEWTAG
By.WINDOWS_UI_AUTOMATION = MobileBy.WINDOWS_UI_AUTOMATION
By.ACCESSIBILITY_ID = MobileBy.ACCESSIBILITY_ID
By.IMAGE = MobileBy.IMAGE
By.CUSTOM = MobileBy.CUSTOM
def _update_command_executor(self, keep_alive: bool) -> None:
"""Update command executor following directConnect feature"""
direct_protocol = 'directConnectProtocol'
direct_host = 'directConnectHost'
direct_port = 'directConnectPort'
direct_path = 'directConnectPath'
if (not {direct_protocol, direct_host, direct_port, direct_path}.issubset(set(self.capabilities))):
message = 'Direct connect capabilities from server were:\n'
for key in [direct_protocol, direct_host, direct_port, direct_path]:
message += '{}: \'{}\'\n'.format(key, self.capabilities.get(key, ''))
logger.warning(message)
return
protocol = self.capabilities[direct_protocol]
hostname = self.capabilities[direct_host]
port = self.capabilities[direct_port]
path = self.capabilities[direct_path]
executor = f'{protocol}://{hostname}:{port}{path}'
logger.info('Updated request endpoint to %s', executor)
# Override command executor
self.command_executor = RemoteConnection(executor, keep_alive=keep_alive)
self._addCommands()
def start_session(self, capabilities: Dict, browser_profile: Optional[str] = None) -> None:
"""Creates a new session with the desired capabilities.
Override for Appium
Args:
automation_name: The name of automation engine to use.
platform_name: The name of target platform.
platform_version: The kind of mobile device or emulator to use
app: The absolute local path or remote http URL to an .ipa or .apk file, or a .zip containing one of these.
Read https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md for more details.
"""
if not isinstance(capabilities, dict):
raise InvalidArgumentException('Capabilities must be a dictionary')
if browser_profile:
if 'moz:firefoxOptions' in capabilities:
# encoded is defined in selenium's original codes
capabilities['moz:firefoxOptions']['profile'] = browser_profile.encoded # type: ignore
else:
# encoded is defined in selenium's original codes
capabilities.update({'firefox_profile': browser_profile.encoded}) # type: ignore
parameters = self._merge_capabilities(capabilities)
response = self.execute(RemoteCommand.NEW_SESSION, parameters)
if 'sessionId' not in response:
response = response['value']
self.session_id = response['sessionId']
self.capabilities = response.get('value')
# if capabilities is none we are probably speaking to
# a W3C endpoint
if self.capabilities is None:
self.capabilities = response.get('capabilities')
# Double check to see if we have a W3C Compliant browser
self.w3c = response.get('status') is None
self.command_executor.w3c = self.w3c
def _merge_capabilities(self, capabilities: Dict) -> Dict[str, Any]:
"""Manage capabilities whether W3C format or MJSONWP format
"""
if _FORCE_MJSONWP in capabilities:
force_mjsonwp = capabilities[_FORCE_MJSONWP]
del capabilities[_FORCE_MJSONWP]
if force_mjsonwp != False:
return {'desiredCapabilities': capabilities}
w3c_caps = _make_w3c_caps(capabilities)
return {'capabilities': w3c_caps, 'desiredCapabilities': capabilities}
def find_element(self, by: str = By.ID, value: Union[str, Dict] = None) -> MobileWebElement:
"""'Private' method used by the find_element_by_* methods.
Override for Appium
Usage:
Use the corresponding find_element_by_* instead of this.
Returns:
`appium.webdriver.webelement.WebElement`
:rtype: `MobileWebElement`
"""
# TODO: If we need, we should enable below converter for Web context
# if self.w3c:
# if by == By.ID:
# by = By.CSS_SELECTOR
# value = '[id="%s"]' % value
# elif by == By.TAG_NAME:
# by = By.CSS_SELECTOR
# elif by == By.CLASS_NAME:
# by = By.CSS_SELECTOR
# value = ".%s" % value
# elif by == By.NAME:
# by = By.CSS_SELECTOR
# value = '[name="%s"]' % value
return self.execute(RemoteCommand.FIND_ELEMENT, {
'using': by,
'value': value})['value']
def find_elements(self, by: str = By.ID, value: Union[str, Dict]
= None) -> Union[List[MobileWebElement], List]:
"""'Private' method used by the find_elements_by_* methods.
Override for Appium
Usage:
Use the corresponding find_elements_by_* instead of this.
Returns:
:obj:`list` of :obj:`appium.webdriver.webelement.WebElement`
:rtype: list of `MobileWebElement`
"""
# TODO: If we need, we should enable below converter for Web context
# if self.w3c:
# if by == By.ID:
# by = By.CSS_SELECTOR
# value = '[id="%s"]' % value
# elif by == By.TAG_NAME:
# by = By.CSS_SELECTOR
# elif by == By.CLASS_NAME:
# by = By.CSS_SELECTOR
# value = ".%s" % value
# elif by == By.NAME:
# by = By.CSS_SELECTOR
# value = '[name="%s"]' % value
# Return empty list if driver returns null
# See https://github.com/SeleniumHQ/selenium/issues/4555
return self.execute(RemoteCommand.FIND_ELEMENTS, {
'using': by,
'value': value})['value'] or []
def create_web_element(self, element_id: int, w3c: bool = False) -> MobileWebElement:
"""Creates a web element with the specified element_id.
Overrides method in Selenium WebDriver in order to always give them
Appium WebElement
Args:
element_id (int): The element id to create a web element
w3c (bool): Whether the element is W3C or MJSONWP
Returns:
`MobileWebElement`
"""
return MobileWebElement(self, element_id, w3c)
def set_value(self, element: MobileWebElement, value: str) -> T:
"""Set the value on an element in the application.
Args:
element (`appium.webdriver.webelement.WebElement`: the element whose value will be set
value (str): the value to set on the element
Returns:
`appium.webdriver.webdriver.WebDriver`
"""
data = {
'id': element.id,
'value': [value],
}
self.execute(Command.SET_IMMEDIATE_VALUE, data)
return self
# pylint: disable=protected-access
def _addCommands(self) -> None:
# call the overridden command binders from all mixin classes except for
# appium.webdriver.webdriver.WebDriver and its sub-classes
# https://github.com/appium/python-client/issues/342
for mixin_class in filter(lambda x: not issubclass(x, WebDriver), self.__class__.__mro__):
if hasattr(mixin_class, self._addCommands.__name__):
getattr(mixin_class, self._addCommands.__name__, None)(self)
self.command_executor._commands[Command.TOUCH_ACTION] = \
('POST', '/session/$sessionId/touch/perform')
self.command_executor._commands[Command.MULTI_ACTION] = \
('POST', '/session/$sessionId/touch/multi/perform')
self.command_executor._commands[Command.SET_IMMEDIATE_VALUE] = \
('POST', '/session/$sessionId/appium/element/$id/value')
# TODO Move commands for element to webelement
self.command_executor._commands[Command.REPLACE_KEYS] = \
('POST', '/session/$sessionId/appium/element/$id/replace_value')
self.command_executor._commands[Command.CLEAR] = \
('POST', '/session/$sessionId/element/$id/clear')
self.command_executor._commands[Command.LOCATION_IN_VIEW] = \
('GET', '/session/$sessionId/element/$id/location_in_view')