Skip to content

Commit 24e4426

Browse files
committed
[tests] Added selenium helper methods
Added: - find_element - wait_for_visibility - wait_for_invisibility - wait_for These methods will allow us to write tests using best practices more easily.
1 parent 6c63898 commit 24e4426

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

openwisp_utils/test_selenium_mixins.py

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22

33
from selenium import webdriver
4+
from selenium.common.exceptions import TimeoutException
45
from selenium.webdriver.common.by import By
56
from selenium.webdriver.firefox.options import Options
67
from selenium.webdriver.support import expected_conditions as EC
@@ -47,7 +48,7 @@ def tearDownClass(cls):
4748
cls.web_driver.quit()
4849
super().tearDownClass()
4950

50-
def open(self, url, driver=None):
51+
def open(self, url, driver=None, timeout=5):
5152
"""Opens a URL.
5253
5354
Input Arguments:
@@ -58,8 +59,11 @@ def open(self, url, driver=None):
5859
if not driver:
5960
driver = self.web_driver
6061
driver.get(f'{self.live_server_url}{url}')
61-
WebDriverWait(self.web_driver, 2).until(
62-
EC.visibility_of_element_located((By.CSS_SELECTOR, '#main-content'))
62+
WebDriverWait(driver, timeout).until(
63+
lambda d: d.execute_script("return document.readyState") == "complete"
64+
)
65+
WebDriverWait(self.web_driver, timeout).until(
66+
EC.presence_of_element_located((By.CSS_SELECTOR, '#main-content'))
6367
)
6468

6569
def login(self, username=None, password=None, driver=None):
@@ -84,3 +88,21 @@ def login(self, username=None, password=None, driver=None):
8488
driver.find_element(by=By.NAME, value='username').send_keys(username)
8589
driver.find_element(by=By.NAME, value='password').send_keys(password)
8690
driver.find_element(by=By.XPATH, value='//input[@type="submit"]').click()
91+
92+
def find_element(self, by, value, timeout=2):
93+
self.wait_for_visibility(by, value, timeout)
94+
return self.web_driver.find_element(by=by, value=value)
95+
96+
def wait_for_visibility(self, by, value, timeout=2):
97+
self.wait_for('visibility_of_element_located', by, value)
98+
99+
def wait_for_invisibility(self, by, value, timeout=2):
100+
self.wait_for('invisibility_of_element_located', by, value)
101+
102+
def wait_for(self, method, by, value, timeout=2):
103+
try:
104+
WebDriverWait(self.web_driver, timeout).until(
105+
getattr(EC, method)(((by, value)))
106+
)
107+
except TimeoutException as e:
108+
self.fail(f'{method} of "{value}" failed: {e}')

0 commit comments

Comments
 (0)