-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathutils.py
263 lines (216 loc) · 10 KB
/
utils.py
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
import datetime
import os
from selenium import webdriver
import settings
def launch_driver(driver_name=settings.DRIVER, desired_capabilities=None):
"""Create and configure a WebDriver.
Args:
driver_name : Name of WebDriver to use
desired_capabilities : Desired browser specs
"""
driver = None
try:
driver_cls = getattr(webdriver, driver_name)
except AttributeError:
driver_cls = getattr(webdriver, settings.DRIVER)
if driver_name == 'Remote':
if desired_capabilities is None:
desired_capabilities = settings.DESIRED_CAP
command_executor = 'http://{}:{}@hub.browserstack.com:80/wd/hub'.format(
settings.BSTACK_USER, settings.BSTACK_KEY
)
if settings.BUILD == 'firefox':
# Create a temporary Firefox WebDriver to fetch the current user agent
temp_options = webdriver.FirefoxOptions()
temp_driver = webdriver.Firefox(options=temp_options)
default_user_agent = temp_driver.execute_script(
'return navigator.userAgent;'
)
temp_driver.quit()
# Append "Selenium Bot" to the existing user agent
custom_user_agent = f'{default_user_agent} OSF Selenium Bot'
from selenium.webdriver.firefox.options import Options
ffo = Options()
# Set custom user agent
ffo.set_preference('general.useragent.override', custom_user_agent)
# Set the default download location [0=Desktop, 1=Downloads, 2=Specified location]
ffo.set_preference('browser.download.folderList', 1)
# Disable the OS-level pop-up modal
ffo.set_preference('browser.download.manager.showWhenStarting', False)
ffo.set_preference('browser.helperApps.alwaysAsk.force', False)
ffo.set_preference('browser.download.manager.alertOnEXEOpen', False)
ffo.set_preference('browser.download.manager.closeWhenDone', True)
ffo.set_preference('browser.download.manager.showAlertOnComplete', False)
ffo.set_preference('browser.download.manager.useWindow', False)
# Specify the file types supported by the download
ffo.set_preference(
'browser.helperApps.neverAsk.saveToDisk',
'text/plain, application/octet-stream, application/binary, text/csv, application/csv, '
'application/excel, text/comma-separated-values, text/xml, application/xml, binary/octet-stream',
)
# Block Third Party Tracking Cookies (Default in Firefox is now 5 which blocks
# all Cross-site cookies)
ffo.set_preference('network.cookie.cookieBehavior', 4)
driver = driver_cls(
command_executor=command_executor,
desired_capabilities=desired_capabilities,
options=ffo,
)
elif settings.BUILD == 'chrome':
from selenium.webdriver.chrome.options import Options
chrome_options: Options = Options()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('window-size=1200x600')
# Fetch default user agent
temp_driver = driver_cls(
command_executor=command_executor,
desired_capabilities=desired_capabilities,
options=chrome_options,
)
default_user_agent = temp_driver.execute_script(
'return navigator.userAgent;'
)
temp_driver.quit()
# Append "OSF Selenium Bot" to the existing user agent
custom_user_agent = f'{default_user_agent} OSF Selenium Bot'
chrome_options.add_argument(f'user-agent={custom_user_agent}')
# Make a copy of desired capabilities for Chrome
desired_capabilities = settings.DESIRED_CAP.copy()
# Attach Chrome options
desired_capabilities['goog:chromeOptions'] = {
'args': chrome_options.arguments
}
driver = driver_cls(
command_executor=command_executor,
desired_capabilities=desired_capabilities,
options=chrome_options,
)
elif settings.BUILD == 'edge':
# Use default settings for edge driver
# We can update this once we upgrade to selenium v4
driver = webdriver.Edge()
elif driver_name == 'Chrome' and settings.HEADLESS:
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('window-size=1200x600')
driver = driver_cls(options=chrome_options)
elif driver_name == 'Chrome' and not settings.HEADLESS:
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
# disable w3c for local testing
chrome_options.add_experimental_option('w3c', False)
preferences = {'download.default_directory': ''}
chrome_options.add_experimental_option('prefs', preferences)
driver = driver_cls(options=chrome_options)
elif driver_name == 'Firefox' and not settings.HEADLESS:
from selenium.webdriver.firefox.options import Options
ffo = Options()
# Set the default download location [0=Desktop, 1=Downloads, 2=Specified location]
ffo.set_preference('browser.download.folderList', 1)
ffo.set_preference('browser.download.manager.showWhenStarting', False)
ffo.set_preference('browser.helperApps.alwaysAsk.force', False)
ffo.set_preference(
'browser.helperApps.neverAsk.saveToDisk',
'text/plain, application/octet-stream, application/binary, text/csv, application/csv, '
'application/excel, text/comma-separated-values, text/xml, application/xml, binary/octet-stream',
)
# Block Third Party Tracking Cookies (Default in Firefox is now 5 which blocks
# all Cross-site cookies)
ffo.set_preference('network.cookie.cookieBehavior', 4)
# Force Firefox to open links in new tab instead of new browser window.
ffo.set_preference('browser.link.open_newwindow', 3)
driver = driver_cls(options=ffo)
elif driver_name == 'Edge' and not settings.HEADLESS:
driver = webdriver.Edge()
else:
driver = driver_cls()
if driver is None:
raise RuntimeError(
'WebDriver could not be instantiated based on provided configuration.'
)
driver.maximize_window()
return driver
def find_current_browser(driver):
current_browser = driver.desired_capabilities.get('browserName')
return current_browser
def switch_to_new_tab(driver):
# Took this snippet from browserstack support docs
# https://www.browserstack.com/guide/how-to-switch-tabs-in-selenium-python
# get current window handle
main_window = driver.current_window_handle
# get first child window
all_windows = driver.window_handles
for new_tab in all_windows:
# switch focus to child window
if new_tab != main_window:
driver.switch_to.window(new_tab)
# We need to return the main_window so we can keep track
# of it and when we close the newly opened tab
return main_window
def close_current_tab(driver, main_window):
# close browser tab window
driver.close()
# switch to parent window
driver.switch_to.window(main_window)
def find_row_by_name(files_page, file_name):
all_files = files_page.file_rows
for file_row in all_files:
if file_name in file_row.text:
return file_row
return
def verify_file_download(driver, file_name):
"""Helper function to verify the file download functionality on the Project Files
page.
"""
current_date = datetime.datetime.now()
if settings.DRIVER == 'Remote':
# First verify the downloaded file exists on the virtual remote machine
assert driver.execute_script(
'browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "%s"}}'
% (file_name)
)
# Next get the file properties and then verify that the file creation date is today
file_props = driver.execute_script(
'browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "%s"}}'
% (file_name)
)
file_create_date = datetime.datetime.fromtimestamp(file_props['created_time'])
assert file_create_date.date() == current_date.date()
else:
# First verify the downloaded file exists
file_path = os.path.expanduser('~/Downloads/' + file_name)
assert os.path.exists(file_path)
# Next verify the file was downloaded today
file_mtime = os.path.getmtime(file_path)
file_mod_date = datetime.datetime.fromtimestamp(file_mtime)
assert file_mod_date.date() == current_date.date()
def latest_download_file():
path = os.path.expanduser('~/Downloads/')
os.chdir(path)
files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime)
newest = files[-1]
return newest
def get_guid_from_url(url, itemno):
url_string_list = url.split('/')
guid = url_string_list[itemno]
return guid
def read_data_from_table(driver, table_path, check_match, item_match=None):
datalist = []
table_data = driver.find_element_by_xpath(table_path)
path1 = table_path + '/tbody/tr'
rows = table_data.find_elements_by_xpath(path1)
rlen = len(rows)
for i in range(1, rlen + 1):
path2 = path1 + '[' + str(i) + ']/td'
items = driver.find_elements_by_xpath(path2)
clen = len(items)
for j in range(1, clen + 1):
path3 = path2 + '[' + str(j) + ']'
cell_data = driver.find_element_by_xpath(path3).text
datalist.append(cell_data)
if check_match:
if item_match in cell_data:
return i, datalist
return rlen, datalist