-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelement_interactor.py
More file actions
236 lines (207 loc) · 8.38 KB
/
element_interactor.py
File metadata and controls
236 lines (207 loc) · 8.38 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
from enum import Enum
from typing import Tuple, Optional, Literal, List, cast
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.pointer_input import PointerInput
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException, NoSuchElementException
Locator = Tuple[str, str]
type Condition = Literal["clickable", "visible", "present"]
class WaitType(Enum):
DEFAULT = 15
SHORTEST = 2
SHORT = 5
LONG = 60
FLUENT = 10
class ElementInteractor:
def __init__(self, driver):
self.driver = driver
self.waiters = {
wait_type: WebDriverWait(driver, wait_type.value)
for wait_type in WaitType
if wait_type != WaitType.FLUENT
}
self.waiters[WaitType.FLUENT] = WebDriverWait(
driver, WaitType.FLUENT.value, poll_frequency=1
)
def _get_waiter(self, wait_type: Optional[WaitType] = None) -> WebDriverWait:
"""Returns the appropriate waiter based on the given wait_type."""
return self.waiters.get(wait_type, self.waiters[WaitType.DEFAULT])
def wait_for(
self,
locator: Locator,
condition: Condition = "visible",
waiter: Optional[WebDriverWait] = None,
) -> WebElement:
waiter = waiter or self._get_waiter()
conditions = {
"clickable": ec.element_to_be_clickable(locator),
"visible": ec.visibility_of_element_located(locator),
"present": ec.presence_of_element_located(locator),
}
if condition not in conditions:
raise ValueError(f"Unknown condition: {condition}")
try:
return waiter.until(conditions[condition])
except TimeoutException as e:
raise TimeoutException(
f"Condition '{condition}' failed for element {locator} after {waiter._timeout} seconds"
) from e
def element(
self,
locator: Locator,
n: int = 3,
condition: Condition = "visible",
wait_type: Optional[WaitType] = WaitType.DEFAULT,
):
for attempt in range(1, n + 1):
try:
self.wait_for(
locator, condition=condition, waiter=self._get_waiter(wait_type)
)
return self.driver.find_element(*locator)
except NoSuchElementException:
if attempt == n:
raise NoSuchElementException(
f"Could not locate element with value: {locator}"
)
def elements(
self,
locator: Locator,
n: int = 3,
condition: Condition = "visible",
wait_type: Optional[WaitType] = WaitType.DEFAULT,
) -> List[WebElement]:
for attempt in range(1, n + 1):
try:
self.wait_for(
locator, condition=condition, waiter=self._get_waiter(wait_type)
)
return self.driver.find_elements(*locator)
except NoSuchElementException:
if attempt == n:
raise NoSuchElementException(
f"Could not locate element list with value: {locator}"
)
def is_displayed(
self,
locator: Locator,
expected: bool = True,
n: int = 3,
condition: Condition = "visible",
wait_type: Optional[WaitType] = None,
) -> None:
wait_type = wait_type or WaitType.DEFAULT
for _ in range(n):
try:
element = self.wait_for(
locator, condition=condition, waiter=self._get_waiter(wait_type)
)
assert element.is_displayed() == expected
return
except Exception:
time.sleep(0.5)
if expected: # Assert if the element is expected to be displayed but isn't
raise AssertionError(f"Element {locator} was not displayed as expected.")
else: # Assert if the element should not be displayed but is
raise AssertionError(
f"Element {locator} was displayed when it shouldn't be."
)
def is_exist(
self,
locator: Locator,
expected: bool = True,
n: int = 3,
condition: Condition = "visible",
wait_type: Optional[WaitType] = WaitType.SHORTEST,
retry_delay: float = 0.5,
) -> bool:
"""
Checks if an element exists on the screen within a specified number of retries.
:param retry_delay: delay between retry
:param locator: The locator tuple (strategy, value) used to find the element.
:param expected: Determines whether the element should exist (True) or not (False).
:param n: The number of attempts to check for the element before returning a result.
:param condition: The condition to check for the element's existence.
- "clickable": Ensures the element is interactable.
- "visible": Ensures the element is visible on the page.
- "present": Ensures the element exists in the DOM (even if not visible).
:param wait_type: Specifies the wait strategy (default is WaitType.DEFAULT).
:return: True if the element matches the expected state, False otherwise.
:rtype: bool
**Usage Example:**
screen.is_exist(("id", "login-button"))
True
screen.is_exist(("id", "error-popup"), expected=False)
True
"""
for _ in range(n):
try:
element = self.element(
locator, n=1, condition=condition, wait_type=wait_type
)
return element.is_displayed() == expected
except (NoSuchElementException, TimeoutException):
if not expected:
return True
except Exception as e:
print(f"Unexpected error in is_exist: {e}")
time.sleep(retry_delay)
return not expected
def scroll_by_coordinates(
self,
start_x: int,
start_y: int,
end_x: int,
end_y: int,
duration: Optional[int] = None,
):
"""Scrolls from one set of coordinates to another.
Args:
start_x: X coordinate to start scrolling from.
start_y: Y coordinate to start scrolling from.
end_x: X coordinate to scroll to.
end_y: Y coordinate to scroll to.
duration: Defines speed of scroll action. Default is 700 ms.
"""
if duration is None:
duration = 700
touch_input = PointerInput(interaction.POINTER_TOUCH, "touch")
actions = ActionChains(self.driver)
actions.w3c_actions = ActionBuilder(self.driver, mouse=touch_input)
actions.w3c_actions.pointer_action.move_to_location(start_x, start_y)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions = ActionBuilder(
self.driver, mouse=touch_input, duration=duration
)
actions.w3c_actions.pointer_action.move_to_location(end_x, end_y)
actions.w3c_actions.pointer_action.release()
actions.perform()
def double_tap_actions(
self,
locator,
condition: Condition = "clickable",
index: Optional[int] = None,
n: int = 2,
):
"""
Performs a double tap using ActionChains.
- Waits for the element(s) to be visible
- Works for both single and multiple elements (use index for multiple)
:param condition:
:param locator: Tuple (By, value)
:param index: Index of element in case of multiple elements
:param n: Number of attempts to locate element
"""
elements = self.elements(locator, condition=condition, n=n)
if not elements:
raise NoSuchElementException(
f"Could not locate element with value: {locator}"
)
element = elements[index] if index is not None else elements[0]
actions = ActionChains(self.driver)
actions.double_click(element).perform()