pumapy 4.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- puma/__init__.py +45 -0
- puma/apps/__init__.py +0 -0
- puma/apps/android/__init__.py +14 -0
- puma/apps/android/appium_actions.py +219 -0
- puma/apps/android/google_camera/__init__.py +3 -0
- puma/apps/android/google_camera/google_camera.py +111 -0
- puma/apps/android/google_chrome/__init__.py +3 -0
- puma/apps/android/google_chrome/google_chrome.py +145 -0
- puma/apps/android/google_chrome/states.py +93 -0
- puma/apps/android/google_chrome/xpaths.py +37 -0
- puma/apps/android/google_maps/__init__.py +0 -0
- puma/apps/android/google_maps/google_maps.py +87 -0
- puma/apps/android/google_play_store/__init__.py +3 -0
- puma/apps/android/google_play_store/google_play_store.py +215 -0
- puma/apps/android/open_camera/__init__.py +3 -0
- puma/apps/android/open_camera/open_camera.py +106 -0
- puma/apps/android/snapchat/__init__.py +0 -0
- puma/apps/android/snapchat/snapchat.py +149 -0
- puma/apps/android/snapchat/xpaths.py +21 -0
- puma/apps/android/telegram/__init__.py +3 -0
- puma/apps/android/telegram/telegram.py +405 -0
- puma/apps/android/telegram/xpaths.py +70 -0
- puma/apps/android/teleguard/__init__.py +3 -0
- puma/apps/android/teleguard/teleguard.py +143 -0
- puma/apps/android/whatsapp/__init__.py +3 -0
- puma/apps/android/whatsapp/states.py +148 -0
- puma/apps/android/whatsapp/whatsapp.py +657 -0
- puma/apps/android/whatsapp/xpaths.py +165 -0
- puma/apps/android/whatsapp_business/__init__.py +0 -0
- puma/apps/android/whatsapp_business/whatsapp_business.py +87 -0
- puma/apps/android/whatsapp_business/whatsapp_common.py +637 -0
- puma/computer_vision/__init__.py +3 -0
- puma/computer_vision/ocr.py +77 -0
- puma/state_graph/__init__.py +3 -0
- puma/state_graph/action.py +137 -0
- puma/state_graph/app_template.py +32 -0
- puma/state_graph/popup_handler.py +55 -0
- puma/state_graph/puma_driver.py +452 -0
- puma/state_graph/state.py +189 -0
- puma/state_graph/state_graph.py +309 -0
- puma/state_graph/utils.py +40 -0
- puma/utils/__init__.py +40 -0
- puma/utils/debug.py +18 -0
- puma/utils/gtl_logging.py +27 -0
- puma/utils/route_simulator.py +251 -0
- puma/utils/video_utils.py +79 -0
- puma/utils/xpath_utils.py +35 -0
- puma/version.py +1 -0
- pumapy-4.0.1.dist-info/METADATA +394 -0
- pumapy-4.0.1.dist-info/RECORD +53 -0
- pumapy-4.0.1.dist-info/WHEEL +5 -0
- pumapy-4.0.1.dist-info/licenses/LICENSE.txt +287 -0
- pumapy-4.0.1.dist-info/top_level.txt +1 -0
puma/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from puma.utils import configure_default_logging
|
|
5
|
+
|
|
6
|
+
MAIN_MODULE = sys.modules.get('__main__')
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _pattern_in_main(pattern):
|
|
10
|
+
if hasattr(MAIN_MODULE, '__file__'):
|
|
11
|
+
return MAIN_MODULE and pattern in MAIN_MODULE.__file__
|
|
12
|
+
return False
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _is_running_as_main() -> bool:
|
|
16
|
+
"""
|
|
17
|
+
Returns True if this package is being run as the main module
|
|
18
|
+
via `python -m puma`.
|
|
19
|
+
"""
|
|
20
|
+
return _pattern_in_main('puma/apps')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _is_running_as_test() -> bool:
|
|
24
|
+
return _pattern_in_main('unittest_runner')
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _is_running_in_jupyter_notebook():
|
|
28
|
+
if MAIN_MODULE is not None:
|
|
29
|
+
if not hasattr(MAIN_MODULE, '__file__'):
|
|
30
|
+
return True
|
|
31
|
+
if 'ipykernel' in str(type(MAIN_MODULE)):
|
|
32
|
+
return True
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# Only configure logging when Puma is not run from another application
|
|
37
|
+
if (
|
|
38
|
+
_is_running_as_main() or
|
|
39
|
+
_is_running_as_test() or
|
|
40
|
+
_is_running_in_jupyter_notebook()
|
|
41
|
+
):
|
|
42
|
+
configure_default_logging()
|
|
43
|
+
else:
|
|
44
|
+
logger = logging.getLogger("puma")
|
|
45
|
+
logger.addHandler(logging.NullHandler())
|
puma/apps/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import logging
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
|
|
5
|
+
logger = logging.getLogger(__name__)
|
|
6
|
+
|
|
7
|
+
def log_action(func):
|
|
8
|
+
@functools.wraps(func)
|
|
9
|
+
def wrapper(self, *args, **kwargs):
|
|
10
|
+
module_name = func.__module__
|
|
11
|
+
logger = logging.getLogger(module_name)
|
|
12
|
+
logger.info(f"Action {func.__name__} initiated")
|
|
13
|
+
return func(self, *args, **kwargs)
|
|
14
|
+
return wrapper
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import time
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Dict
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
from adb_pywrapper.adb_device import AdbDevice
|
|
9
|
+
from adb_pywrapper.adb_screen_recorder import AdbScreenRecorder
|
|
10
|
+
from appium.options.android import UiAutomator2Options
|
|
11
|
+
from appium.webdriver import WebElement
|
|
12
|
+
from appium.webdriver.common.appiumby import AppiumBy
|
|
13
|
+
from appium.webdriver.extensions.android.nativekey import AndroidKey
|
|
14
|
+
from appium.webdriver.webdriver import WebDriver
|
|
15
|
+
from selenium.common import NoSuchElementException
|
|
16
|
+
from typing_extensions import deprecated
|
|
17
|
+
|
|
18
|
+
from puma.apps.android import logger
|
|
19
|
+
from puma.computer_vision import ocr
|
|
20
|
+
from puma.state_graph.puma_driver import _get_appium_driver
|
|
21
|
+
from puma.utils.video_utils import CACHE_FOLDER, log_error_and_raise_exception
|
|
22
|
+
|
|
23
|
+
__drivers: dict[str, WebDriver] = {}
|
|
24
|
+
|
|
25
|
+
def _get_android_default_options():
|
|
26
|
+
options = UiAutomator2Options()
|
|
27
|
+
options.no_reset = True
|
|
28
|
+
options.platform_name = 'Android'
|
|
29
|
+
options.new_command_timeout = 1200
|
|
30
|
+
return options
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def supported_version(version: str):
|
|
34
|
+
def decorator(class_or_function):
|
|
35
|
+
class_or_function.supported_version = version
|
|
36
|
+
return class_or_function
|
|
37
|
+
|
|
38
|
+
return decorator
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@deprecated('AndroidAppiumActions is deprecated since Puma version 3.0.0. Use the StateGraph instead.')
|
|
42
|
+
class AndroidAppiumActions:
|
|
43
|
+
|
|
44
|
+
def __init__(self,
|
|
45
|
+
udid: str,
|
|
46
|
+
app_package: str,
|
|
47
|
+
desired_capabilities: Dict[str, str] = None,
|
|
48
|
+
implicit_wait: int = 1,
|
|
49
|
+
appium_server: str = 'http://localhost:4723'):
|
|
50
|
+
"""
|
|
51
|
+
Class with a generic API for Appium scripting on an Android device.
|
|
52
|
+
Can be used with an emulator or real device attached to the computer.
|
|
53
|
+
:param desired_capabilities: desired capabilities as passed to the Appium webdriver
|
|
54
|
+
:param implicit_wait: how long Appium will look for an element (you can look for an element before it is
|
|
55
|
+
rendered). Default 1 second
|
|
56
|
+
:param appium_server: url of the appium server
|
|
57
|
+
"""
|
|
58
|
+
# prepare options
|
|
59
|
+
self.options = _get_android_default_options()
|
|
60
|
+
self.options.udid = udid
|
|
61
|
+
self.app_package = app_package
|
|
62
|
+
if desired_capabilities:
|
|
63
|
+
self.options.load_capabilities(desired_capabilities)
|
|
64
|
+
|
|
65
|
+
logger.info("Connecting to Appium driver...")
|
|
66
|
+
self.driver = _get_appium_driver(appium_server, udid, self.options)
|
|
67
|
+
|
|
68
|
+
# the implicit wait time is how long appium looks for an element (you can try to find an element before it is rendered)
|
|
69
|
+
self.implicit_wait = implicit_wait
|
|
70
|
+
self.driver.implicitly_wait(implicit_wait)
|
|
71
|
+
self.udid = self.driver.capabilities.get("udid")
|
|
72
|
+
self.adb = AdbDevice(self.udid)
|
|
73
|
+
|
|
74
|
+
# screen recorder
|
|
75
|
+
self._screen_recorder = None
|
|
76
|
+
|
|
77
|
+
logger.info(f"Activating package {self.app_package}...")
|
|
78
|
+
self.activate_app()
|
|
79
|
+
logger.info(f"App package {self.app_package} activated!")
|
|
80
|
+
|
|
81
|
+
def activate_app(self):
|
|
82
|
+
self.driver.activate_app(self.app_package)
|
|
83
|
+
|
|
84
|
+
def terminate_app(self):
|
|
85
|
+
self.driver.terminate_app(self.app_package)
|
|
86
|
+
|
|
87
|
+
def restart_app(self):
|
|
88
|
+
self.terminate_app()
|
|
89
|
+
self.activate_app()
|
|
90
|
+
|
|
91
|
+
def app_open(self) -> bool:
|
|
92
|
+
return str(self.driver.current_package) == self.app_package
|
|
93
|
+
|
|
94
|
+
def __enter__(self):
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
98
|
+
if self._screen_recorder is not None:
|
|
99
|
+
self.stop_recording_and_save_video()
|
|
100
|
+
self.driver.__exit__(exc_type, exc_val, exc_tb)
|
|
101
|
+
|
|
102
|
+
def back(self):
|
|
103
|
+
self.driver.press_keycode(AndroidKey.BACK)
|
|
104
|
+
|
|
105
|
+
def home(self):
|
|
106
|
+
self.driver.press_keycode(AndroidKey.HOME)
|
|
107
|
+
|
|
108
|
+
def open_notifications(self):
|
|
109
|
+
self.driver.open_notifications()
|
|
110
|
+
|
|
111
|
+
def scroll_to_find_element(self, resource_id: str = None, text_equals: str = None,
|
|
112
|
+
text_contains: str = None) -> WebElement:
|
|
113
|
+
"""
|
|
114
|
+
This code will scroll in the current view until a certain element is found, and then return that element.
|
|
115
|
+
The element can be searched for by resource-id and/or the text in that element.
|
|
116
|
+
When defining the text of the element either an exact match or a textContains match can be used. These two can
|
|
117
|
+
of course not be used at the same time.
|
|
118
|
+
The method will keep scrolling until the element is found. If you look for something that doesn't exist you
|
|
119
|
+
will have a bad time.
|
|
120
|
+
The first matching element is returned when found.
|
|
121
|
+
:param resource_id: the resource id of the element to look for.
|
|
122
|
+
:param text_equals: the exact text of the element to look for. Cannot be used in combination with text_contains.
|
|
123
|
+
:param text_contains: part of the text of the element to look for. Cannot be used in combination with
|
|
124
|
+
text_equals.
|
|
125
|
+
:return: The element when found.
|
|
126
|
+
"""
|
|
127
|
+
if text_equals is not None and text_contains is not None:
|
|
128
|
+
raise ValueError('text_equals and text_contains can not be used at the same time')
|
|
129
|
+
if resource_id is None and text_contains is None and text_equals is None:
|
|
130
|
+
raise ValueError('resource_id, text_equals and text_contains cannot all be None')
|
|
131
|
+
|
|
132
|
+
resource_id_part = '' if resource_id is None else f'.resourceIdMatches("{resource_id}")'
|
|
133
|
+
text_part = '' if text_equals is None else f'.text("{text_equals}")'
|
|
134
|
+
text_contains_part = '' if text_contains is None else f'.textContains("{text_contains}")'
|
|
135
|
+
|
|
136
|
+
java_code = f'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector(){resource_id_part}{text_part}{text_contains_part}.instance(0))'
|
|
137
|
+
return self.driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value=java_code)
|
|
138
|
+
|
|
139
|
+
def swipe_to_find_element(self, xpath: str, max_swipes: int = 10) -> WebElement:
|
|
140
|
+
for attempt in range(max_swipes):
|
|
141
|
+
if self.is_present(xpath):
|
|
142
|
+
return self.driver.find_element(AppiumBy.XPATH, xpath)
|
|
143
|
+
else:
|
|
144
|
+
# Element not found, perform swipe down
|
|
145
|
+
print(f"Attempt {attempt + 1}: Element not found, swiping down")
|
|
146
|
+
# Get the window size to determine the swipe dimensions
|
|
147
|
+
window_size = self.driver.get_window_size()
|
|
148
|
+
start_x = window_size['width'] / 2
|
|
149
|
+
start_y = window_size['height'] * 0.8
|
|
150
|
+
end_y = window_size['height'] * 0.2
|
|
151
|
+
|
|
152
|
+
# Perform the swipe down
|
|
153
|
+
self.driver.swipe(start_x, start_y, start_x, end_y, 500)
|
|
154
|
+
|
|
155
|
+
# Wait a bit before the next attempt
|
|
156
|
+
time.sleep(0.5)
|
|
157
|
+
|
|
158
|
+
# If the loop completes, the element was not found
|
|
159
|
+
raise NoSuchElementException(msg=f'After {max_swipes} swipes, cannot find element with xpath {xpath}')
|
|
160
|
+
|
|
161
|
+
def is_present(self, xpath: str, implicit_wait: int = 0) -> bool:
|
|
162
|
+
self.driver.implicitly_wait(implicit_wait)
|
|
163
|
+
found = self.driver.find_elements(by=AppiumBy.XPATH, value=xpath)
|
|
164
|
+
self.driver.implicitly_wait(self.implicit_wait)
|
|
165
|
+
return len(found) > 0
|
|
166
|
+
|
|
167
|
+
def start_recording(self, output_directory: str):
|
|
168
|
+
if self._screen_recorder is None:
|
|
169
|
+
self._screen_recorder_output_directory = output_directory
|
|
170
|
+
self._screen_recorder = AdbScreenRecorder(self.adb)
|
|
171
|
+
self._screen_recorder.start_recording()
|
|
172
|
+
|
|
173
|
+
def stop_recording_and_save_video(self) -> [str]:
|
|
174
|
+
if self._screen_recorder is None:
|
|
175
|
+
return None
|
|
176
|
+
video_files = self._screen_recorder.stop_recording(self._screen_recorder_output_directory)
|
|
177
|
+
self._screen_recorder.__exit__(None, None, None)
|
|
178
|
+
self._screen_recorder = None
|
|
179
|
+
return video_files
|
|
180
|
+
|
|
181
|
+
def new_screenshot_name(self):
|
|
182
|
+
now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
183
|
+
device_name = self.options.device_name
|
|
184
|
+
return Path(CACHE_FOLDER) / f'{now}-{device_name}-{uuid4()}.png'
|
|
185
|
+
|
|
186
|
+
def find_text_ocr(self, text_to_find: str) -> [ocr.RecognizedText]:
|
|
187
|
+
path = self.new_screenshot_name()
|
|
188
|
+
screenshot_taken = False
|
|
189
|
+
try:
|
|
190
|
+
screenshot_taken = self.driver.get_screenshot_as_file(path)
|
|
191
|
+
if not screenshot_taken:
|
|
192
|
+
raise Exception(f'Screenshot could not be stored to {path}')
|
|
193
|
+
found_text = ocr.find_text(str(path), text_to_find)
|
|
194
|
+
return found_text
|
|
195
|
+
finally:
|
|
196
|
+
if screenshot_taken:
|
|
197
|
+
os.remove(path)
|
|
198
|
+
|
|
199
|
+
def click_text_ocr(self, text_to_click: str, click_first_when_multiple: bool = False):
|
|
200
|
+
found_text = self.find_text_ocr(text_to_click)
|
|
201
|
+
if len(found_text) == 0:
|
|
202
|
+
msg = f'Could not find text {text_to_click} on screen so could not click it'
|
|
203
|
+
log_error_and_raise_exception(logger, msg)
|
|
204
|
+
if len(found_text) > 1:
|
|
205
|
+
msg = f'Found multiple occurrences of text {text_to_click} on screen so could not determine what to click'
|
|
206
|
+
if not click_first_when_multiple:
|
|
207
|
+
log_error_and_raise_exception(logger, msg)
|
|
208
|
+
else:
|
|
209
|
+
logger.warning(f'Found multiple occurrences of text {text_to_click} on screen, clicking first one')
|
|
210
|
+
x = found_text[0].bounding_box.middle[0]
|
|
211
|
+
y = found_text[0].bounding_box.middle[1]
|
|
212
|
+
self.driver.execute_script('mobile: clickGesture', {'x': x, 'y': y})
|
|
213
|
+
|
|
214
|
+
def set_idle_timeout(self, timeout: int):
|
|
215
|
+
# https://github.com/appium/appium-uiautomator2-driver#poor-elements-interaction-performance
|
|
216
|
+
# https://github.com/appium/appium-uiautomator2-driver#settings-api
|
|
217
|
+
settings = self.driver.get_settings()
|
|
218
|
+
settings.update({"waitForIdleTimeout": timeout})
|
|
219
|
+
self.driver.update_settings(settings)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from time import sleep
|
|
2
|
+
|
|
3
|
+
from puma.state_graph.action import action
|
|
4
|
+
from puma.state_graph.popup_handler import PopUpHandler
|
|
5
|
+
from puma.state_graph.puma_driver import supported_version
|
|
6
|
+
from puma.state_graph.state_graph import StateGraph
|
|
7
|
+
from puma.state_graph.state import SimpleState, compose_clicks
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
PHOTO_STATE_TAKE_PHOTO = '//android.widget.ImageButton[@content-desc="Take photo"]'
|
|
11
|
+
PHOTO_STATE_CAMERA = '//android.widget.TextView[@content-desc="Camera"]'
|
|
12
|
+
PHOTO_STATE_SWITCH_TO_VIDEO = '//android.widget.TextView[@content-desc="Switch to Video Camera"]'
|
|
13
|
+
PHOTO_STATE_SHUTTER_BUTTON = '//android.widget.ImageButton[@resource-id="com.google.android.GoogleCamera:id/shutter_button"]'
|
|
14
|
+
|
|
15
|
+
VIDEO_STATE_VIDEO = '//android.widget.TextView[@content-desc="Video"]'
|
|
16
|
+
VIDEO_STATE_TAKE_VIDEO = '//android.widget.ImageButton[@content-desc="Start video"]'
|
|
17
|
+
VIDEO_STATE_SWITCH_TO_PHOTO = '//android.widget.TextView[@content-desc="Switch to Camera Mode"]'
|
|
18
|
+
VIDEO_STATE_STOP_VIDEO = '//android.widget.ImageButton[@content-desc="Stop video"]'
|
|
19
|
+
|
|
20
|
+
SWITCH_CAMERA_BUTTON = '//android.widget.ImageButton[@resource-id="com.google.android.GoogleCamera:id/camera_switch_button"]'
|
|
21
|
+
|
|
22
|
+
SETTINGS_STATE_CAMERA_SETTINGS = '//android.widget.TextView[@text="Camera settings"]'
|
|
23
|
+
SETTINGS_STATE_TITLE = '//android.widget.TextView[@resource-id="android:id/title" and @text="General"]'
|
|
24
|
+
|
|
25
|
+
OPEN_OPTIONS_MENU = '//android.widget.ImageView[@content-desc="Open options menu"]'
|
|
26
|
+
OPEN_SETTINGS = '//android.widget.Button[@content-desc="Open settings"]'
|
|
27
|
+
|
|
28
|
+
POPUP_TURN_ON_BY_DEFAULT = '//android.widget.TextView[@text="Turned on by default"]'
|
|
29
|
+
POPUP_BOTTOMSHEET = '//android.widget.LinearLayout[@resource-id="com.google.android.GoogleCamera:id/bottomsheet_container"]'
|
|
30
|
+
POPUP_GOT_IT = '//android.widget.Button[@resource-id="com.google.android.GoogleCamera:id/got_it_button"]'
|
|
31
|
+
DONE = '//android.widget.Button[@text="Done"]'
|
|
32
|
+
|
|
33
|
+
APPLICATION_PACKAGE = 'com.google.android.GoogleCamera'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@supported_version("8.8.225.510547499.09")
|
|
37
|
+
class GoogleCamera(StateGraph):
|
|
38
|
+
"""
|
|
39
|
+
A class representing a state graph for managing UI states and transitions in the Google Camera application.
|
|
40
|
+
|
|
41
|
+
This class uses a state machine approach to manage transitions between different states
|
|
42
|
+
of the Google Camera user interface. It provides methods to navigate between states,
|
|
43
|
+
take pictures, and record videos.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
# Define states
|
|
47
|
+
photo = SimpleState(xpaths=[PHOTO_STATE_TAKE_PHOTO,
|
|
48
|
+
PHOTO_STATE_CAMERA],
|
|
49
|
+
initial_state=True)
|
|
50
|
+
video = SimpleState(xpaths=[VIDEO_STATE_VIDEO,
|
|
51
|
+
VIDEO_STATE_TAKE_VIDEO])
|
|
52
|
+
settings = SimpleState(xpaths=[SETTINGS_STATE_CAMERA_SETTINGS,
|
|
53
|
+
SETTINGS_STATE_TITLE],
|
|
54
|
+
parent_state=photo) # note that settings does not have a real parent state. the back restores the last state before navigating to settings.
|
|
55
|
+
|
|
56
|
+
# Define transitions. Only forward transitions are needed, back transitions are added automatically
|
|
57
|
+
photo.to(video, compose_clicks([PHOTO_STATE_SWITCH_TO_VIDEO], name='go_to_video'))
|
|
58
|
+
video.to(photo, compose_clicks([VIDEO_STATE_SWITCH_TO_PHOTO], name='go_to_camera'))
|
|
59
|
+
go_to_settings = compose_clicks([OPEN_OPTIONS_MENU, OPEN_SETTINGS], name= 'go_to_settings')
|
|
60
|
+
photo.to(settings, go_to_settings)
|
|
61
|
+
video.to(settings, go_to_settings)
|
|
62
|
+
|
|
63
|
+
def __init__(self, device_udid):
|
|
64
|
+
"""
|
|
65
|
+
Initializes the GoogleCamera with a device UDID.
|
|
66
|
+
|
|
67
|
+
:param device_udid: The unique device identifier for the Android device.
|
|
68
|
+
"""
|
|
69
|
+
StateGraph.__init__(self, device_udid, APPLICATION_PACKAGE)
|
|
70
|
+
self.add_popup_handler(PopUpHandler([POPUP_TURN_ON_BY_DEFAULT], [DONE]))
|
|
71
|
+
self.add_popup_handler(PopUpHandler([POPUP_BOTTOMSHEET], [POPUP_GOT_IT]))
|
|
72
|
+
|
|
73
|
+
@action(photo)
|
|
74
|
+
def take_picture(self, front_camera: bool = None):
|
|
75
|
+
"""
|
|
76
|
+
Takes a single picture.
|
|
77
|
+
|
|
78
|
+
This method ensures the correct camera view (front or back) and then takes a picture.
|
|
79
|
+
|
|
80
|
+
:param front_camera: If True, uses the front camera; if False, uses the back camera; if None, no change is made.
|
|
81
|
+
"""
|
|
82
|
+
self._ensure_correct_camera_view(front_camera)
|
|
83
|
+
self.driver.click(PHOTO_STATE_SHUTTER_BUTTON)
|
|
84
|
+
|
|
85
|
+
@action(video)
|
|
86
|
+
def record_video(self, duration, front_camera: bool = None):
|
|
87
|
+
"""
|
|
88
|
+
Records a video for the given duration.
|
|
89
|
+
|
|
90
|
+
This method ensures the correct camera view (front or back) and then starts and stops video recording.
|
|
91
|
+
|
|
92
|
+
:param duration: The duration in seconds to record the video.
|
|
93
|
+
:param front_camera: If True, uses the front camera; if False, uses the back camera; if None, no change is made.
|
|
94
|
+
"""
|
|
95
|
+
self._ensure_correct_camera_view(front_camera)
|
|
96
|
+
self.driver.click(VIDEO_STATE_TAKE_VIDEO)
|
|
97
|
+
sleep(duration)
|
|
98
|
+
self.driver.click(VIDEO_STATE_STOP_VIDEO)
|
|
99
|
+
|
|
100
|
+
def _ensure_correct_camera_view(self, front_camera):
|
|
101
|
+
"""
|
|
102
|
+
Ensures the correct camera view (front or back) is selected.
|
|
103
|
+
|
|
104
|
+
:param front_camera: If True, ensures the front camera is selected; if False, ensures the back camera is selected.
|
|
105
|
+
"""
|
|
106
|
+
if front_camera is None:
|
|
107
|
+
return
|
|
108
|
+
switch_button = self.driver.get_element(SWITCH_CAMERA_BUTTON)
|
|
109
|
+
currently_in_front = 'front' not in switch_button.get_attribute("content-desc")
|
|
110
|
+
if currently_in_front != front_camera:
|
|
111
|
+
switch_button.click()
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
from time import sleep
|
|
2
|
+
|
|
3
|
+
from puma.apps.android.appium_actions import supported_version
|
|
4
|
+
from puma.apps.android.google_chrome import logger
|
|
5
|
+
from puma.apps.android.google_chrome.states import BookmarksFolder, CurrentTab
|
|
6
|
+
from puma.apps.android.google_chrome.xpaths import *
|
|
7
|
+
from puma.state_graph.action import action
|
|
8
|
+
from puma.state_graph.popup_handler import PopUpHandler
|
|
9
|
+
from puma.state_graph.state import SimpleState, compose_clicks
|
|
10
|
+
from puma.state_graph.state_graph import StateGraph
|
|
11
|
+
|
|
12
|
+
GOOGLE_CHROME_PACKAGE = 'com.android.chrome'
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@supported_version("141.0.7390.111")
|
|
16
|
+
class GoogleChrome(StateGraph):
|
|
17
|
+
"""
|
|
18
|
+
A class representing the Google Chrome application on Android devices.
|
|
19
|
+
|
|
20
|
+
The Google Chrome browser application does not really fit the parent-child relationship of states well, as most
|
|
21
|
+
states can be reached from most other states. However, to keep to the structure of the StateGraph, we have chosen
|
|
22
|
+
the tab overview as the parent state of most states, as it is the most neutral state from which other states can be
|
|
23
|
+
reached. Moreover, for simplicity, we have not implemented all possible transitions between states.
|
|
24
|
+
"""
|
|
25
|
+
# States
|
|
26
|
+
tab_overview_state = SimpleState(xpaths=[TAB_LIST, SEARCH_TABS])
|
|
27
|
+
incognito_tab_overview_state = SimpleState(xpaths=[TAB_LIST, SEARCH_INCOGNITO_TABS],
|
|
28
|
+
parent_state=tab_overview_state,
|
|
29
|
+
parent_state_transition=compose_clicks([STANDARD_TAB_OVERVIEW_BUTTON], 'go_to_tab_overview'))
|
|
30
|
+
new_tab_state = SimpleState(xpaths=[SEARCH_BOX, SEARCH_BOX_ENGINE_ICON],
|
|
31
|
+
initial_state=True,
|
|
32
|
+
parent_state=tab_overview_state,
|
|
33
|
+
parent_state_transition=compose_clicks([TAB_SWITCH_BUTTON],'go_to_tab_overview'))
|
|
34
|
+
current_tab_state = CurrentTab(parent_state=tab_overview_state)
|
|
35
|
+
new_incognito_tab_state = SimpleState(xpaths=[URL_BAR, NEW_TAB_INCOGNITO_TITLE],
|
|
36
|
+
parent_state=incognito_tab_overview_state,
|
|
37
|
+
parent_state_transition=compose_clicks([TAB_SWITCH_BUTTON], 'go_to_incognito_tab_overview'))
|
|
38
|
+
bookmarks_state = SimpleState(xpaths=[BOOKMARKS_SORT_VIEW, BOOKMARKS_CREATE_FOLDER, BOOKMARKS_PAGE_TITLE],
|
|
39
|
+
parent_state=current_tab_state,
|
|
40
|
+
parent_state_transition=compose_clicks([CLOSE_BOOKMARKS], 'go_to_current_tab'))
|
|
41
|
+
bookmarks_folder_state = BookmarksFolder(parent_state=bookmarks_state)
|
|
42
|
+
# Transitions
|
|
43
|
+
tab_overview_state.to(new_tab_state, compose_clicks([NEW_TAB_XPATH_TAB_OVERVIEW], 'go_to_tab_overview'))
|
|
44
|
+
tab_overview_state.to(current_tab_state, current_tab_state.switch_to_tab)
|
|
45
|
+
tab_overview_state.to(new_incognito_tab_state,
|
|
46
|
+
compose_clicks([THREE_DOTS, NEW_INCOGNITO_TAB_BUTTON], 'go_to_incognito_state'))
|
|
47
|
+
current_tab_state.to(new_tab_state, compose_clicks([NEW_TAB_FROM_CURRENT_TAB], 'go_to_current_tab'))
|
|
48
|
+
current_tab_state.to(bookmarks_state, compose_clicks([THREE_DOTS, OPEN_BOOKMARKS], 'go_to_current_tab'))
|
|
49
|
+
bookmarks_state.to(bookmarks_folder_state, bookmarks_folder_state.go_to_bookmarks_folder)
|
|
50
|
+
|
|
51
|
+
def __init__(self, device_udid):
|
|
52
|
+
"""
|
|
53
|
+
Initializes Google Chrome with a device UDID.
|
|
54
|
+
|
|
55
|
+
:param device_udid: The unique device identifier for the Android device.
|
|
56
|
+
"""
|
|
57
|
+
StateGraph.__init__(self, device_udid, GOOGLE_CHROME_PACKAGE)
|
|
58
|
+
self.add_popup_handlers(PopUpHandler([NEW_ADS_PRIVACY_TEXT_XPATH], [ACK_BUTTON_XPATH]),
|
|
59
|
+
PopUpHandler([OTHER_ADS_PRIVACY_TEXT_XPATH], [MORE_BUTTON_XPATH, ACK_BUTTON_XPATH]),
|
|
60
|
+
PopUpHandler([TURN_ON_AD_PRIVACY_TEXT_XPATH], [ACK_BUTTON_XPATH]),
|
|
61
|
+
PopUpHandler([CHROME_NOTIFICATIONS_TEXT_XPATH], [NEGATIVE_BUTTON_XPATH]),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
@action(current_tab_state)
|
|
65
|
+
def visit_url(self, url_string: str, tab_index: int):
|
|
66
|
+
"""
|
|
67
|
+
Visits a url in an existing tab.
|
|
68
|
+
Note that if you supply a tab index that is a new tab, the action will fail. Use go_to_new_tab instead.
|
|
69
|
+
:param url_string: The argument to pass to the address bar
|
|
70
|
+
:param tab_index: which tab to open
|
|
71
|
+
"""
|
|
72
|
+
logger.warning(
|
|
73
|
+
"In Chrome version 141.0.7390.111, we have noticed clicking on a tab with index might not open the tab on "
|
|
74
|
+
"some devices. Hopefully this will be fixed in future Chrome versions.")
|
|
75
|
+
self._enter_url(url_string, URL_BAR)
|
|
76
|
+
|
|
77
|
+
@action(new_tab_state)
|
|
78
|
+
def visit_url_new_tab(self, url_string):
|
|
79
|
+
"""
|
|
80
|
+
Creates a new tab and visits the url.
|
|
81
|
+
:param url_string: Url to visit
|
|
82
|
+
"""
|
|
83
|
+
self.driver.send_keys(SEARCH_BOX, url_string)
|
|
84
|
+
self.driver.press_enter()
|
|
85
|
+
|
|
86
|
+
@action(new_incognito_tab_state)
|
|
87
|
+
def visit_url_incognito(self, url_string: str):
|
|
88
|
+
"""
|
|
89
|
+
Opens an incognito tab and enters the url_string to the address bar.
|
|
90
|
+
:param url_string: the input to pass to the address bar
|
|
91
|
+
"""
|
|
92
|
+
self._open_settings_pane()
|
|
93
|
+
self.driver.click(NEW_INCOGNITO_TAB_BUTTON)
|
|
94
|
+
self._enter_url(url_string, URL_BAR)
|
|
95
|
+
|
|
96
|
+
@action(current_tab_state)
|
|
97
|
+
def bookmark_page(self, tab_index: int):
|
|
98
|
+
"""
|
|
99
|
+
Bookmarks the current page.
|
|
100
|
+
:param tab_index: Index of the tab to bookmark.
|
|
101
|
+
:return: True if bookmark has been added, False if it already existed.
|
|
102
|
+
"""
|
|
103
|
+
self._open_settings_pane()
|
|
104
|
+
if self.driver.is_present(EDIT_BOOKMARK_BUTTON):
|
|
105
|
+
self.gtl_logger.info("This page was already bookmarked, skipping...")
|
|
106
|
+
return False
|
|
107
|
+
else:
|
|
108
|
+
self.driver.click(BOOKMARK_THIS_PAGE_BUTTON)
|
|
109
|
+
return True
|
|
110
|
+
|
|
111
|
+
@action(bookmarks_folder_state)
|
|
112
|
+
def load_first_bookmark(self, folder_name: str):
|
|
113
|
+
"""
|
|
114
|
+
Load the first saved bookmark in the specified folder.
|
|
115
|
+
:param folder_name: The name of the folder to load the first bookmark from.
|
|
116
|
+
"""
|
|
117
|
+
self.driver.click(FIRST_BOOKMARK)
|
|
118
|
+
|
|
119
|
+
@action(current_tab_state)
|
|
120
|
+
def delete_bookmark(self, tab_index: int):
|
|
121
|
+
"""
|
|
122
|
+
Delete the current bookmark.
|
|
123
|
+
:param tab_index: Index of the tab to delete the bookmark from.
|
|
124
|
+
:return: True if bookmark has been deleted, False if it wasn't bookmarked.
|
|
125
|
+
"""
|
|
126
|
+
self._open_settings_pane()
|
|
127
|
+
if self.driver.is_present(BOOKMARK_THIS_PAGE_BUTTON):
|
|
128
|
+
self.gtl_logger.info("This page was not bookmarked, skipping...")
|
|
129
|
+
return False
|
|
130
|
+
else:
|
|
131
|
+
self.driver.click(EDIT_BOOKMARK_BUTTON)
|
|
132
|
+
self.driver.click(DELETE_BOOKMARK)
|
|
133
|
+
return True
|
|
134
|
+
|
|
135
|
+
def _open_settings_pane(self):
|
|
136
|
+
"""
|
|
137
|
+
Opens the settings pane. Add a short sleep to ensure the page is actually opened.
|
|
138
|
+
"""
|
|
139
|
+
self.driver.click(THREE_DOTS)
|
|
140
|
+
sleep(1)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _enter_url(self, url_string: str, url_bar_xpath):
|
|
144
|
+
self.driver.send_keys(url_bar_xpath, url_string)
|
|
145
|
+
self.driver.press_enter()
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from puma.apps.android.google_chrome import logger
|
|
2
|
+
from puma.apps.android.google_chrome.xpaths import TAB_SWITCH_BUTTON, TAB_LIST, URL_BAR, \
|
|
3
|
+
NEW_TAB_FROM_CURRENT_TAB, BOOKMARKS_SORT_VIEW, BOOKMARKS_CREATE_FOLDER, BOOKMARKS_GO_BACK
|
|
4
|
+
from puma.state_graph.puma_driver import PumaDriver
|
|
5
|
+
from puma.state_graph.state import SimpleState, ContextualState, compose_clicks, TransitionError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BookmarksFolder(SimpleState, ContextualState):
|
|
9
|
+
def __init__(self, parent_state):
|
|
10
|
+
"""
|
|
11
|
+
Initializes the BookmarksFolder state with a given parent state.
|
|
12
|
+
|
|
13
|
+
:param parent_state: The parent state of this state
|
|
14
|
+
"""
|
|
15
|
+
super().__init__(xpaths=[BOOKMARKS_SORT_VIEW, BOOKMARKS_GO_BACK, BOOKMARKS_CREATE_FOLDER],
|
|
16
|
+
parent_state=parent_state,
|
|
17
|
+
parent_state_transition=compose_clicks([BOOKMARKS_GO_BACK]))
|
|
18
|
+
|
|
19
|
+
def validate_context(self, driver: PumaDriver, folder_name: str = None) -> bool:
|
|
20
|
+
"""
|
|
21
|
+
Validates if we are in the correct bookmarks folder.
|
|
22
|
+
:param driver: Puma driver
|
|
23
|
+
:param folder_name: Name of the bookmarks folder
|
|
24
|
+
:return: boolean
|
|
25
|
+
"""
|
|
26
|
+
if folder_name is None:
|
|
27
|
+
return True
|
|
28
|
+
return driver.is_present(f'//android.view.ViewGroup[@resource-id="com.android.chrome:id/action_bar"]//android.widget.TextView[@text="{folder_name}"]')
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def go_to_bookmarks_folder(driver: PumaDriver, folder_name: str):
|
|
32
|
+
driver.click(f'//android.widget.TextView[@resource-id="com.android.chrome:id/title" and @text="{folder_name}"]')
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CurrentTab(SimpleState, ContextualState):
|
|
36
|
+
"""
|
|
37
|
+
A state representing an existing tab in the application.
|
|
38
|
+
|
|
39
|
+
This class extends both SimpleState and ContextualState to represent a tab screen. The contextual state is an outlier,
|
|
40
|
+
see the validate_context method.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, parent_state):
|
|
44
|
+
"""
|
|
45
|
+
Initializes the Current Tab state with a given parent state.
|
|
46
|
+
|
|
47
|
+
:param parent_state: The parent state of this current tab state.
|
|
48
|
+
"""
|
|
49
|
+
super().__init__(
|
|
50
|
+
xpaths=[URL_BAR, NEW_TAB_FROM_CURRENT_TAB],
|
|
51
|
+
parent_state=parent_state,
|
|
52
|
+
parent_state_transition=compose_clicks([TAB_SWITCH_BUTTON]))
|
|
53
|
+
# Keep a dict that tracks which tab indices were opened last on which device. See validate_context()
|
|
54
|
+
self.last_opened = {}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def validate_context(self, driver: PumaDriver, tab_index: int = None) -> bool:
|
|
58
|
+
"""
|
|
59
|
+
We can not validate if we are in the nth tab from the tab overview, while in the tab contextual state, as this
|
|
60
|
+
index is not available in the state.
|
|
61
|
+
Therefore, we opted to store the last opened tab index for each device in this state. This means that the
|
|
62
|
+
contextual state is not actually verified against the UI, but against the tab index saved in the last opened
|
|
63
|
+
dict. When switching between two tabs, this works as long as the user does not interrupt Puma during these UI
|
|
64
|
+
actions.
|
|
65
|
+
#TODO document this situation in the CONTRIBUTING
|
|
66
|
+
:param driver: Puma driver
|
|
67
|
+
:param tab_index: Index of the tab last opened
|
|
68
|
+
:return: boolean
|
|
69
|
+
"""
|
|
70
|
+
if not tab_index:
|
|
71
|
+
return True
|
|
72
|
+
try:
|
|
73
|
+
return self.last_opened[driver.udid] == tab_index
|
|
74
|
+
except KeyError:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
def switch_to_tab(self, driver: PumaDriver, tab_index: int):
|
|
78
|
+
"""
|
|
79
|
+
Navigate to the tab at the specified index in the tab overview. This method also stores which tab index was
|
|
80
|
+
opened on which device, enabling contextual validation in validate_context().
|
|
81
|
+
|
|
82
|
+
:param driver: The PumaDriver instance used to interact with the application
|
|
83
|
+
:param tab_index: Index of the tab to navigate to
|
|
84
|
+
"""
|
|
85
|
+
tab_content_view = f'({TAB_LIST}//*[@resource-id="com.android.chrome:id/content_view"])[{tab_index}]'
|
|
86
|
+
if driver.is_present(f'{tab_content_view}'
|
|
87
|
+
f'//*'
|
|
88
|
+
f'[@resource-id="com.android.chrome:id/tab_title" and @text="New tab"]'):
|
|
89
|
+
logger.error(f"The tab at index {tab_index} is a new tab, not an existing tab. Use the new tab action "
|
|
90
|
+
f"instead.")
|
|
91
|
+
raise TransitionError()
|
|
92
|
+
driver.click(tab_content_view)
|
|
93
|
+
self.last_opened[driver.udid] = tab_index
|