Skip to content

mobile_client_actions

MobileClientActions

Provides actions for interacting with mobile elements.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
 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
class MobileClientActions:
    """Provides actions for interacting with mobile elements."""

    def __init__(self, mobile_driver: webdriver.Remote = None, default_explicit_wait: int = None):
        """Initializes MobileClientActions with a driver and optional explicit
        wait.

        Args:
            mobile_driver: The Appium webdriver instance.
                            if not provided, it will be picked from Session Store
            default_explicit_wait: The default explicit wait time (in seconds).
                                   If not provided, it will be retrieved from ConfigUtils.
        """
        self.mobile_driver = mobile_driver or SessionStore().mobile_driver
        self.default_explicit_wait = default_explicit_wait or ConfigUtils().get_explicit_wait()
        self.logger = CoreLogger(name=__name__).get_logger()
        self.__exceptions_generic = CoreExceptions()

        self.mobile_locator_strategies = {
            "XPATH": AppiumBy.XPATH,
            "ID": AppiumBy.ID,
            "NAME": AppiumBy.NAME,
            "CLASS_NAME": AppiumBy.CLASS_NAME,
            "ACCESSIBILITY_ID": AppiumBy.ACCESSIBILITY_ID,
            "ANDROID_UIAUTOMATOR": AppiumBy.ANDROID_UIAUTOMATOR,
            "IOS_PREDICATE": AppiumBy.IOS_PREDICATE,
            "CLASS_CHAIN": AppiumBy.IOS_CLASS_CHAIN,
        }

    def get_driver_context(self) -> str:
        """Returns the current driver context (e.g., WEBVIEW, NATIVE)."""
        try:
            return self.mobile_driver.current_context
        except Exception as e:
            error_description = f"Error getting driver context: {str(e)}"
            self.__exceptions_generic.raise_generic_exception(
                message=error_description, fail_test=False
            )
            return ""

    def switch_driver_context(self, context: str) -> bool:
        """Switches the driver context to 'WEBVIEW' or 'NATIVE'.

        Args:
            context: The desired context ('WEBVIEW' or 'NATIVE').

        Returns:
            True if the context switch was successful, False otherwise.
        """
        try:
            context = context.lower()
            if context == "webview":
                self.mobile_driver.switch_to.context(self.mobile_driver.contexts[1])
                return True
            if context == "native":
                self.mobile_driver.switch_to.context(self.mobile_driver.contexts[0])
                return True
            return False  # If context is not webview or native
        except Exception as e:
            error_description = f"Error switching driver context to '{context}': {str(e)}"
            self.__exceptions_generic.raise_generic_exception(
                message=error_description, fail_test=False
            )
            return False

    def open_deep_link(self, link: str) -> None:
        """Opens a deep link in the mobile app.

        Args:
            link: The deep link URL.
        """
        try:
            self.mobile_driver.get(link)
        except Exception as e:
            self.logger.exception("Error opening deep link '%s': %s", link, e)
            raise e

    def get_page_url(self) -> str:
        """Returns the current URL of the webview context."""
        try:
            return self.mobile_driver.current_url
        except Exception as e:
            self.logger.exception("Error getting page URL: %s", e)
            raise e

    def terminate_mobile_app(self, package: str) -> None:
        """Terminates the mobile app specified by the package name or bundle
        ID.

        Args:
            package:  The Android package name or iOS bundle ID of the app.

        Raises:
            Exception: If an error occurs during app termination.
        """
        try:
            self.mobile_driver.terminate_app(package)
        except Exception as e:
            self.logger.exception("Error terminating mobile app '%s': %s", package, e)
            raise e

    def activate_mobile_app(self, package: str) -> None:
        """Activates the mobile app specified by the package name or bundle ID.

        Args:
            package: The Android package name or iOS bundle ID of the app.

        Raises:
            Exception: If an error occurs during app activation.
        """
        try:
            self.mobile_driver.activate_app(package)
            self.mobile_driver.orientation = "PORTRAIT"
            # Switch to native context if not already there
            if self.get_driver_context() != self.mobile_driver.contexts[0]:
                self.switch_driver_context("NATIVE")
        except Exception as e:
            self.logger.exception("Error activating mobile app '%s': %s", package, e)
            raise e

    def _get_mobile_locator_strategy(self, locator_strategy: str) -> str:
        """Returns the AppiumBy locator strategy based on the input string.

        Args:
            locator_strategy: The locator strategy as a string
                             (e.g., 'XPATH', 'ID', 'ACCESSIBILITY_ID').

        Returns:
            The corresponding AppiumBy locator strategy.

        Raises:
            ValueError: If the locator strategy is not supported.
        """
        try:
            strategy = locator_strategy.strip().replace(" ", "_").upper()
            if strategy in self.mobile_locator_strategies:
                return self.mobile_locator_strategies[strategy]

            raise ValueError(
                f"Unsupported locator strategy: {locator_strategy}. "
                f"Supported strategies are: {', '.join(self.mobile_locator_strategies.keys())}"
            )
        except Exception as e:
            self.logger.exception("Error in get_mobile_locator_strategy: %s", e)
            raise e

    def _parse_locator(self, locator_string: str) -> Tuple[str, str]:
        """Parses a locator string in the format "strategy=value" and returns
        the corresponding AppiumBy strategy and locator value.

        Args:
            locator_string: The locator string.

        Returns:
            A tuple containing the AppiumBy strategy and the locator value.

        Raises:
            ValueError: If the locator string is invalid.
        """
        try:
            strategy, value = locator_string.split("=", 1)
            strategy = self._get_mobile_locator_strategy(strategy)
            return strategy, value.strip()
        except ValueError as e:
            raise ValueError(
                f"Invalid locator string: {locator_string}. "
                f"It must be in the format 'strategy=value'."
            ) from e

    def is_element_displayed(
            self, locator: Union[str, WebElement], explicit_wait: int = None
    ) -> bool:
        """Verifies if an element is displayed on the screen.

        Args:
            locator: Locator string in the format "strategy=value"
                     (e.g., "id=my_element" or "xpath=//button[@name='submit']")
                     or a WebElement object.
            explicit_wait:  Optional explicit wait time (in seconds).
                           Defaults to the configured default explicit wait.

        Returns:
            True if the element is displayed, False otherwise.

        Raises:
            ValueError: If an invalid locator string is provided.
            TypeError: If an invalid locator type is provided.
            Exception: If any other error occurs while checking element visibility.
        """
        try:
            explicit_wait = explicit_wait or self.default_explicit_wait

            if isinstance(locator, str):
                strategy, value = self._parse_locator(locator)

                element = WebDriverWait(self.mobile_driver, explicit_wait).until(
                    EC.visibility_of_element_located((strategy, value))
                )
                return bool(element)
            if isinstance(locator, WebElement):
                return locator.is_displayed()

            raise TypeError("Invalid locator type. Must be a string or a WebElement.")

        except Exception as e:
            error_description = f"Error checking visibility of element: '{locator}': {str(e)}"
            self.__exceptions_generic.raise_generic_exception(
                message=error_description, trim_log=True, fail_test=False
            )
            return False

    def get_clickable_mobile_element(
            self, locator: Union[str, WebElement], explicit_wait: int = None
    ) -> WebElement:
        """Waits for an element to be clickable and returns it.

        Args:
            locator: Locator string in the format "strategy=value" or a WebElement object.
            explicit_wait: Optional explicit wait time (seconds).

        Returns:
            The clickable WebElement.

        Raises:
            ValueError: If an invalid locator string is provided.
            TypeError: If an invalid locator type is provided.
            TimeoutException: If the element is not clickable within the explicit wait time.
        """
        try:
            explicit_wait = explicit_wait or self.default_explicit_wait

            if isinstance(locator, str):
                strategy, value = self._parse_locator(locator)
                return WebDriverWait(self.mobile_driver, explicit_wait).until(
                    EC.element_to_be_clickable((strategy, value))
                )
            if isinstance(locator, WebElement):
                return locator

            raise TypeError("Invalid locator type. Must be a string or a WebElement.")
        except Exception as e:
            self.logger.exception("Error getting clickable element: %s. Error: %s", locator, e)
            raise e

    def click(self, locator: str, explicit_wait: int = None) -> None:
        """Clicks on a mobile element.

        Args:
            locator: Locator string in the format "strategy=value".
            explicit_wait: Optional explicit wait time (seconds).

        Raises:
            ValueError: If an invalid locator string is provided.
            Exception: If an error occurs while clicking the element.
        """
        try:
            element = self.get_clickable_mobile_element(locator, explicit_wait)
            element.click()
        except Exception as e:
            self.logger.exception("Error clicking element: %s. Error: %s", locator, e)
            raise e

    def type(
            self,
            locator: str,
            text: str,
            explicit_wait: int = None,
            clear: bool = False,
            click_before_type: bool = True,
    ) -> None:
        """Types text into a mobile element.

        Args:
            locator: Locator string in the format "strategy=value".
            text: The text to type.
            explicit_wait: Optional explicit wait time (seconds).
            clear: If True, clears the element before typing.
            click_before_type: If True, clicks the element before typing.

        Raises:
            ValueError: If an invalid locator string is provided.
            Exception: If an error occurs while typing.
        """
        try:
            element = self.get_clickable_mobile_element(locator, explicit_wait)
            if click_before_type:
                element.click()
            if clear:
                element.clear()
            element.send_keys(text)
        except Exception as e:
            self.logger.exception(
                "Error typing text '%s' into element: %s. Error: %s", text, locator, e
            )
            raise e

    def is_element_present(
            self, locator: Union[str, WebElement], explicit_wait: int = None
    ) -> bool:
        """Checks if an element is present in the DOM.

        Args:
            locator: Locator string in the format "strategy=value" or a WebElement object.
            explicit_wait: Optional explicit wait time (seconds).

        Returns:
            True if the element is present, False otherwise.

        Raises:
            ValueError: If an invalid locator string is provided.
            TypeError: If an invalid locator type is provided.
            Exception: If an error occurs while checking element presence.
        """
        try:
            explicit_wait = explicit_wait or self.default_explicit_wait

            if isinstance(locator, str):
                strategy, value = self._parse_locator(locator)
                element = WebDriverWait(self.mobile_driver, explicit_wait).until(
                    EC.presence_of_element_located((strategy, value))
                )
                return bool(element)
            if isinstance(locator, WebElement):
                return True  # A WebElement object is always considered present

            raise TypeError("Invalid locator type. Must be a string or a WebElement.")
        except Exception as e:
            self.logger.exception("Error checking presence of element: %s. Error: %s", locator, e)
            raise e

    def get_web_element(
            self, locator: Union[str, WebElement], explicit_wait: int = None
    ) -> WebElement:
        """Locates and returns a mobile element.

        Args:
            locator: Locator string in the format "strategy=value" or a WebElement object.
            explicit_wait: Optional explicit wait time (seconds).

        Returns:
            The located WebElement.

        Raises:
            ValueError: If an invalid locator string is provided.
            TypeError: If an invalid locator type is provided.
            TimeoutException: If the element is not found within the explicit wait time.
        """
        try:
            explicit_wait = explicit_wait or self.default_explicit_wait

            if isinstance(locator, str):
                strategy, value = self._parse_locator(locator)
                return WebDriverWait(self.mobile_driver, explicit_wait).until(
                    EC.presence_of_element_located((strategy, value))
                )
            if isinstance(locator, WebElement):
                return locator

            raise TypeError("Invalid locator type. Must be a string or a WebElement.")
        except Exception as e:
            self.logger.exception("Error locating element: %s. Error: %s", locator, e)
            raise e

    def scroll_mobile(
            self, direction: str, find_locator: str, explicit_wait: int = None, max_swipes: int = 10
    ) -> bool:
        """Scrolls horizontally or vertically to find an element.

        Args:
            direction: Scroll direction ('down', 'up', 'right', 'left').
            find_locator: Locator string of the element to find.
            explicit_wait: Optional explicit wait time (seconds).
            max_swipes: Maximum number of swipes to attempt.

        Returns:
            True if the element is found, False otherwise.

        Raises:
            Exception: If an error occurs during scrolling.
        """
        try:
            explicit_wait = explicit_wait or self.default_explicit_wait

            if self.is_element_displayed(find_locator, explicit_wait):
                return True

            size = self.mobile_driver.get_window_size()
            for _ in range(max_swipes):
                if direction == "down":
                    self.mobile_driver.swipe(
                        size["width"] * 0.20,
                        size["height"] * 0.80,
                        size["width"] * 0.20,
                        size["height"] * 0.20,
                        3000,
                    )
                elif direction == "up":
                    self.mobile_driver.swipe(
                        size["width"] * 0.20,
                        size["height"] * 0.20,
                        size["width"] * 0.20,
                        size["height"] * 0.80,
                        3000,
                    )
                elif direction == "right":
                    self.mobile_driver.swipe(
                        size["width"] * 0.80,
                        size["height"] * 0.50,
                        size["width"] * 0.20,
                        size["height"] * 0.50,
                        3000,
                    )
                elif direction == "left":
                    self.mobile_driver.swipe(
                        size["width"] * 0.20,
                        size["height"] * 0.50,
                        size["width"] * 0.80,
                        size["height"] * 0.50,
                        3000,
                    )

                if self.is_element_displayed(find_locator, explicit_wait):
                    return True

            return False

        except Exception as e:
            self.logger.exception("Exception in scroll_mobile method. Exception Details: %s", e)
            raise e

__init__(mobile_driver=None, default_explicit_wait=None)

Initializes MobileClientActions with a driver and optional explicit wait.

Parameters:

Name Type Description Default
mobile_driver Remote

The Appium webdriver instance. if not provided, it will be picked from Session Store

None
default_explicit_wait int

The default explicit wait time (in seconds). If not provided, it will be retrieved from ConfigUtils.

None
Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
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
def __init__(self, mobile_driver: webdriver.Remote = None, default_explicit_wait: int = None):
    """Initializes MobileClientActions with a driver and optional explicit
    wait.

    Args:
        mobile_driver: The Appium webdriver instance.
                        if not provided, it will be picked from Session Store
        default_explicit_wait: The default explicit wait time (in seconds).
                               If not provided, it will be retrieved from ConfigUtils.
    """
    self.mobile_driver = mobile_driver or SessionStore().mobile_driver
    self.default_explicit_wait = default_explicit_wait or ConfigUtils().get_explicit_wait()
    self.logger = CoreLogger(name=__name__).get_logger()
    self.__exceptions_generic = CoreExceptions()

    self.mobile_locator_strategies = {
        "XPATH": AppiumBy.XPATH,
        "ID": AppiumBy.ID,
        "NAME": AppiumBy.NAME,
        "CLASS_NAME": AppiumBy.CLASS_NAME,
        "ACCESSIBILITY_ID": AppiumBy.ACCESSIBILITY_ID,
        "ANDROID_UIAUTOMATOR": AppiumBy.ANDROID_UIAUTOMATOR,
        "IOS_PREDICATE": AppiumBy.IOS_PREDICATE,
        "CLASS_CHAIN": AppiumBy.IOS_CLASS_CHAIN,
    }

activate_mobile_app(package)

Activates the mobile app specified by the package name or bundle ID.

Parameters:

Name Type Description Default
package str

The Android package name or iOS bundle ID of the app.

required

Raises:

Type Description
Exception

If an error occurs during app activation.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def activate_mobile_app(self, package: str) -> None:
    """Activates the mobile app specified by the package name or bundle ID.

    Args:
        package: The Android package name or iOS bundle ID of the app.

    Raises:
        Exception: If an error occurs during app activation.
    """
    try:
        self.mobile_driver.activate_app(package)
        self.mobile_driver.orientation = "PORTRAIT"
        # Switch to native context if not already there
        if self.get_driver_context() != self.mobile_driver.contexts[0]:
            self.switch_driver_context("NATIVE")
    except Exception as e:
        self.logger.exception("Error activating mobile app '%s': %s", package, e)
        raise e

click(locator, explicit_wait=None)

Clicks on a mobile element.

Parameters:

Name Type Description Default
locator str

Locator string in the format "strategy=value".

required
explicit_wait int

Optional explicit wait time (seconds).

None

Raises:

Type Description
ValueError

If an invalid locator string is provided.

Exception

If an error occurs while clicking the element.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def click(self, locator: str, explicit_wait: int = None) -> None:
    """Clicks on a mobile element.

    Args:
        locator: Locator string in the format "strategy=value".
        explicit_wait: Optional explicit wait time (seconds).

    Raises:
        ValueError: If an invalid locator string is provided.
        Exception: If an error occurs while clicking the element.
    """
    try:
        element = self.get_clickable_mobile_element(locator, explicit_wait)
        element.click()
    except Exception as e:
        self.logger.exception("Error clicking element: %s. Error: %s", locator, e)
        raise e

get_clickable_mobile_element(locator, explicit_wait=None)

Waits for an element to be clickable and returns it.

Parameters:

Name Type Description Default
locator Union[str, WebElement]

Locator string in the format "strategy=value" or a WebElement object.

required
explicit_wait int

Optional explicit wait time (seconds).

None

Returns:

Type Description
WebElement

The clickable WebElement.

Raises:

Type Description
ValueError

If an invalid locator string is provided.

TypeError

If an invalid locator type is provided.

TimeoutException

If the element is not clickable within the explicit wait time.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
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
def get_clickable_mobile_element(
        self, locator: Union[str, WebElement], explicit_wait: int = None
) -> WebElement:
    """Waits for an element to be clickable and returns it.

    Args:
        locator: Locator string in the format "strategy=value" or a WebElement object.
        explicit_wait: Optional explicit wait time (seconds).

    Returns:
        The clickable WebElement.

    Raises:
        ValueError: If an invalid locator string is provided.
        TypeError: If an invalid locator type is provided.
        TimeoutException: If the element is not clickable within the explicit wait time.
    """
    try:
        explicit_wait = explicit_wait or self.default_explicit_wait

        if isinstance(locator, str):
            strategy, value = self._parse_locator(locator)
            return WebDriverWait(self.mobile_driver, explicit_wait).until(
                EC.element_to_be_clickable((strategy, value))
            )
        if isinstance(locator, WebElement):
            return locator

        raise TypeError("Invalid locator type. Must be a string or a WebElement.")
    except Exception as e:
        self.logger.exception("Error getting clickable element: %s. Error: %s", locator, e)
        raise e

get_driver_context()

Returns the current driver context (e.g., WEBVIEW, NATIVE).

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
43
44
45
46
47
48
49
50
51
52
def get_driver_context(self) -> str:
    """Returns the current driver context (e.g., WEBVIEW, NATIVE)."""
    try:
        return self.mobile_driver.current_context
    except Exception as e:
        error_description = f"Error getting driver context: {str(e)}"
        self.__exceptions_generic.raise_generic_exception(
            message=error_description, fail_test=False
        )
        return ""

get_page_url()

Returns the current URL of the webview context.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
91
92
93
94
95
96
97
def get_page_url(self) -> str:
    """Returns the current URL of the webview context."""
    try:
        return self.mobile_driver.current_url
    except Exception as e:
        self.logger.exception("Error getting page URL: %s", e)
        raise e

get_web_element(locator, explicit_wait=None)

Locates and returns a mobile element.

Parameters:

Name Type Description Default
locator Union[str, WebElement]

Locator string in the format "strategy=value" or a WebElement object.

required
explicit_wait int

Optional explicit wait time (seconds).

None

Returns:

Type Description
WebElement

The located WebElement.

Raises:

Type Description
ValueError

If an invalid locator string is provided.

TypeError

If an invalid locator type is provided.

TimeoutException

If the element is not found within the explicit wait time.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
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
def get_web_element(
        self, locator: Union[str, WebElement], explicit_wait: int = None
) -> WebElement:
    """Locates and returns a mobile element.

    Args:
        locator: Locator string in the format "strategy=value" or a WebElement object.
        explicit_wait: Optional explicit wait time (seconds).

    Returns:
        The located WebElement.

    Raises:
        ValueError: If an invalid locator string is provided.
        TypeError: If an invalid locator type is provided.
        TimeoutException: If the element is not found within the explicit wait time.
    """
    try:
        explicit_wait = explicit_wait or self.default_explicit_wait

        if isinstance(locator, str):
            strategy, value = self._parse_locator(locator)
            return WebDriverWait(self.mobile_driver, explicit_wait).until(
                EC.presence_of_element_located((strategy, value))
            )
        if isinstance(locator, WebElement):
            return locator

        raise TypeError("Invalid locator type. Must be a string or a WebElement.")
    except Exception as e:
        self.logger.exception("Error locating element: %s. Error: %s", locator, e)
        raise e

is_element_displayed(locator, explicit_wait=None)

Verifies if an element is displayed on the screen.

Parameters:

Name Type Description Default
locator Union[str, WebElement]

Locator string in the format "strategy=value" (e.g., "id=my_element" or "xpath=//button[@name='submit']") or a WebElement object.

required
explicit_wait int

Optional explicit wait time (in seconds). Defaults to the configured default explicit wait.

None

Returns:

Type Description
bool

True if the element is displayed, False otherwise.

Raises:

Type Description
ValueError

If an invalid locator string is provided.

TypeError

If an invalid locator type is provided.

Exception

If any other error occurs while checking element visibility.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
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
def is_element_displayed(
        self, locator: Union[str, WebElement], explicit_wait: int = None
) -> bool:
    """Verifies if an element is displayed on the screen.

    Args:
        locator: Locator string in the format "strategy=value"
                 (e.g., "id=my_element" or "xpath=//button[@name='submit']")
                 or a WebElement object.
        explicit_wait:  Optional explicit wait time (in seconds).
                       Defaults to the configured default explicit wait.

    Returns:
        True if the element is displayed, False otherwise.

    Raises:
        ValueError: If an invalid locator string is provided.
        TypeError: If an invalid locator type is provided.
        Exception: If any other error occurs while checking element visibility.
    """
    try:
        explicit_wait = explicit_wait or self.default_explicit_wait

        if isinstance(locator, str):
            strategy, value = self._parse_locator(locator)

            element = WebDriverWait(self.mobile_driver, explicit_wait).until(
                EC.visibility_of_element_located((strategy, value))
            )
            return bool(element)
        if isinstance(locator, WebElement):
            return locator.is_displayed()

        raise TypeError("Invalid locator type. Must be a string or a WebElement.")

    except Exception as e:
        error_description = f"Error checking visibility of element: '{locator}': {str(e)}"
        self.__exceptions_generic.raise_generic_exception(
            message=error_description, trim_log=True, fail_test=False
        )
        return False

is_element_present(locator, explicit_wait=None)

Checks if an element is present in the DOM.

Parameters:

Name Type Description Default
locator Union[str, WebElement]

Locator string in the format "strategy=value" or a WebElement object.

required
explicit_wait int

Optional explicit wait time (seconds).

None

Returns:

Type Description
bool

True if the element is present, False otherwise.

Raises:

Type Description
ValueError

If an invalid locator string is provided.

TypeError

If an invalid locator type is provided.

Exception

If an error occurs while checking element presence.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
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
def is_element_present(
        self, locator: Union[str, WebElement], explicit_wait: int = None
) -> bool:
    """Checks if an element is present in the DOM.

    Args:
        locator: Locator string in the format "strategy=value" or a WebElement object.
        explicit_wait: Optional explicit wait time (seconds).

    Returns:
        True if the element is present, False otherwise.

    Raises:
        ValueError: If an invalid locator string is provided.
        TypeError: If an invalid locator type is provided.
        Exception: If an error occurs while checking element presence.
    """
    try:
        explicit_wait = explicit_wait or self.default_explicit_wait

        if isinstance(locator, str):
            strategy, value = self._parse_locator(locator)
            element = WebDriverWait(self.mobile_driver, explicit_wait).until(
                EC.presence_of_element_located((strategy, value))
            )
            return bool(element)
        if isinstance(locator, WebElement):
            return True  # A WebElement object is always considered present

        raise TypeError("Invalid locator type. Must be a string or a WebElement.")
    except Exception as e:
        self.logger.exception("Error checking presence of element: %s. Error: %s", locator, e)
        raise e

Opens a deep link in the mobile app.

Parameters:

Name Type Description Default
link str

The deep link URL.

required
Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
79
80
81
82
83
84
85
86
87
88
89
def open_deep_link(self, link: str) -> None:
    """Opens a deep link in the mobile app.

    Args:
        link: The deep link URL.
    """
    try:
        self.mobile_driver.get(link)
    except Exception as e:
        self.logger.exception("Error opening deep link '%s': %s", link, e)
        raise e

scroll_mobile(direction, find_locator, explicit_wait=None, max_swipes=10)

Scrolls horizontally or vertically to find an element.

Parameters:

Name Type Description Default
direction str

Scroll direction ('down', 'up', 'right', 'left').

required
find_locator str

Locator string of the element to find.

required
explicit_wait int

Optional explicit wait time (seconds).

None
max_swipes int

Maximum number of swipes to attempt.

10

Returns:

Type Description
bool

True if the element is found, False otherwise.

Raises:

Type Description
Exception

If an error occurs during scrolling.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
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
def scroll_mobile(
        self, direction: str, find_locator: str, explicit_wait: int = None, max_swipes: int = 10
) -> bool:
    """Scrolls horizontally or vertically to find an element.

    Args:
        direction: Scroll direction ('down', 'up', 'right', 'left').
        find_locator: Locator string of the element to find.
        explicit_wait: Optional explicit wait time (seconds).
        max_swipes: Maximum number of swipes to attempt.

    Returns:
        True if the element is found, False otherwise.

    Raises:
        Exception: If an error occurs during scrolling.
    """
    try:
        explicit_wait = explicit_wait or self.default_explicit_wait

        if self.is_element_displayed(find_locator, explicit_wait):
            return True

        size = self.mobile_driver.get_window_size()
        for _ in range(max_swipes):
            if direction == "down":
                self.mobile_driver.swipe(
                    size["width"] * 0.20,
                    size["height"] * 0.80,
                    size["width"] * 0.20,
                    size["height"] * 0.20,
                    3000,
                )
            elif direction == "up":
                self.mobile_driver.swipe(
                    size["width"] * 0.20,
                    size["height"] * 0.20,
                    size["width"] * 0.20,
                    size["height"] * 0.80,
                    3000,
                )
            elif direction == "right":
                self.mobile_driver.swipe(
                    size["width"] * 0.80,
                    size["height"] * 0.50,
                    size["width"] * 0.20,
                    size["height"] * 0.50,
                    3000,
                )
            elif direction == "left":
                self.mobile_driver.swipe(
                    size["width"] * 0.20,
                    size["height"] * 0.50,
                    size["width"] * 0.80,
                    size["height"] * 0.50,
                    3000,
                )

            if self.is_element_displayed(find_locator, explicit_wait):
                return True

        return False

    except Exception as e:
        self.logger.exception("Exception in scroll_mobile method. Exception Details: %s", e)
        raise e

switch_driver_context(context)

Switches the driver context to 'WEBVIEW' or 'NATIVE'.

Parameters:

Name Type Description Default
context str

The desired context ('WEBVIEW' or 'NATIVE').

required

Returns:

Type Description
bool

True if the context switch was successful, False otherwise.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def switch_driver_context(self, context: str) -> bool:
    """Switches the driver context to 'WEBVIEW' or 'NATIVE'.

    Args:
        context: The desired context ('WEBVIEW' or 'NATIVE').

    Returns:
        True if the context switch was successful, False otherwise.
    """
    try:
        context = context.lower()
        if context == "webview":
            self.mobile_driver.switch_to.context(self.mobile_driver.contexts[1])
            return True
        if context == "native":
            self.mobile_driver.switch_to.context(self.mobile_driver.contexts[0])
            return True
        return False  # If context is not webview or native
    except Exception as e:
        error_description = f"Error switching driver context to '{context}': {str(e)}"
        self.__exceptions_generic.raise_generic_exception(
            message=error_description, fail_test=False
        )
        return False

terminate_mobile_app(package)

Terminates the mobile app specified by the package name or bundle ID.

Parameters:

Name Type Description Default
package str

The Android package name or iOS bundle ID of the app.

required

Raises:

Type Description
Exception

If an error occurs during app termination.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def terminate_mobile_app(self, package: str) -> None:
    """Terminates the mobile app specified by the package name or bundle
    ID.

    Args:
        package:  The Android package name or iOS bundle ID of the app.

    Raises:
        Exception: If an error occurs during app termination.
    """
    try:
        self.mobile_driver.terminate_app(package)
    except Exception as e:
        self.logger.exception("Error terminating mobile app '%s': %s", package, e)
        raise e

type(locator, text, explicit_wait=None, clear=False, click_before_type=True)

Types text into a mobile element.

Parameters:

Name Type Description Default
locator str

Locator string in the format "strategy=value".

required
text str

The text to type.

required
explicit_wait int

Optional explicit wait time (seconds).

None
clear bool

If True, clears the element before typing.

False
click_before_type bool

If True, clicks the element before typing.

True

Raises:

Type Description
ValueError

If an invalid locator string is provided.

Exception

If an error occurs while typing.

Source code in libs\cafex_ui\src\cafex_ui\mobile_client\mobile_client_actions.py
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
def type(
        self,
        locator: str,
        text: str,
        explicit_wait: int = None,
        clear: bool = False,
        click_before_type: bool = True,
) -> None:
    """Types text into a mobile element.

    Args:
        locator: Locator string in the format "strategy=value".
        text: The text to type.
        explicit_wait: Optional explicit wait time (seconds).
        clear: If True, clears the element before typing.
        click_before_type: If True, clicks the element before typing.

    Raises:
        ValueError: If an invalid locator string is provided.
        Exception: If an error occurs while typing.
    """
    try:
        element = self.get_clickable_mobile_element(locator, explicit_wait)
        if click_before_type:
            element.click()
        if clear:
            element.clear()
        element.send_keys(text)
    except Exception as e:
        self.logger.exception(
            "Error typing text '%s' into element: %s. Error: %s", text, locator, e
        )
        raise e