| import contextlib |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from selenium import webdriver |
| from selenium.webdriver.chrome.service import Service as ChromeService |
| from webdriver_manager.chrome import ChromeDriverManager |
| from selenium.webdriver.support.wait import WebDriverWait |
| from selenium.webdriver.common.by import By |
| from selenium.common.exceptions import TimeoutException, ElementNotInteractableException |
| from selenium.webdriver.support import expected_conditions as EC |
| from selenium.webdriver.chrome.options import Options |
| from selenium.webdriver.chrome.service import Service |
| from selenium.webdriver.common.action_chains import ActionChains |
| from selenium.webdriver.common.keys import Keys |
| from json.decoder import JSONDecodeError |
| import html |
| from simple_term_menu import TerminalMenu |
| import shutil |
| import subprocess |
| import html |
| import random |
|
|
| |
| import threading |
|
|
| import json |
| import time |
| import re |
| import glob |
| import sys |
| import os |
|
|
| |
| |
| |
|
|
| |
| DEVTOOLS = True |
|
|
| |
| urls = [ |
| "http://localhost:8080", |
| |
| |
| "https://molmoda.org", |
| "https://beta.molmoda.org", |
| ] |
|
|
| menu = TerminalMenu(urls, title="Select the root URL") |
| chosen_index = menu.show() |
| root_url = urls[chosen_index] |
|
|
| browsers_to_use = [] |
| browser_choices = [ |
| "[s] standard three", |
| "chrome", |
| "chrome-headless", |
| "firefox", |
| "firefox-headless", |
| "safari", |
| "[d] done", |
| ] |
| menu = TerminalMenu(browser_choices, title="Select the browsers to use") |
|
|
| while True: |
| print("Selected browsers: " + ", ".join(browsers_to_use)) |
| chosen_index2 = menu.show() |
| if chosen_index2 == len(browser_choices) - 1: |
| |
| break |
| if browser_choices[chosen_index2] == "[s] standard three": |
| browsers_to_use.extend(["chrome-headless", "firefox", "safari"]) |
| else: |
| browsers_to_use.append(browser_choices[chosen_index2]) |
| browsers_to_use = list(set(browsers_to_use)) |
| browsers_to_use.sort() |
|
|
| print("\nUsing root URL: " + root_url) |
|
|
|
|
| class el: |
| def __init__(self, selector, drvr, timeout=50): |
| self.selector = selector |
| self.timeout = timeout |
| self.driver = drvr |
| self.poll_frequency_secs = 2 |
|
|
| try: |
| self.el = WebDriverWait( |
| drvr, self.timeout, poll_frequency=self.poll_frequency_secs |
| ).until(lambda drvr: drvr.find_element(By.CSS_SELECTOR, selector)) |
| except TimeoutException as e: |
| self.throw_error(f"{self.selector} not found after {self.timeout} seconds") |
|
|
| @property |
| def text(self): |
| txt = self.el.get_attribute("value") |
| if txt in [None, ""]: |
| txt = self.el.get_attribute("innerHTML") |
|
|
| return txt |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
|
|
| @text.setter |
| def text(self, value): |
| |
| try: |
| self.el.clear() |
| except Exception as e: |
| pass |
|
|
| |
| with contextlib.suppress(Exception): |
| value = html.unescape(value) |
| if value == "BACKSPACE": |
| self.el.send_keys(Keys.BACKSPACE) |
| else: |
| self.el.send_keys(value) |
| self.check_errors() |
|
|
| @property |
| def value(self): |
| |
| return self.text |
|
|
| @value.setter |
| def value(self, value): |
| |
| self.text = value |
|
|
| def wait_until_text_is_not(self, text="", timeout=None): |
| if timeout is None: |
| timeout = self.timeout |
|
|
| |
| try: |
| WebDriverWait( |
| self.driver, self.timeout, poll_frequency=self.poll_frequency_secs |
| ).until_not(lambda driver: self.text == text) |
| except TimeoutException as e: |
| self.throw_error( |
| f"{self.selector} still [[{text}]] after {self.timeout} seconds" |
| ) |
|
|
| def click(self, shiftPressed=False): |
| try: |
| if shiftPressed: |
| |
| |
| ActionChains(self.driver).key_down(Keys.SHIFT).perform() |
| self.el.click() |
| if shiftPressed: |
| |
| ActionChains(self.driver).key_up(Keys.SHIFT).perform() |
|
|
| self.check_errors() |
| except ElementNotInteractableException as e: |
| |
| self.throw_error(f"{self.selector} not clickable") |
|
|
| def upload_file(self, file_path): |
| file_path = os.path.realpath(file_path) |
| self.el.send_keys(file_path) |
| self.check_errors() |
|
|
| def checkBox(self, value): |
| |
| current_value = self.el.get_attribute("checked") == "true" |
|
|
| if value != current_value: |
| self.el.click() |
|
|
| def wait_until_contains_regex(self, regex): |
|
|
| |
| try: |
| regex = html.unescape(regex) |
| wait = WebDriverWait( |
| self.driver, self.timeout, poll_frequency=self.poll_frequency_secs |
| ) |
|
|
| def check(driver): |
| |
| text_content = self.text |
|
|
| |
| |
| |
| |
|
|
| |
| return re.search(regex, text_content) |
|
|
| self.el = wait.until(check) |
| |
| except TimeoutException as e: |
| self.throw_error( |
| f"{self.selector} does not contain [[{regex}]] after {self.timeout} seconds; Actual text: [[{self.text}]]" |
| ) |
|
|
| def wait_until_does_not_contain_regex(self, regex): |
| try: |
| regex = html.unescape(regex) |
| WebDriverWait( |
| self.driver, self.timeout, poll_frequency=self.poll_frequency_secs |
| ).until_not(lambda driver: re.search(regex, self.text)) |
| |
| except TimeoutException as e: |
| self.throw_error( |
| f"{self.selector} still contains [[{regex}]] after {self.timeout} seconds" |
| ) |
|
|
| def check_errors(self): |
| |
| |
| time.sleep(0.5) |
|
|
| |
| err = el("#test-error", self.driver) |
| if err.text != "": |
| self.throw_error(err.text) |
|
|
| def throw_error(self, msg): |
| |
|
|
| if not msg.endswith("."): |
| msg += "." |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| raise Exception(msg) |
|
|
|
|
| def make_chrome_driver(options): |
| |
| if DEVTOOLS: |
| options.add_argument("--auto-open-devtools-for-tabs") |
|
|
| service = Service(executable_path="utils/chromedriver_wrapper.sh") |
| options.set_capability("goog:loggingPrefs", {"browser": "ALL"}) |
| driver = webdriver.Chrome(service=service, options=options) |
|
|
| |
| if "localhost" in root_url or "127.0.0.1" in root_url: |
| |
| driver.execute_cdp_cmd("Network.enable", {}) |
|
|
| |
| |
| |
| |
|
|
| return driver |
|
|
|
|
| def make_driver(browser): |
| driver = None |
| if browser == "firefox": |
| options = webdriver.FirefoxOptions() |
|
|
| |
| |
| |
| |
|
|
| driver = webdriver.Firefox(options=options) |
| driver.maximize_window() |
| elif browser == "firefox-headless": |
| input( |
| "Could get an error here (untested). Involving e.php. If so, it's because firefox-headless doesn't send the Origin header with 'localhost' in it..." |
| ) |
| options = webdriver.FirefoxOptions() |
| options.add_argument("-headless") |
| options.add_argument("--width=1920") |
| options.add_argument("--height=1080") |
| driver = webdriver.Firefox(options=options) |
| elif browser == "safari": |
| |
| |
| driver = webdriver.Safari() |
| driver.maximize_window() |
| os.system("""osascript -e 'tell application "Safari" to activate'""") |
| elif browser == "chrome": |
| |
| |
|
|
| |
|
|
| |
| |
| options = webdriver.ChromeOptions() |
| options.add_argument("--start-maximized") |
| options.add_argument("--window-size=1920,1080") |
| driver = make_chrome_driver(options) |
| elif browser == "chrome-headless": |
| options = webdriver.ChromeOptions() |
| |
| options.add_argument("--headless=new") |
| options.add_argument("--start-maximized") |
| options.add_argument("--window-size=1920,1080") |
| |
| options.add_argument( |
| "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" |
| ) |
| driver = make_chrome_driver(options) |
| return driver |
|
|
|
|
| def do_logs_have_errors(driver, browser): |
| if "firefox" in browser.lower(): |
| |
| return False |
|
|
| logs = driver.get_log("browser") |
|
|
| |
| logs_to_keep = [l for l in logs if l["level"] in ["SEVERE", "ERROR"]] |
|
|
| |
| |
| logs_to_keep = [ |
| l |
| for l in logs_to_keep |
| if "message" in l |
| and "status of 404" not in l["message"] |
| and "status code 404" not in l["message"] |
| and "status of 400" not in l["message"] |
| and "404 (Not Found)" not in l["message"] |
| |
| and not ( |
| "https://www.ebi.ac.uk/" in l["message"] |
| and "blocked by CORS policy" in l["message"] |
| ) |
| and not ( |
| "https://www.ebi.ac.uk/" in l["message"] |
| and "Failed to load resource" in l["message"] |
| ) |
| ] |
|
|
| if not logs_to_keep: |
| return False |
| else: |
| return " ".join([l["message"] for l in logs_to_keep]) |
|
|
|
|
| allowed_threads = { |
| "chrome": 4, |
| "chrome-headless": 4, |
| "firefox": 4, |
| "firefox-headless": 4, |
| "safari": 1, |
| } |
|
|
| drivers = {} |
| browser = "" |
|
|
|
|
| def check_errors(driver, browser): |
| |
| js_errs = do_logs_have_errors(driver, browser) |
| if js_errs != False: |
| if "user gesture" in js_errs: |
| print(f"Ignored JavaScript error: {js_errs} (ignored, user gesture)") |
| else: |
| raise Exception(f"Critical JavaScript error: {js_errs}") |
| return js_errs |
|
|
|
|
| def run_test(plugin_id_tuple): |
| global drivers |
| global browser |
|
|
| try: |
| key = threading.get_ident() |
| if key not in drivers: |
| drivers[key] = make_driver(browser) |
|
|
| driver = drivers[key] |
|
|
| try: |
| plugin_name, plugin_idx = plugin_id_tuple |
| test_lbl = ( |
| f"{plugin_name}{f' #{plugin_idx + 1}' if plugin_idx is not None else ''}" |
| ) |
| |
| url = f"{root_url}/?test={plugin_name}" |
| if plugin_idx is not None: |
| url += f"&index={str(plugin_idx)}" |
| driver.get(url) |
| cmds_str = None |
| cmds = None |
| for _ in range(4): |
| cmds_str = el("#test-cmds", driver).text |
| try: |
| cmds = json.loads(cmds_str) |
| break |
| except Exception as JSONDecodeError: |
| time.sleep(0.25) |
| |
| |
| |
| if cmds is None: |
| raise Exception( |
| "No commands found. Are you sure you specified an actual plugin id?" |
| ) |
| |
| if cmds_str is None: |
| print(f"Failed to parse JSON: {cmds_str}") |
| return { |
| "status": "failed", |
| "test": test_lbl, |
| "error": f"Failed to parse JSON: {cmds_str}", |
| } |
|
|
| screenshot_dir = f"./screenshots/{test_lbl}" |
| if os.path.exists(screenshot_dir): |
| shutil.rmtree(screenshot_dir) |
| if not os.path.exists("./screenshots"): |
| os.makedirs("./screenshots") |
| if not os.path.exists(screenshot_dir): |
| os.makedirs(screenshot_dir) |
|
|
| |
| try: |
| |
| for cmd_idx, cmd in enumerate(cmds): |
| |
| |
| if cmd["cmd"] == "click": |
| el(cmd["selector"], driver).click( |
| cmd["data"] if "data" in cmd else False |
| ) |
| elif cmd["cmd"] == "text": |
| el(cmd["selector"], driver).text = cmd["data"] |
| elif cmd["cmd"] == "wait": |
| time.sleep(cmd["data"]) |
| elif cmd["cmd"] == "waitUntilRegex": |
| el(cmd["selector"], driver).wait_until_contains_regex(cmd["data"]) |
| elif cmd["cmd"] == "waitUntilNotRegex": |
| el(cmd["selector"], driver).wait_until_does_not_contain_regex( |
| cmd["data"] |
| ) |
| elif cmd["cmd"] == "upload": |
| el(cmd["selector"], driver).upload_file(cmd["data"]) |
| elif cmd["cmd"] == "addTests": |
| return [(plugin_name, i) for i in range(cmd["data"])] |
| elif cmd["cmd"] == "checkBox": |
| el(cmd["selector"], driver).checkBox(cmd["data"]) |
| screenshot_path = f"{screenshot_dir}/{test_lbl}_{cmd_idx}.png" |
| driver.save_screenshot(screenshot_path) |
| js_errs = check_errors(driver, browser) |
| |
| |
| |
| |
| |
| |
|
|
| |
| resp = { |
| "status": "passed", |
| "test": test_lbl, |
| "error": "", |
| } |
| except Exception as e: |
| |
| |
| |
| |
| |
| resp = { |
| "status": "failed", |
| "test": test_lbl, |
| "error": str(e), |
| } |
| js_errs = check_errors(driver, browser) |
| |
| |
| |
| |
| return resp |
| finally: |
| |
| with contextlib.suppress(Exception): |
| driver.execute_script( |
| "window.localStorage.clear(); window.sessionStorage.clear();" |
| ) |
| except Exception as e: |
| if is_single_test_run: |
| print(f"\nAn error occurred during test '{plugin_id_tuple[0]}'.") |
| print(f"Error details: {e}") |
| input( |
| "The browser remains open for inspection. Press Enter to close it and proceed." |
| ) |
| raise |
|
|
|
|
| |
| if len(sys.argv) > 1: |
| |
| |
| |
|
|
| subjob_idx = None |
| plugin_ids = [] |
| |
| |
| for arg in sys.argv[1:]: |
| try: |
| subjob_idx = int(arg) - 1 |
| except ValueError: |
| plugin_ids.append(arg) |
|
|
| |
| plugin_ids = [(i, subjob_idx) for i in plugin_ids] |
|
|
| else: |
| |
| plugin_ids = [] |
| for ts_file in glob.glob("./src/**/*Plugin.vue", recursive=True): |
| with open(ts_file, "r") as f: |
| content = f.read() |
| plugin_id = re.search(r'[^:]\bpluginId *?= *?"(.+)"', content, re.MULTILINE)[1] |
| plugin_ids.append((plugin_id, None)) |
|
|
| |
| plugin_ids = [ |
| i |
| for i in plugin_ids |
| if "simplemsg" not in i[0] and "testplugin" not in i[0] and "redo" not in i[0] |
| ] |
|
|
| |
| if "safari" in browsers_to_use: |
| plugin_ids = [i for i in plugin_ids if "documentation" not in i[0]] |
|
|
| plugin_ids.sort() |
| |
|
|
| |
| |
|
|
| |
|
|
| |
| is_single_test_run = len(plugin_ids) == 1 |
|
|
| passed_tests = [] |
| failed_tests = [] |
|
|
| for browser_to_use in browsers_to_use: |
| |
| browser = browser_to_use |
|
|
| print("\nBrowser: " + browser + "\n") |
|
|
| plugin_ids_per_browser = plugin_ids.copy() |
|
|
| for try_idx in range(4): |
| |
| failed_tests_this_round = [] |
| drivers = {} |
|
|
| |
| random.shuffle(plugin_ids_per_browser) |
|
|
| with ThreadPoolExecutor( |
| max_workers=allowed_threads[browser_to_use] |
| ) as executor: |
| |
| |
| futures_to_tests = {} |
|
|
| results = [] |
|
|
| while plugin_ids_per_browser or futures_to_tests: |
| |
| while plugin_ids_per_browser: |
| |
| test = plugin_ids_per_browser.pop() |
| future = executor.submit(run_test, test) |
| futures_to_tests[future] = test |
|
|
| |
| for future in as_completed(futures_to_tests): |
| test = futures_to_tests[future] |
| try: |
| result = future.result() |
|
|
| |
| if isinstance(result, list): |
| plugin_ids_per_browser = result + plugin_ids_per_browser |
| |
| continue |
|
|
| |
| print( |
| f"{result['status'][:1].upper()}{result['status'][1:]}: {result['test']} {result['error']}" |
| ) |
| if result["status"] == "passed": |
| |
| passed_tests.append( |
| { |
| **result, |
| "try": try_idx + 1, |
| "browser": browser_to_use, |
| } |
| ) |
| else: |
| |
| failed_tests_this_round.append(test) |
| |
| failed_tests.append( |
| { |
| **result, |
| "try": try_idx + 1, |
| "browser": browser_to_use, |
| } |
| ) |
| except Exception as e: |
| print(f"Test {test} raised an exception: {e}") |
| |
| failed_tests_this_round.append(test) |
| |
| failed_tests.append( |
| { |
| "status": "failed", |
| "test": f"{test[0]}{f' #{test[1] + 1}' if test[1] is not None else ''}", |
| "error": str(e), |
| "try": try_idx + 1, |
| "browser": browser_to_use, |
| } |
| ) |
| finally: |
| del futures_to_tests[future] |
|
|
| |
| plugin_ids_per_browser = failed_tests_this_round |
| plugin_ids_per_browser.sort() |
|
|
| |
| for driver in drivers.values(): |
| driver.quit() |
| if browser == "safari": |
| |
| time.sleep(1) |
| os.system("pkill -9 Safari > /dev/null 2>&1") |
| time.sleep(1) |
|
|
| if not plugin_ids_per_browser: |
| break |
|
|
| plugin_ids_str = ", ".join( |
| [ |
| i[0] if i[1] is None else f"{i[0]} #{str(i[1] + 1)}" |
| for i in plugin_ids_per_browser |
| ] |
| ) |
| print(f"Will retry the following tests: {plugin_ids_str}") |
|
|
|
|
| |
|
|
| |
| print("") |
| print("Tests that passed:") |
| for result in passed_tests: |
| print(f" {result['test']}-{result['browser']} (try {result['try']})") |
|
|
| print("") |
| print("Tests that failed:") |
| unique_failed_tests = {f"{t['test']}-{t['browser']}": t for t in failed_tests}.values() |
| if not unique_failed_tests: |
| print(" None!") |
| else: |
| for result in unique_failed_tests: |
| print( |
| f" {result['test']}-{result['browser']} (Final Error: {result['error']})" |
| ) |
| |
|
|
| print("") |
| print(urls[chosen_index] + "\n") |
|
|
| if failed_tests: |
| failed_summary = {} |
| for t in failed_tests: |
| parts = t["test"].split(" #") |
| name = parts[0] |
| if name not in failed_summary: |
| failed_summary[name] = {"indices": set(), "no_index_failed": False} |
| if len(parts) > 1: |
| failed_summary[name]["indices"].add(int(parts[1])) |
| else: |
| failed_summary[name]["no_index_failed"] = True |
|
|
| run_again_parts = [] |
| for name in sorted(failed_summary.keys()): |
| summary = failed_summary[name] |
| if summary["no_index_failed"]: |
| run_again_parts.append(name) |
| elif summary["indices"]: |
| indices = summary["indices"] |
| indices_str = "".join(map(str, sorted(list(indices)))) |
| run_again_parts.append(f"{name}({indices_str})") |
|
|
| print(f" RUN AGAIN (FAILED)?: {' '.join(run_again_parts)}") |
| |
|
|
| |
|
|
| |
| input("Press Enter to run all jest unit tests...") |
| os.system("node_modules/.bin/jest") |
|
|