Last active
October 28, 2021 05:44
-
-
Save Asad-Khan-Aasanjobs/3b1b813e93f28b0ca037a3d4d74f0c89 to your computer and use it in GitHub Desktop.
Get element logic for selenium script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
__________________________________________________ | |
Base Page that provides basic page functionality | |
Positional arguments: | |
Selenium webdriver instance. | |
__________________________________________________ | |
""" | |
from bs4 import BeautifulSoup | |
from random import randint | |
import time | |
import logging | |
import requests | |
# import os | |
# import csv | |
# from enchant import DictWithPWL | |
# from enchant.checker import SpellChecker | |
# from enchant.tokenize import EmailFilter | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver import ActionChains | |
from selenium.webdriver.common.keys import Keys | |
from selenium.webdriver.support.ui import WebDriverWait | |
from selenium.webdriver.support import expected_conditions as EC | |
from selenium.common.exceptions import TimeoutException, NoSuchElementException | |
from selenium.webdriver.support.ui import Select | |
class AbstractBasePage(object): | |
""" Base Page object that provides basic page functionality. | |
Positional arguments: | |
Selenium webdriver instance. | |
""" | |
PATH = '/' | |
EXIT_PATH_URL = 'http://beta3.aasaanjobs.net' | |
API_URL = 'http://api3.aasaanjobs.net' | |
BEARER_TOKEN = 'Bearer AJSystemAdminStaging' | |
PROD_EXIT_PATH_URL = 'https://www.aasaanjobs.com' | |
PROD_API_URL = 'https://api.aasaanjobs.com' | |
PROD_BEARER_TOKEN = 'Bearer AJInfinity@XGod' | |
# ############ Candidate Creds | |
_CANDIDATE_MOBILE = "8823522624" | |
_CANDIDATE_PASSWORD = "123456" | |
# | |
_PROD_CANDIDATE_MOBILE = "9820453336" | |
_PROD_CANDIDATE_PASSWORD = "123123" | |
# ############ Partner Creds | |
_PARTNER_EMAIL = "[email protected]" | |
_PARTNER_PASSWORD = "123456" | |
# | |
_PROD_PARTNER_EMAIL = "[email protected]" | |
_PROD_PARTNER_PASSWORD = "dhruvil" | |
MY_WORDS_FILE_NAME = 'mywords.txt' | |
_timeout = 40 | |
_FOCUS_TAG_LOCATOR = (By.CSS_SELECTOR, 'body') | |
_CLOSE_LOGIN_MODEL_BUTTON_LOCATOR = (By.CSS_SELECTOR, '[style*="block"] .close') | |
_LOCATOR = (By.CSS_SELECTOR, 'div[class*="row"]') | |
_MAIN_CSS_FILE_LOCATOR = (By.CSS_SELECTOR, 'title ~ link[href*="css/main"]') | |
_LIB_JS_FILE_LOCATOR = (By.CSS_SELECTOR, 'script[src*="commons/libs."]') | |
_PUBLIC_JS_FILE_LOCATOR = (By.CSS_SELECTOR, 'script[src*="public."]') | |
_ALL_CDN_SCRIPT_LOCOS = (By.CSS_SELECTOR, 'script[src]') | |
_LOGIN_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'a[href^="/login/"]') | |
_HOMEPAGE_COMPANY_LOGO_LOCATOR = (By.CSS_SELECTOR, 'img.logo') | |
_HOPSCOTCH_CLOSE_BUTTON_LOCATOR = (By.CSS_SELECTOR, '.hopscotch-close') | |
_SPELLING_CHECKER1_LOCATOR = (By.CSS_SELECTOR, '.internal-navbar-wrapper + .row') | |
_SPELLING_CHECKER2_LOCATOR = (By.CSS_SELECTOR, '.internal-nav.nav') | |
# | |
# Page Level Functions for inheriting classes | |
# Kundiddate : 9797969676 | |
def __init__(self, *args, **kwargs): | |
""" Initializer method for Page base """ | |
self._base_url = self.EXIT_PATH_URL | |
# Waring! | |
# Variable 'selenium' is not an object of Selenium class | |
# It is a Selenium Webdriver Object! [Apologies for misleading name] | |
# !![This should be changed asap unanimously]!! | |
# | |
self.selenium = args[0] | |
# Print kwargs [if any] : Or they will go unused | |
logging.debug("kwargs:", kwargs) | |
@property | |
def is_aj_logo_displayed(self): | |
""" Check to see if main AJ logo is available """ | |
return self.check_page_element(self._HOMEPAGE_COMPANY_LOGO_LOCATOR) | |
@property | |
def is_current_page(self): | |
""" Checks if the currently opened page is as expected | |
Smoke test to see if viewport matches the active page class | |
""" | |
# Revamp the whole gamut | |
try: | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_all_elements_located(self._ALL_CDN_SCRIPT_LOCOS)) | |
elem_js = EC.presence_of_all_elements_located( | |
self._ALL_CDN_SCRIPT_LOCOS).__call__(self.selenium) | |
for each_js in elem_js: | |
logging.log(1, "\nELEM JS : >> " + str(each_js.tag_name) + " " + str(each_js.get_attribute("src"))) | |
return True | |
except Exception as exc: | |
print("EXC : ", exc) | |
return False | |
def go_to_page(self): | |
"""Instructs webdriver make a GET request to the page URL. | |
This method is blocking until the entire page loads. | |
""" | |
url = self._base_url + self.PATH | |
# print("\nURL -=> ", url) | |
self.selenium.get(url) | |
def refresh(self): | |
self.selenium.refresh() | |
def maximize(self): | |
self.selenium.maximize_window() | |
def go_to(self, path): | |
self.selenium.get(path) | |
@property | |
def get_current_url(self): | |
url = self.selenium.current_url | |
url = url[url.find('.com/')+4:] | |
return url | |
@property | |
def check_google_analytic_script(self): | |
source = self.selenium.page_source | |
soup = BeautifulSoup(source, 'html.parser') | |
script = soup.find_all('script') | |
ga_script = "ga('create', 'UA-52588259-1', 'auto');" | |
result = [] | |
for script_part in script: | |
if str(script_part).find(ga_script) != -1: | |
result.append(True) | |
else: | |
result.append(False) | |
if True in result: | |
return True | |
else: | |
return False | |
@property | |
def browser_title(self): | |
""" Returns the title of the browser window after page load. | |
The browser title may contain garbage from a previous page. | |
Ascertain that you are at the current page before querying | |
webdriver for the browser title. | |
""" | |
WebDriverWait(self.selenium, self._timeout).until( | |
lambda s: self.selenium.title) | |
return self.selenium.title | |
def get_page_source(self, locator=_FOCUS_TAG_LOCATOR): | |
"""Returns the text contained within the locator tag. | |
The page source contains all visible text on the page. | |
No HTML tags are included. | |
For the entire HTML page source, resort to the | |
*get_page_source* api of Selenium Webdriver. | |
""" | |
# String of element[0] | |
return str(self.get_text_of_elements(locator)[0]) | |
# | |
# Generic Input Functions for page interaction for inheriting classes | |
# | |
def click_on_element( | |
self, | |
locator=None, | |
index=None, | |
exit_path=EXIT_PATH_URL): | |
""" Generic function for clicking elements. (Range index version) | |
Parameters: | |
locator - The locator of page element(s) in a range | |
index - Position of element in range to be clicked | |
exit_path - URL to redirect to in case of error/failure | |
Returns: | |
click_result - The Boolean result of checking the page element | |
""" | |
click_result = False | |
try: | |
# print("\n 01 ICP") | |
# | |
# FIXME | |
# Some methods are breaking becoz of [is_current_page] | |
# - Mainly du2 3 page heavyweight elements expected 2b present | |
# | |
# assert self.is_current_page | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.element_to_be_clickable(locator)) | |
button_link = self.selenium.find_elements(*locator) | |
if index is None: | |
if len(button_link) > 1: | |
index = randint(0, len(button_link)-1) | |
else: | |
index = 0 | |
# Page functionalilites tend to react to different inputs, / | |
# depending on various factors outside of the tester's control | |
time.sleep(0.5) | |
self.get_text_of_elements() | |
button_link[index].click() | |
# if button_link[index].tag_name is not None: | |
click_result = True | |
finally: | |
# return True | |
return click_result | |
def click_on_non_clickable( | |
self, | |
locator=_FOCUS_TAG_LOCATOR, | |
index=None, | |
exit_path=""): | |
""" Generic function for clicking Non clickable elements. (Non click check version) | |
Parameters: | |
locator - The locator of page element(s) in a range | |
index - Position of element in range to be clicked | |
exit_path - URL to redirect to in case of error/failure | |
Returns: | |
click_result - The Boolean result of checking the page element | |
""" | |
click_result = False | |
try: | |
# print("\n 01 ICP") | |
# assert self.is_current_page | |
# print(" 02 P") | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
time.sleep(0.3) | |
# print(" 03 Find Elems, ", locator) | |
button_link = self.selenium.find_elements(*locator) | |
if index is None: | |
if len(button_link) > 1: | |
index = randint(0, len(button_link)-1) | |
else: | |
index = 0 | |
# print(" 04 Set index elem ", button_link[index]) | |
clicker = button_link[index] | |
# assert self.log_stall_loop(25) | |
# Page functionalilites tend to react to different inputs, / | |
# depending on various factors outside of the tester's control | |
# print(" 05 Create AC") | |
# action = ActionChains(self.selenium) | |
# action.move_to_element(clicker) | |
# action.click(clicker) | |
# time.sleep(0.3) | |
time.sleep(1) | |
# print("\nChek anaabled: ", clicker.is_enabled()) | |
# print("\nAboot to cleek : ", clicker) | |
# input() | |
clicker.click() | |
# print("What just happnedededed????") | |
# input() | |
click_result = True | |
# print("Aboot 2 click on it", action) | |
# action.perform() | |
# print("Did we click on it? Page says : ", click_result) | |
finally: | |
# return True | |
return click_result | |
def click_actionchain_clickable( | |
self, | |
locator=_FOCUS_TAG_LOCATOR, | |
index=None, | |
exit_path=""): | |
""" Generic function for clicking Non clickable elements. (Action Chain version) | |
Parameters: | |
locator - The locator of page element(s) in a range | |
index - Position of element in range to be clicked | |
exit_path - URL to redirect to in case of error/failure | |
Returns: | |
click_result - The Boolean result of checking the page element | |
""" | |
click_result = False | |
try: | |
# print("\n\n 01 ICP") | |
# # assert self.is_current_page | |
# print(" 02 P") | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
# # print(" 03 V") | |
# WebDriverWait(self.selenium, self._timeout).until( | |
# EC.visibility_of_element_located(locator)) | |
# print(" 04 Find Elems, ", locator) | |
button_link = self.selenium.find_elements(*locator) | |
if index is None: | |
if len(button_link) > 1: | |
index = randint(0, len(button_link)-1) | |
else: | |
index = 0 | |
# print(" 05 Set index elem ", button_link[index]) | |
clicker = button_link[index] | |
# Page functionalilites tend to react to different inputs, / | |
# depending on various factors outside of the tester's control | |
# print(" 06 Create AC") | |
action = ActionChains(self.selenium) | |
action.move_to_element(clicker) | |
action.click(clicker) | |
time.sleep(2) | |
# print(" 07 Aboot to perform AC") | |
action.perform() | |
# print(" 08 Aboot to check results of AC") | |
if clicker.tag_name is not None: | |
if clicker.is_enabled(): | |
# print(" 09.A Aboot to check results of AC") | |
click_result = True | |
finally: | |
# # return True | |
# print("\n XX - Final value of click result : ", click_result) | |
return click_result | |
def click_js_element(self, locator=_FOCUS_TAG_LOCATOR, index=None): | |
click_result = False | |
try: | |
print("Attempt to click on : ", index) | |
self.wait_it_out(3.0) | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
elems = self.selenium.find_elements(*locator) | |
if index is None: | |
index = self.select_random_index(locator) | |
if elems[index] is not None: | |
self.selenium.execute_script("arguments[0].focus(); return arguments[0].click();", elems[index]) | |
click_result = True | |
except Exception: | |
print("Exception : ", Exception) | |
return False | |
finally: | |
print("Click result : ", click_result) | |
return click_result | |
def send_enter_keys_to_element( | |
self, | |
locator=None, | |
index=None, | |
exit_path=EXIT_PATH_URL): | |
""" Specialized function for clicking elements. (Range index Enter version) | |
Parameters: | |
locator - The locator of page element(s) in a range | |
index - Position of element in range to be clicked | |
exit_path - URL to redirect to in case of error/failure | |
Returns: | |
click_result - The Boolean result of checking the page element | |
""" | |
click_result = False | |
try: | |
# assert self.is_current_page | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.visibility_of_element_located(locator)) | |
button_link = self.selenium.find_elements(*locator) | |
if index is None: | |
if len(button_link) > 1: | |
index = randint(0, len(button_link)-1) | |
else: | |
index = 0 | |
# Page functionalilites tend to react to different inputs, / | |
# depending on various factors outside of the tester's control | |
# | |
# # POSSIBLE COMBINATIONS OF CLICKING | |
# | |
# self.selenium.find_element(*self._FOCUS_TAG_LOCATOR).click() | |
# self.selenium.find_element(*self._FOCUS_TAG_LOCATOR).send_keys(Keys.ENTER) | |
# self.selenium.find_element(*self._FOCUS_TAG_LOCATOR).send_keys(Keys.RETURN) | |
# self.selenium.find_element(*self._FOCUS_TAG_LOCATOR).send_keys("\n") | |
# self.selenium.find_element(*self._FOCUS_TAG_LOCATOR).send_keys(Keys.CONTROL+Keys.RETURN) | |
# self.selenium.find_element(*self._FOCUS_TAG_LOCATOR).send_keys(Keys.CONTROL+Keys.ENTER) | |
time.sleep(0.6) | |
button_link[index].send_keys(Keys.ENTER) | |
click_result = True | |
finally: | |
# return True | |
return click_result | |
def select_from_dropdown( | |
self, | |
list_option_locator=_FOCUS_TAG_LOCATOR, | |
list_option_attribute="class", | |
index=None): | |
""" | |
Method 2 select option from Dropdown & return selection attribute | |
""" | |
element_ids = None | |
try: | |
self.check_page_element(list_option_locator) | |
element_ids = self.get_attribute_of_elements( | |
list_option_locator, list_option_attribute | |
) | |
# nose.tools.assert_is_not_none(element_ids) | |
if index is None: | |
if len(element_ids) > 1: | |
index = randint(0, len(element_ids)-1) | |
else: | |
index = 0 | |
if len(element_ids) > 0: | |
# print("\nDa joob link : ", element_ids[index]) | |
self.click_on_non_clickable( | |
list_option_locator, index | |
) | |
return element_ids[index] | |
finally: | |
return element_ids[index] | |
def enter_field_input( | |
self, | |
input_locator=_FOCUS_TAG_LOCATOR, | |
values="No Input", | |
exit_path=EXIT_PATH_URL): | |
""" Generic Input function to enter passed values into field element | |
Parameters: | |
input_locator - The form field element which will take input value | |
values - Sample values to simulate user input | |
exit_path - URL to redirect to in case of error/failure | |
""" | |
fill_result = False | |
try: | |
# print("\n 2 Field Present?") | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(input_locator)) # Present? | |
# print("\n 3 Field Visible?") | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.visibility_of_element_located(input_locator)) # Visible? | |
# # print("\n 4 Field Clickable?") | |
# WebDriverWait(self.selenium, self._timeout).until( | |
# EC.element_to_be_clickable(input_locator)) # Clickable? | |
name_field = self.selenium.find_element(*input_locator) | |
# print("\n 5 Get Field : ", name_field) | |
# print("\n 6 Click on field text") | |
# name_field.click() | |
time.sleep(0.5) | |
# print(self.get_text_of_elements()) | |
# input("Before send Keys") | |
name_field.send_keys(Keys.CONTROL + 'a') | |
name_field.send_keys(Keys.BACKSPACE) | |
# print("\n 9 Fill current values : ", values) | |
name_field.send_keys(str(values)) | |
# input("Done diss putin") | |
# print("\n 10 Find body tag") | |
# next_link = self.selenium.find_element(*self._FOCUS_TAG_LOCATOR) | |
# # # >> Safety checks | |
# # # >> Will work on input fields but not text areas | |
# # | |
# field_ip = self.get_attribute_of_elements(input_locator, 'value') | |
# # print("\n 10 Field input says : ", field_ip) | |
# if field_ip is not None: | |
# # print("\n 11 Field input Not n0ne", field_ip) | |
# for iput in field_ip: | |
# # print("\n 12 Field input part : ", iput) | |
# if str(values) in str(iput): | |
# # print("\n 13 We input : ", values, " and it shows :", iput) | |
# fill_result = True | |
# break | |
# if fill_result and name_field.is_enabled(): | |
# # print("\n 14 Fill result is : ", fill_result, " and Enabled shows :", name_field.is_enabled()) | |
fill_result = True | |
# print("\n Fill result is : ", fill_result) | |
except Exception as e: | |
print("\n Got exception, which is apparently : ") | |
print("\n", e) | |
finally: | |
# print("\n 14 Return fill_result, which is apparently : ", fill_result) | |
# input() | |
return fill_result | |
def enter_multiple_field_input( | |
self, | |
input_locator=_LOCATOR, | |
values="", | |
key_action=None, | |
exit_path=EXIT_PATH_URL): | |
""" Generic Form-field Input function | |
To enter passed values into given selected fields | |
""" | |
input_field = None | |
ipf_length = 0 | |
try: | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(input_locator)) # Present? | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.element_to_be_clickable(input_locator)) # Clickable? | |
input_field = self.selenium.find_elements(*input_locator) | |
if input_field is not None: | |
ipf_length = len(input_field) | |
for i in range(ipf_length): | |
input_field[i].send_keys(Keys.CONTROL + 'a') | |
input_field[i].send_keys(Keys.BACKSPACE) | |
input_field[i].send_keys(values[i]) | |
if key_action: | |
time.sleep(0.5) | |
input_field[i].send_keys(key_action) | |
return values[:ipf_length] | |
finally: | |
return values[:ipf_length] | |
def get_text_of_elements(self, locator=_FOCUS_TAG_LOCATOR, exit_path=EXIT_PATH_URL): | |
""" Returns list of text of element/s """ | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.visibility_of_element_located(locator)) | |
time.sleep(0.5) | |
element = self.selenium.find_elements(*locator) | |
if element is not None: | |
element_texts = [elem.text for elem in element] | |
return element_texts | |
# | |
def get_attribute_of_elements( | |
self, | |
locator=_FOCUS_TAG_LOCATOR, | |
attribute_name="class", | |
exit_path=EXIT_PATH_URL): | |
""" Returns list of attributes of element/s """ | |
try: | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
# WebDriverWait(self.selenium, self._timeout).until( | |
# EC.visibility_of_element_located(locator)) | |
time.sleep(0.2) | |
elements = self.selenium.find_elements(*locator) | |
element_attributes = [elem.get_attribute(attribute_name) for elem in elements] | |
return element_attributes | |
except TimeoutException: | |
raise TimeoutException | |
except NoSuchElementException: | |
raise NoSuchElementException | |
except Warning: | |
raise Warning | |
# | |
def get_page_element( | |
self, | |
locator=_FOCUS_TAG_LOCATOR): | |
""" Returns the python object representation of a web element """ | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
self.wait_it_out(2) | |
web_element = self.selenium.find_element(*locator) | |
return web_element | |
# | |
def get_page_elements( | |
self, | |
locator=_FOCUS_TAG_LOCATOR): | |
""" Returns a list of object representations of all web elements identified """ | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
self.wait_it_out(2) | |
web_elements = self.selenium.find_elements(*locator) | |
return web_elements | |
# | |
@staticmethod | |
def log_stall_loop(num): | |
rep = 0 | |
while rep < num: | |
logging.debug(".") | |
logging.info(".") | |
rep += 1 | |
if rep is num: | |
return True | |
else: | |
return False | |
# | |
# Assertion Check Generators : | |
# (Boolean status methods for Functionality/Element under Test) | |
# | |
# ######################################################################## | |
# | |
def check_page_element(self, locator=_LOCATOR, timeout=None): | |
""" Check to see if given WebElement is in place, present and visible | |
Parameters: | |
locator - The locator of page element to be checked | |
Returns: | |
check_result - The Boolean result of checking the page element | |
""" | |
check_result = False | |
try: | |
# print("\n Checking a page element with loco : ", locator) | |
# assert self.is_current_page | |
if timeout is None: | |
timeout = self._timeout | |
WebDriverWait(self.selenium, timeout).until( | |
EC.presence_of_element_located(locator)) | |
WebDriverWait(self.selenium, timeout).until( | |
EC.visibility_of_element_located(locator)) | |
self.wait_it_out(3) | |
element = self.selenium.find_element(*locator) | |
if element is not None: | |
if element.tag_name is not None: | |
if element.text is not None: | |
check_result = True | |
# print("\n Do you see it ? : \t", self.get_text_of_elements(locator)) | |
# print("\n Check result says : ", check_result) | |
return check_result | |
except Exception: | |
# print("\n Exception at ::>> LOCATOR == ", locator) | |
# print("\n Check result says : ", check_result) | |
return check_result | |
finally: | |
return check_result | |
def move_to_page_element(self, locator=_LOCATOR, index=None, timeout=None): | |
""" Move mouse over given WebElement if it's in place, present and visible | |
Parameters: | |
locator - The locator of page element to be checked | |
Returns: | |
check_result - Boolean result of moving the mouse over the page element | |
""" | |
check_result = False | |
try: | |
if timeout is None: | |
timeout = self._timeout | |
WebDriverWait(self.selenium, timeout).until( | |
EC.presence_of_element_located(locator)) | |
if locator is not self._LOCATOR: | |
self.wait_it_out(3) | |
elements = self.selenium.find_elements(*locator) | |
# print("\n Index is : ", index) | |
# print("\n Elems r : ", [elem.text for elem in elements]) | |
target_elem = elements[index] | |
# print("\n\n Elems[i] is : ", target_elem.text) | |
self.scroll_into_view(locator, index, 200) | |
ActionChains(self.selenium)\ | |
.move_to_element(target_elem)\ | |
.perform() | |
# print("\n Aboot to clickce ctara") | |
# self.click_on_element(locator, index) | |
self.wait_it_out(2) | |
# print("\n Working now ???") | |
check_result = True | |
# print("\n Do you see it ? : \t", self.get_text_of_elements(locator)) | |
# print("\n Check result says : ", check_result) | |
return check_result | |
except Exception: | |
# print("\n Exception at ::>> LOCATOR == ", locator) | |
# print("\n Check result says : ", check_result) | |
return check_result | |
finally: | |
# print("\n Move mouser Check result says : ", check_result) | |
return check_result | |
def check_input_results( | |
self, | |
required_msg="error", | |
as_expected=True, | |
text_locator=_FOCUS_TAG_LOCATOR, | |
exit_path=EXIT_PATH_URL): | |
""" Function to check if field returns the appropriate results for given input | |
[ Currently done by parsing Page Source for the presence | |
(or absence) of the appropriate related error message string ] | |
""" | |
check_result = False | |
# assert self.is_current_page | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(text_locator)) | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.visibility_of_element_located(text_locator)) | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.element_to_be_clickable(text_locator)) | |
# cgas = self.check_google_analytic_script | |
# if cgas is True: | |
# print(cgas) | |
time.sleep(0.3) | |
source = self.get_text_of_elements(text_locator) | |
# print("\n\n REQ: ", required_msg) | |
# print("\n\n SRC: ", source) | |
for text in source: | |
if (required_msg in text) is as_expected: | |
check_result = True | |
break | |
else: | |
check_result = False | |
if not check_result: | |
print("\n") | |
print("\nThe message : ", required_msg, ". . . Should it be there? : ", as_expected) | |
print("\nThe source : ", source) | |
return check_result | |
def click_on_back_button(self): | |
self.selenium.back() | |
def check_internal_frame( | |
self, | |
link_locator=None, | |
frame_locator=None, | |
exit_path=EXIT_PATH_URL, | |
index=None, timeout=None): | |
""" Check if the Internal Frame is properly visible after the Click event | |
Parameters: | |
link_locator - The internal link button to be clicked | |
frame_locator - The resulting internal page area expected from event | |
exit_path - URL to redirect to in case of error/failure | |
index - The selected position from within range | |
Returns: | |
check_result - The Boolean result of checking the Internal frame | |
""" | |
check_result = False | |
try: | |
# Click an element of specific index | |
click_result = self.click_js_element(link_locator, index) | |
self.wait_it_out(3) | |
# Check expected element/frame is present and visible | |
present_result = self.check_page_element(frame_locator, timeout) | |
check_result = click_result and present_result | |
finally: | |
return check_result | |
def check_same_page_link_works( | |
self, | |
sp_link_locator=None, | |
required_string="asaanjobs", | |
exit_path=EXIT_PATH_URL, | |
index=None): | |
""" Check if the Linked Page opens up in the Same Tab | |
Parameters: | |
sp_link_locator - The link to a page opening in the same tab | |
required_string - The conditional string to check in the linked page | |
exit_path - URL to redirect to in case of error/failure | |
index - The selected position from within range | |
Returns: | |
check_result - The Boolean result of checking for the Internal frame | |
""" | |
check_result = False | |
try: | |
# assert self.is_current_page | |
# print("\nAboot 2 Click on link") | |
len_before = len(self.selenium.window_handles) | |
# print("Window count B4 : ", len_before) | |
self.click_on_element(sp_link_locator, index, exit_path) | |
# self.click_js_element(sp_link_locator, index) | |
# print("Clicked on link") | |
len_after = len(self.selenium.window_handles) | |
self.selenium.switch_to_window(self.selenium.current_window_handle) | |
# print("Switched to current window {just to be careful} ") | |
# print("Window count AF : ", len_after) | |
self.wait_it_out(3) | |
if self.check_for_new_url(required_string, interval=2): | |
# print("Checked url of page for : ", required_string) | |
# and "asaanjobs" | |
check_result = True | |
else: | |
print("\n SPL") | |
print("\n REQ: ", required_string) | |
print("\n URL: ", self.selenium.current_url) | |
print("\n") | |
# check_result = False | |
finally: | |
# print("Window count Finally : ", len(self.selenium.window_handles)) | |
# print("\n Check result says : ", check_result) | |
return check_result | |
def check_new_page_link_works( | |
self, | |
np_link_locator=None, | |
required_string="asaanjobs", | |
exit_path=EXIT_PATH_URL, | |
index=None): | |
""" Check if the Linked Page opens up in a New Tab | |
Parameters: | |
np_link_locator - The link to a page opening in a new tab | |
required_string - The conditional string to check in the linked page | |
exit_path - URL to redirect to in case of error/failure | |
index - The selected position from within range | |
Returns: | |
check_result - The Boolean result of checking the Internal page link | |
""" | |
check_result = False | |
try: | |
# assert self.is_current_page | |
time.sleep(0.5) | |
# input("Aboot 2 Click on link") | |
self.click_on_element(np_link_locator, index, exit_path) | |
# input("Clickeed on link") | |
self.selenium.switch_to_window(self.selenium.window_handles[0]) | |
# input("Switched to old window") | |
self.selenium.close() | |
# input("Closed old window") | |
self.selenium.switch_to_window(self.selenium.window_handles[0]) | |
self.maximize() | |
# input("Switched to new window - which is now updated to 0") | |
if self.check_for_new_url(required_string, interval=2): | |
# and "asaanjobs" | |
check_result = True | |
else: | |
print("\n NPL") | |
print("REQ: ", required_string) | |
print("URL: ", str(self.selenium.current_url)) | |
check_result = False | |
finally: | |
return check_result | |
def check_for_new_url( | |
self, | |
expected_url_string=EXIT_PATH_URL, | |
interval=0.5, | |
max_limit=_timeout): | |
""" Generic Method to check until a new url is loaded, at given interval (in seconds) """ | |
check_result = False | |
cycle = 0.0 | |
max_limit = float(max_limit) | |
try: | |
# assert expected_url_string is not None | |
# assert self.is_current_page | |
while check_result is False and expected_url_string is not None: | |
time.sleep(interval) | |
cycle += interval | |
current_page_url = str(self.selenium.current_url) | |
if expected_url_string in current_page_url: | |
check_result = True | |
# print("\n\n We are now at URL : ", current_page_url) | |
self.wait_it_out(1) | |
return check_result | |
# break ? or continue ? | |
if cycle > max_limit: | |
print("\n Failed") | |
print("\n We want URL : ", expected_url_string) | |
print("\n We are now at URL : ", current_page_url) | |
return check_result | |
# EOIf | |
# EOW | |
finally: | |
return check_result | |
# EOT | |
# EOM | |
def check_new_window_link_works( | |
self, | |
nw_link_locator=None, | |
required_string="aasaanjobs", | |
exit_path=EXIT_PATH_URL, | |
index=None): | |
""" Check if the Linked Page opens up in a New window | |
Parameters: | |
nw_link_locator - The link to a page opening in a new window | |
required_string - The conditional string to check in the linked page | |
exit_path - URL to redirect to in case of error/failure | |
index - The selected position from within range | |
Returns: | |
check_result - The Boolean result of checking the Internal page link | |
""" | |
check_result = False | |
try: | |
# assert self.is_current_page | |
time.sleep(0.5) | |
# print("\nAboot 2 Click on link") | |
if index is None: | |
index = self.select_random_index(nw_link_locator) | |
# self.print_page_source() | |
self.click_on_element(nw_link_locator, index, exit_path) | |
# print("Clickeed on link") | |
self.selenium.switch_to_window(self.selenium.window_handles[1]) | |
# print("Switched to new window") | |
time.sleep(2) | |
print(self.selenium.current_url) | |
if self.check_for_new_url(required_string, interval=2): | |
# and "asaanjobs" | |
self.wait_it_out(1) | |
# self.print_page_source() | |
check_result = True | |
else: | |
print("\n NWL") | |
print("REQ: ", required_string) | |
print("URL: ", str(self.selenium.current_url)) | |
check_result = False | |
self.selenium.close() | |
# print("Closed new window") | |
self.selenium.switch_to_window(self.selenium.window_handles[0]) | |
# print("Switched to old window") | |
# self.print_page_source() | |
except Exception as exception_case: | |
print("\nException : ", exception_case) | |
finally: | |
return check_result | |
# Move to generic PageBase | |
# @property | |
def select_random_index(self, card_locator=_FOCUS_TAG_LOCATOR): | |
card_list = self.get_page_elements(card_locator) | |
self.wait_it_out(1) | |
card_count = len(card_list) | |
if card_count > 1: | |
index = randint(0, card_count-1) | |
else: | |
index = 0 | |
return index | |
def scroll_into_view(self, locator, index=0, scroll_val=100): | |
self.check_page_element(locator, timeout=25) | |
self.wait_it_out(1) | |
elems = self.selenium.find_elements(*locator) | |
if index is None: | |
index = self.select_random_index(locator) | |
self.selenium.execute_script("return arguments[0].scrollIntoView();", elems[index]) | |
self.selenium.execute_script("window.scrollBy(0, -" + str(scroll_val) + ");") | |
def check_page_has_scrolled(self, expected_scrollbar_pos, locator=_FOCUS_TAG_LOCATOR, index=None): | |
old_scrollbar_pos = self.selenium.execute_script("return window.scrollY;") | |
self.click_on_element(locator, index) | |
time.sleep(1.5) | |
new_scrollbar_pos = self.selenium.execute_script("return window.scrollY;") | |
print("\nOld scroll position : ", old_scrollbar_pos) | |
print("New scroll position : ", new_scrollbar_pos) | |
print("Expected scroll position : ", expected_scrollbar_pos) | |
check_result = abs(expected_scrollbar_pos - new_scrollbar_pos) < 30 | |
return check_result | |
def switch_to_new_window(self, wait_quantum=1, timeout=10): | |
check_result = False | |
window_count = 0 | |
window_wait = 0 | |
try: | |
while window_count < 2 or window_wait == timeout: | |
self.wait_it_out(wait_quantum) | |
window_wait += wait_quantum | |
window_count = len(self.selenium.window_handles) | |
# print("WC : ", str(window_count)) | |
if window_wait >= timeout: | |
check_result = False | |
else: | |
# print(self.selenium.window_handles[0]) | |
# print(self.selenium.window_handles[1]) | |
self.selenium.switch_to_window(self.selenium.window_handles[1]) | |
check_result = True | |
except Exception as exp: | |
print("\n\nException : ", exp) | |
return check_result | |
return check_result | |
def switch_to_old_window(self): | |
check_result = False | |
try: | |
before_count = len(self.selenium.window_handles) | |
self.selenium.close() | |
self.wait_it_out(3) | |
self.selenium.switch_to_window(self.selenium.window_handles[0]) | |
after_count = len(self.selenium.window_handles) | |
if before_count > after_count: | |
check_result = True | |
else: | |
check_result = False | |
except Exception as exp: | |
print("\n\nException : ", exp) | |
return check_result | |
return check_result | |
def switch_to_iframe(self, iframe_locator=_LOCATOR): | |
check_result = False | |
try: | |
iframe_elem = self.get_page_element(iframe_locator) | |
# self.selenium.close() | |
self.wait_it_out(1) | |
self.selenium.switch_to.frame(iframe_elem) | |
# print("\nNewPage SRC\n\n") | |
# self.print_page_source() | |
check_result = True | |
except Exception as exp: | |
print("\n\nException : ", exp) | |
return check_result | |
return check_result | |
def switch_to_mainframe(self): | |
check_result = False | |
try: | |
self.selenium.switch_to.parent_frame() | |
# print("\nOldPage SRC\n\n") | |
# self.print_page_source() | |
check_result = True | |
except Exception as exp: | |
print("\n\nException : ", exp) | |
return check_result | |
return check_result | |
@classmethod | |
def wait_it_out(cls, seconds=1.0): | |
time.sleep(seconds) | |
return True | |
def click_on_browser_back_button(self): | |
self.selenium.back() | |
def click_on_browser_forward_button(self): | |
self.selenium.forward() | |
def close_hopscotch_if_visible(self): | |
if self.check_page_element(self._HOPSCOTCH_CLOSE_BUTTON_LOCATOR, 10): | |
return self.click_on_element(self._HOPSCOTCH_CLOSE_BUTTON_LOCATOR) | |
else: | |
return True | |
def print_page_source(self): | |
source = self.get_text_of_elements() | |
for text in source: | |
print(text, "\n") | |
assert source is not None | |
def drag_element_using_offset(self, locator, x_offset=0, y_offset=0): | |
click_result = False | |
try: | |
WebDriverWait(self.selenium, self._timeout).until( | |
EC.presence_of_element_located(locator)) | |
button_link = self.selenium.find_element(*locator) | |
action = ActionChains(self.selenium) | |
action.drag_and_drop_by_offset(button_link, x_offset, y_offset) | |
action.perform() | |
if button_link.tag_name is not None: | |
if button_link.is_enabled(): | |
click_result = True | |
finally: | |
return click_result | |
@property | |
def accept_javascript_alert(self): | |
click_result = False | |
try: | |
self.wait_it_out(2) | |
alert = self.selenium.switch_to.alert | |
alert.accept() | |
click_result = True | |
finally: | |
return click_result | |
@staticmethod | |
def clean_str(kword): | |
""" | |
Returns a stripped, case-insensitive stringified version of kword [ideal for comparisons] | |
""" | |
return str(kword).strip().casefold() | |
@staticmethod | |
def which_proficiency(edu_level): | |
""" | |
Returns a Proficiency level [int] denoting the education level | |
""" | |
pro = AbstractBasePage.clean_str(edu_level) | |
if pro == 'not specified': | |
pro_level = 0 | |
elif pro == '10th': | |
pro_level = 1 | |
elif pro == '12th': | |
pro_level = 2 | |
elif pro == 'under graduation': | |
pro_level = 3 | |
elif pro == 'graduation': | |
pro_level = 4 | |
elif pro == 'post graduation': | |
pro_level = 5 | |
else: | |
pro_level = -1 | |
return pro_level | |
def set_prod_config(self): | |
""" Static method to change Page object attributes to production_login_test values """ | |
# | |
self._base_url = self.PROD_EXIT_PATH_URL | |
# self.API_URL = self.PROD_API_URL | |
# self.BEARER_TOKEN = self.PROD_BEARER_TOKEN | |
# | |
self._CANDIDATE_MOBILE = self._PROD_CANDIDATE_MOBILE | |
self._CANDIDATE_PASSWORD = self._PROD_CANDIDATE_PASSWORD | |
# | |
self._PARTNER_EMAIL = self._PROD_PARTNER_EMAIL | |
self._PARTNER_PASSWORD = self._PROD_PARTNER_PASSWORD | |
# | |
# API Call methods : | |
# (Backend API Http request method calls to retrieve essential data) | |
# | |
# ######################################################################## | |
# | |
def get_user_id_staging(self, mobile_email): | |
header = {'Authorization': self.BEARER_TOKEN} | |
req_user = requests.get( | |
self.API_URL+'/api/v4/recognize_user/?username='+str(mobile_email), headers=header) | |
time.sleep(2) | |
print("\n\n", self.API_URL+'/api/v4/recognize_user/?username='+str(mobile_email), header) | |
req_user = req_user.json() | |
print("\n\n", req_user) | |
return req_user['id'] | |
def get_user_id(self, mobile_email): | |
header = {'Authorization': self.PROD_BEARER_TOKEN} | |
req_user = requests.get( | |
self.PROD_API_URL+'/api/v4/recognize_user/?username='+str(mobile_email), headers=header) | |
time.sleep(2) | |
print("\n\n", self.PROD_API_URL+'/api/v4/recognize_user/?username='+str(mobile_email), header) | |
req_user = req_user.json() | |
print("\n\n", req_user) | |
return req_user['id'] | |
def generate_user_otp_codes(self, user_id, reset_code_type="L"): | |
header = {'Authorization': self.PROD_BEARER_TOKEN} | |
body_data = {"reset_code_type": str(reset_code_type)} | |
code_gen_results = requests.post( | |
self.PROD_API_URL+'/api/v4/user/' + | |
user_id+'/generate_otp/', | |
headers=header, | |
data=body_data).json() | |
if code_gen_results['id']: | |
if code_gen_results['id'] is not None: | |
return True | |
else: | |
return False | |
def get_user_password_otp_staging(self, mobile_email): | |
user_id = self.get_user_id_staging(mobile_email) | |
header = {'Authorization': self.BEARER_TOKEN} | |
reset_code_results = requests.get(self.API_URL + '/api/v4/user/' + user_id + '/activation_code/', | |
headers=header).json() | |
time.sleep(4) | |
pass_otp_code = reset_code_results['password_otp'] | |
activation_otp = reset_code_results['activation_otp'] | |
login_otp = reset_code_results['login_otp'] | |
return pass_otp_code, activation_otp, login_otp | |
def get_user_password_otp_prod(self, mobile_email): | |
user_id = self.get_user_id(mobile_email) | |
header = {'Authorization': self.PROD_BEARER_TOKEN} | |
reset_code_results = requests.get(self.PROD_API_URL+'/api/v4/user/'+user_id+'/activation_code/', | |
headers=header).json() | |
time.sleep(4) | |
pass_otp_code = reset_code_results['password_otp'] | |
activation_otp = reset_code_results['activation_otp'] | |
login_otp = reset_code_results['login_otp'] | |
print(pass_otp_code, activation_otp, login_otp) | |
return pass_otp_code, activation_otp, login_otp | |
def get_manager_otp_codes(self, mobile_email, reset_type="L"): | |
# otp_types = ['password', 'activation', 'login'] | |
user_id = self.get_user_id(mobile_email) | |
otp_genrated = self.generate_user_otp_codes(user_id, reset_type) | |
self.wait_it_out(1) | |
reset_code_results = None | |
if otp_genrated: | |
reset_code_results = self.get_user_password_otp_prod(mobile_email) | |
# print("\nWe have these results: \n") | |
# for res in reset_code_results, otp_types: | |
# print(res) | |
return reset_code_results | |
def logout_user(self): | |
try: | |
self.selenium.get(self._base_url+"/accounts/logout/") | |
return True | |
except: | |
print("There was a problem in logging out") | |
return False | |
def get_cand_users(self): | |
cand_mobs = [] | |
api_params = self.API_URL+'/api/v4/candidate/?filter={"and":{' \ | |
'"user.mobile_verified":{"eq":"true"},' \ | |
'"user.email_verified":{"eq":"true"},' \ | |
'"is_assessed":{"eq":"true"},' \ | |
'"is_profiled":{"eq":"true"}}}' \ | |
'&limit=100' | |
print(api_params) | |
header = {'Authorization': self.BEARER_TOKEN} | |
cand_data = requests.get(api_params, headers=header) | |
self.wait_it_out(2) | |
candudut = cand_data.json() | |
for each_cando in candudut['objects']: | |
cand_mobs.append(each_cando['_source']['user']['mobile']) | |
return cand_mobs | |
# def check_spelling_mistakes_of_a_text(self, lang, locator_text): | |
# error_list = [] | |
# my_dict = DictWithPWL(lang, os.getcwd()+'/'+self.MY_WORDS_FILE_NAME) | |
# my_checker = SpellChecker(my_dict, filters=[EmailFilter]) | |
# my_checker.set_text(locator_text) | |
# for error in my_checker: | |
# # print("ERROR:", error.word) | |
# error_list.append(error.word) | |
# return error_list | |
# def spell_checker(self, locator=None): | |
# locator_text = [] | |
# lang_list = ['en_US', 'en_GB', 'en_IN'] | |
# if locator is None: | |
# locator = [self._SPELLING_CHECKER1_LOCATOR, self._SPELLING_CHECKER2_LOCATOR] | |
# for elem in locator: | |
# print(self.get_text_of_elements(elem)) | |
# locator_text.append(' '.join(self.get_text_of_elements(elem))) | |
# locator_text = ' '.join(locator_text).replace('\n', ' ') | |
# us_error = self.check_spelling_mistakes_of_a_text(lang_list[0], locator_text) | |
# gb_error = self.check_spelling_mistakes_of_a_text(lang_list[1], locator_text) | |
# in_error = self.check_spelling_mistakes_of_a_text(lang_list[2], locator_text) | |
# error_list = [err for err in us_error if err in gb_error and err in in_error] | |
# error_list = list(set(error_list)) | |
# print('us -->', us_error, 'gb -->', gb_error, 'in -->', in_error, 'tot -->', error_list) | |
# with open('spelling_mistakes.csv', 'a') as csv_out: | |
# writer = csv.writer(csv_out) | |
# for key in error_list: | |
# writer.writerow([key+' '+self.selenium.current_url]) | |
# return len(error_list) | |
@property | |
def get_3_complete_functional_area(self): | |
req_user = requests.get(self.PROD_API_URL + '/api/v4/fa/?limit=30&offset=0') | |
print(req_user) | |
all_fa = req_user.json()['objects'] | |
print(all_fa) | |
job_role = [] | |
for elem in all_fa: | |
if elem['name'].title() in ['Drilling Operator', 'Bartender', 'Carpenter']: | |
pass | |
else: | |
job_role.append(elem['name'].title()) | |
job_role = list(set(job_role)) | |
return job_role | |
@property | |
def get_verified_production_org_name(self): | |
org_names = [] | |
org_pop_names = [] | |
api_params = self.PROD_API_URL + '/api/v4/organization?filter={"and":{' \ | |
'"status":{"eq":"O_A"},' \ | |
'"org_pricing_stats.is_paid_client":{"eq":"true"},' \ | |
'"org_pricing_stats.total_paid_int_recharge":{"gt":0}}}' \ | |
'&order_by=-modified' | |
header = {'Authorization': self.PROD_BEARER_TOKEN} | |
org_req = requests.get(api_params, headers=header) | |
self.wait_it_out(2) | |
org_data = org_req.json() | |
for org in org_data['objects']: | |
org_names.append(org['_source']['name']) | |
org_pop_names.append(org['_source']['popular_name']) | |
return list(zip(org_names, org_pop_names)) | |
class Meta: | |
""" Just a meta class for base test """ | |
abstract = True | |
def scroll_to_top(self): | |
self.selenium.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.HOME) | |
def select_using_select(self, locator, value): | |
return Select(self.selenium.find_element(*locator)).select_by_value(value) | |
# EOC | |
# Created by AsadK on 08/01/16 | |
# Last Edited by AsadK on 08/03/17 - 4:03pm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment