-
Notifications
You must be signed in to change notification settings - Fork 4
/
run-tests.py
executable file
·462 lines (394 loc) · 17.5 KB
/
run-tests.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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#!/usr/bin/env python3
import argparse
import logging
import pdb
import re
from selenium import webdriver
from selenium.common.exceptions import (
ElementClickInterceptedException,
NoSuchElementException,
NoSuchWindowException,
)
from selenium.webdriver.common.by import By
import tempfile
import time
import yaml
### Workaround for bug in Ubuntu/Debian Python Selenium module
# In the main body code below, `webdriver.Chrome` has been replaced with
# `ChromeWebDriver` and `webdriver.Firefox` has been replaced with
# `FirefoxWebDriver`. These changes can be undone if/when Ubuntu and Debian get
# around to cleaning up their shit.
import os
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver import Chrome
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver import Firefox
def ChromeWebDriver(*args, **kwargs):
service = ChromeService(executable_path='/usr/bin/chromedriver')
return Chrome(*args, service=service, **kwargs)
def FirefoxWebDriver(*args, **kwargs):
geckodriver = ('/snap/bin/geckodriver'
if os.path.exists('/snap/bin/geckodriver')
else '/usr/local/bin/geckodriver')
service = FirefoxService(executable_path=geckodriver)
return Firefox(*args, service=service, **kwargs)
### End workaround code
config_file = "test-config.yml"
job_selector = (".jobs-search-results__list-item, "
".jobs-job-board-list__item, "
".discovery-templates-entity-item")
title_selector = ".job-card-list__title"
company_selector = (".job-card-container__primary-description, "
".job-card-container__company-name")
location_selector = ".job-card-container__metadata-item"
workplace_selector = ".job-card-container__metadata-item--workplace-type"
private_hide_selector = ".lijfhidebutton"
show_you_fewer = "Got it. We’ll show you fewer"
class_logger = None
url_prefix = None
def parse_args():
parser = argparse.ArgumentParser(
description="Test Jobs Filterer for LinkedIn")
group = parser.add_mutually_exclusive_group()
group.add_argument("--chrome", dest="browser", action="store_const",
const="chrome", default="chrome",
help="Test in Chrome (Default)")
group.add_argument("--firefox", dest="browser", nargs='?', action="store",
const="firefox", help="Test in Firefox (optionally "
"specify path of firefox executable)")
parser.add_argument("--headless", action="store_true", default=False)
parser.add_argument("--transient", action="store_true", default=False,
help='Use transient user data directory with Chrome '
'(Firefox always uses transient directory) instead '
'of ".chrome"')
parser.add_argument("--local-only", action="store_true", default=False,
help="Don't run tests that depend on LinkedIn")
return parser.parse_args()
def main():
global class_logger, url_prefix
class_logger = logging.getLogger(__file__)
class_logger.setLevel(logging.DEBUG)
handler = logging.FileHandler("classes.log")
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
class_logger.addHandler(handler)
config = yaml.load(open(config_file), yaml.Loader)
args = parse_args()
with tempfile.TemporaryDirectory() as user_data_directory:
if args.browser == "chrome":
url_prefix = "chrome-extension"
if not args.transient:
user_data_directory = ".chrome"
options = webdriver.ChromeOptions()
if args.headless:
options.add_argument("headless=new")
# Needs to be big enough to prevent the Messaging banner from
# obscuring the first listed job even when Messaging is hidden.
options.add_argument("window-size=1280,1024")
options.add_argument(f"user-data-dir={user_data_directory}")
options.add_extension("JobsFiltererForLinkedIn-test.zip")
driver = ChromeWebDriver(options=options)
else:
url_prefix = "moz-extension"
options = webdriver.FirefoxOptions()
if args.browser != "firefox":
options.binary_location = args.browser
options.set_preference("xpinstall.signatures.required", False)
if args.headless:
options.add_argument("headless")
options.add_argument("--width=1280")
options.add_argument("--height=1024")
driver = FirefoxWebDriver(options=options)
driver.install_addon("JobsFiltererForLinkedIn-test.xpi")
try:
run_tests(config, args, driver)
finally:
driver.quit()
def run_tests(config, args, driver):
# Did the changelog page load on install?
start = time.time()
while len(driver.window_handles) == 1 and time.time() - start < 2:
time.sleep(0.1)
# Does permission need to be granted?
time.sleep(1) # Wait for permissions page to load
for window in range(2, len(driver.window_handles)):
driver.switch_to.window(driver.window_handles[window])
if driver.current_url.endswith("permissions.html"):
print("Waiting for access to linkedin.com to be granted.")
start = time.time()
while time.time() - start < 30:
try:
driver.current_url
except NoSuchWindowException:
break
time.sleep(0.1)
else:
raise TimeoutError("Giving up waiting for access.")
# Does the changelog page have expected content?
driver.switch_to.window(driver.window_handles[1])
assert "change history" in driver.page_source
match = re.match(r"(?:chrome|moz)-extension://(.*)/changes\.html$",
driver.current_url)
extension_id = match[1]
# Can we load the help page with expected content?
driver.get(f"{url_prefix}://{extension_id}/help.html")
assert "Example workflow" in driver.page_source
# Can we load the options page with expected content?
options_page = f"{url_prefix}://{extension_id}/options.html"
driver.get(options_page)
driver.find_element(By.ID, "hideJobs")
options_window_handle = driver.current_window_handle
hidden = driver.find_element(By.ID, "alt-s").get_attribute("hidden")
assert (hidden == "true") is (args.browser != "chrome")
driver.find_element(By.ID, "titles").send_keys("TitleRegexp")
driver.find_element(By.ID, "companies").send_keys("CompanyRegexp")
driver.find_element(By.ID, "locations").send_keys("LocationRegexp")
driver.find_element(By.ID, "jobs").send_keys(
"Title // Company // Location")
driver.find_element(By.ID, "save").click()
wait_for(lambda: "Options saved" in
driver.find_element(By.ID, "status").get_attribute("innerText"))
driver.find_element(By.ID, "save").click()
wait_for(lambda: "No changes" in
driver.find_element(By.ID, "status").get_attribute("innerText"))
driver.switch_to.new_window("tab")
driver.get(options_page)
wait_for(lambda: driver.find_element(By.ID, "titles").
get_attribute("value") == "TitleRegexp\n")
wait_for(lambda: driver.find_element(By.ID, "companies").
get_attribute("value") == "CompanyRegexp\n")
wait_for(lambda: driver.find_element(By.ID, "locations").
get_attribute("value") == "LocationRegexp\n")
wait_for(lambda: driver.find_element(By.ID, "jobs").
get_attribute("value") == "Title // Company // Location\n")
# Note that subsequent tests depend on "jobs" not being empty.
driver.close()
# Run JavaScript tests
driver.switch_to.window(options_window_handle)
test_load_script = """
import(chrome.runtime.getURL('tests.js'))
.then((tests) => { return tests.runTests();})
.then((result) => { document.testResult = result; });
"""
driver.execute_script(test_load_script)
test_result = wait_for(
lambda: driver.execute_script("return document.testResult"),
timeout=2
)
if test_result != "success":
print("JavaScript tests failed")
pdb.set_trace()
if args.local_only:
return
# Log into LinkedIn
driver.switch_to.new_window("tab")
linkedin_window_handle = driver.current_window_handle
driver.get("https://www.linkedin.com/")
state = None
while state != "homepage":
(state, elt) = wait_for(
lambda: ("login", find_password_field(driver)),
lambda: ("2fa", driver.find_element(
By.ID, "input__phone_verification_pin")),
lambda: ("captcha", driver.find_element(
By.ID, "captcha-internal")),
lambda: ("challenge", driver.find_element(
By.NAME, "challengeType")),
lambda: ("homepage", driver.find_element(
By.PARTIAL_LINK_TEXT, "Notifications"))
)
if state == "login":
find_username_field(driver).send_keys(config["linkedin_username"])
elt.send_keys(config["linkedin_password"])
find_login_button(driver).click()
elif state == "2fa":
mfa_code = input("Enter MFA code: ")
elt.send_keys(mfa_code)
driver.find_element(By.ID, "two-step-submit-button").click()
elif state == "captcha":
input("Solve CAPTCHA and then hit Enter: ")
elif state == "challenge":
input("Complete challenge and then hit Enter: ")
try:
test_job_on_page(
driver, "https://www.linkedin.com/jobs",
linkedin_window_handle, options_window_handle)
test_job_on_page(
driver, "https://www.linkedin.com/jobs/collections/recommended/",
linkedin_window_handle, options_window_handle)
test_job_on_page(
driver, "https://www.linkedin.com/jobs/search/"
"?keywords=Quality%20Assurance%20Engineer",
linkedin_window_handle, options_window_handle)
except ElementClickInterceptedException:
fn = "/tmp/litest_screenshot.png"
driver.save_screenshot(fn)
print(f"Element click intercepted, screenshot saved in {fn}")
pdb.set_trace()
def find_username_field(driver):
elts = driver.find_elements(By.ID, "username")
if elts:
return elts[0]
return driver.find_element(By.ID, "session_key")
def find_password_field(driver):
elts = driver.find_elements(By.ID, "password")
if elts:
return elts[0]
return driver.find_element(By.ID, "session_password")
def find_login_button(driver):
elts = driver.find_elements(By.XPATH, "//*[@aria-label='Sign in']")
if elts:
return elts[0]
return driver.find_element(By.XPATH,
"//*[@data-id='sign-in-form__submit-btn']")
def hide_messaging(driver):
# If Messaging is showing it can block other buttons.
state = None
while state != "hidden":
(state, elt) = wait_for(
lambda: ("hidden", driver.find_element(
By.XPATH, "//*[@id='msg-overlay']//*[@type='chevron-up']")),
lambda: ("showing", driver.find_element(
By.XPATH, "//*[@id='msg-overlay']//*[@type='chevron-down']")),
)
if state == "showing":
elt.click()
def test_job_on_page(driver, url,
linkedin_window_handle, options_window_handle):
driver.switch_to.window(options_window_handle)
orig_job_text = wait_for(lambda: driver.find_element(By.ID, "jobs").
get_attribute("value"))
# Can we find and hide a job?
driver.switch_to.window(linkedin_window_handle)
driver.get(url)
hide_messaging(driver)
# We need to wait until we see the first job _title_ before we look for
# the first _job_ because empty jobs show up temporarily on the page and
# are then replaced by the real ones with contents (like job title).
titles = log_class(wait_for(lambda: driver.find_elements(
By.CSS_SELECTOR, title_selector)), is_list=True)
# Wait for the page to "settle", i.e., wait until two seconds go by with
# the set of job title elements not changing.
start = time.time()
while time.time() - start < 2:
new_titles = wait_for(lambda: driver.find_elements(
By.CSS_SELECTOR, title_selector))
if titles != new_titles:
titles = new_titles
start = time.time()
ordinal, first_job = wait_for(lambda: find_first_active_job(driver))
job_title = wait_for(lambda: first_job.find_elements(
By.CSS_SELECTOR, title_selector))[0].text
job_company = log_class(wait_for(lambda: first_job.find_elements(
By.CSS_SELECTOR, company_selector))[0]).text
job_location = get_location(first_job)
hide_button = wait_for(lambda: find_hide_button(driver, first_job))
hide_button.click()
# Is the job we just hid now in the options?
driver.switch_to.window(options_window_handle)
job_text = f"{job_title} // {job_company} // {job_location}\n"
wait_for(lambda: driver.find_element(By.ID, "jobs").
get_attribute("value") == job_text + orig_job_text)
# Can we find and unhide the same job?
driver.switch_to.window(linkedin_window_handle)
time.sleep(1) # race condition, LinkedIn may not be done rearranging
first_job = wait_for(lambda: find_job(driver, ordinal))
unhide_result = wait_for(
lambda: find_unhide_button(first_job),
lambda: ("permanent" if show_you_fewer
in first_job.get_attribute("innerText") else False))
if unhide_result != "permanent":
unhide_result.click()
# Does the unhidden job get removed from the options page?
driver.switch_to.window(options_window_handle)
wait_for(lambda: driver.find_element(By.ID, "jobs").
get_attribute("value") == orig_job_text)
else:
driver.switch_to.window(options_window_handle)
orig_job_text = (driver.find_element(By.ID, "jobs").
get_attribute("value"))
# Can we find and click the private hide button?
driver.switch_to.window(linkedin_window_handle)
ordinal, first_job = wait_for(lambda: find_first_active_job(driver))
job_title = wait_for(lambda: first_job.find_elements(
By.CSS_SELECTOR, title_selector))[0].text
job_company = wait_for(lambda: first_job.find_elements(
By.CSS_SELECTOR, company_selector))[0].text
job_location = get_location(first_job)
hide_button = wait_for(lambda: find_private_hide_button(driver, first_job))
hide_button.click()
# Is the job hidden now?
wait_for(lambda: first_job.get_attribute("hidden") == "true")
# Is the LinkedIn hide button still there, i.e., we didn't do the wrong
# thing and hide the job via LinkedIn instead of privately?
wait_for(lambda: find_hide_button(driver, first_job, hidden_ok=True))
# Is the job we just hid now listed on the options page?
driver.switch_to.window(options_window_handle)
job_text = f"{job_title} // {job_company} // {job_location} // private\n"
wait_for(lambda: driver.find_element(By.ID, "jobs").
get_attribute("value") == job_text + orig_job_text)
def get_location(elt):
job_location = log_class(wait_for(lambda: elt.find_elements(
By.CSS_SELECTOR, location_selector))[0]).text
workplaces = log_class(
elt.find_elements(By.CSS_SELECTOR, workplace_selector), is_list=True)
if workplaces:
job_location = f"{job_location} ({workplaces[0].text})"
return job_location
def wait_for(*funcs, timeout=10):
sleep_for = 0.1
start = time.time()
while time.time() - start < timeout:
for func in funcs:
try:
result = func()
except NoSuchElementException:
continue
if result:
return result
time.sleep(sleep_for)
sleep_for *= 2
pdb.set_trace()
def find_first_active_job(driver):
ordinal = 1
for elt in log_class(driver.find_elements(By.CSS_SELECTOR, job_selector),
is_list=True):
if elt.get_attribute("hidden") == "true":
ordinal += 1
continue
if show_you_fewer in elt.get_attribute("innerText"):
ordinal += 1
continue
return (ordinal, elt)
def find_job(driver, ordinal):
for elt in driver.find_elements(By.CSS_SELECTOR, job_selector):
ordinal -= 1
if ordinal == 0:
return elt
return None
def find_hide_button(driver, elt, hidden_ok=False):
if not (hidden_ok or elt.get_attribute("lijfState") == "visible"):
return None
elts = elt.find_elements(By.TAG_NAME, "button")
for elt in elts:
label = elt.get_attribute("aria-label")
if label and ("Hide" in label or "Dismiss" in label or
re.match(r'^Mark .* with Not for me', label)):
return elt
return None
def find_private_hide_button(driver, elt):
return elt.find_element(By.CSS_SELECTOR, private_hide_selector)
def find_unhide_button(elt):
elts = elt.find_elements(By.TAG_NAME, "button")
for elt in elts:
if elt.text == "Undo":
return elt
return None
def log_class(elt, is_list=False):
if elt:
the_class = (elt[0] if is_list else elt).get_attribute("class")
the_class = re.sub(r'\s+', ' ', the_class).strip()
class_logger.info(the_class)
return elt
if __name__ == "__main__":
main()