I am writing my first Python Selenium page factory and am getting an error regarding my waits.
My code is as follows
Basepage Class
class Basepage():
browser = None
def __init__(self, browser):
self.browser = browser
self.base_url = config.url
def wait_for_element(self, *element):
WebDriverWait(self.browser, 10).until(
EC.presence_of_element_located(*element)
)
def click_element(self, *element):
self.browser.find_element(*element).click()
def find_element(self, *element):
self.browser.find_element(*element)
CreatePage Class
class CreatePage(Basepage):
def isat_createpage(self):
self.wait_for_element(*CreatePageLocators.add_computer_title)
text = self.find_element(*CreatePageLocators.add_computer_title).text
if text == "Add a computer":
return True
else:
return False
Behave Step
#then('the user will be navigated to "Create_Computer" page')
def step_impl(context):
page = CreatePage(context.browser)
assert page.isat_createpage(), "not at ADD Computer page"
Locator I am using for the item
class CreatePageLocators:
add_computer_title = (By.XPATH, "//*[#id=\"main\"]/h1")
I am getting the error
Scenario: User can open Create Computer screen # features/UI_Tests/Create.feature:8
Given A user has navigated to the BB_Test_Webpage # steps/Backbase_common_steps.py:6
And add a new computer is clicked # steps/Backbase_common_steps.py:11
Then the user will be navigated to "Create_Computer" page # steps/web_create_steps.py:5
Traceback (most recent call last):
File "c:\users\richard.cariven\python\lib\site-packages\behave\model.py", line 1329, in run
match.run(runner.context)
File "c:\users\richard.cariven\python\lib\site-packages\behave\matchers.py", line 98, in run
self.func(context, *args, **kwargs)
File "steps\web_create_steps.py", line 8, in step_impl
assert page.isat_createpage(), "not at ADD Computer page"
File "C:\Users\richard.cariven\Documents\Backbase_Test_RC\modules\pages\createpage.py", line 15, in isat_createpage
self.wait_for_element(*CreatePageLocators.add_computer_title)
File "C:\Users\richard.cariven\Documents\Backbase_Test_RC\modules\pages\basepage.py", line 23, in wait_for_element
EC.presence_of_element_located(*element)
TypeError: __init__() takes 2 positional arguments but 3 were given
I imagine I am doing something very simple wrong. But help greatly appreciated
If you check the error it is mentioned about positional arguments.
EC.presence_of_element_located(*element)
TypeError: init() takes 2 positional arguments but 3 were given
Change the following inside function like that add one more parenthesis.
def wait_for_element(self, *element):
WebDriverWait(self.browser, 10).until(
EC.presence_of_element_located((By.XPATH, "//*[#id='main']/h1")))
Related
I have multiple py files with unit tests specified for specific module.
I want to import these unittests to seperate py file and run them from there, but I have trouble getting it working.
example of one of the unittest:
from webdriver_manager.chrome import ChromeDriverManager
from to_import import acceptConsent, URL_poznavacky, URL_poznavacky_vikendy, URL_poznavacky_rodiny, URL_pobocky
import time
from selenium import webdriver
import unittest
class TestPobocky_D(unittest.TestCase):
def setup_method(self, method):
self.driver = webdriver.Chrome(ChromeDriverManager().install())
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_pobocky_D(self):
self.driver.get(URL_pobocky)
acceptConsent(self.driver)
self.driver.maximize_window()
time.sleep(2)
mapa = self.driver.find_element_by_xpath("//*[#class='leaflet-pane leaflet-tile-pane']") ## jen jeden element, no need to call find_elementS
mapaDisplayed = mapa.is_displayed()
assert mapaDisplayed == True
mapaKolecka = self.driver.find_elements_by_xpath("//*[#class='leaflet-marker-icon marker-cluster marker-cluster-medium leaflet-zoom-animated leaflet-interactive']")
y=0
for _ in mapaKolecka:
mapaKoleckaDisplayed = mapaKolecka[y].is_displayed()
y=y+1
print("mapa kolecka")
assert mapaKoleckaDisplayed == True
pobockaBoxiky = self.driver.find_elements_by_xpath("//*[#class='f_branch-header f_anchor']")
x=0
for _ in pobockaBoxiky:
pobockaBoxikyDisplay = pobockaBoxiky[x].is_displayed()
print("boxiky")
assert pobockaBoxikyDisplay == True
x=x+1
basicInfo = self.driver.find_elements_by_xpath("//*[#class='f_branch-basicInfo']")
a=0
for _ in basicInfo:
basicInfoDisplay = basicInfo[a].is_displayed()
print("basic info ")
assert basicInfoDisplay == True
a=a+1
I want to import the whole class TestPobocky_D to new file and run it in seperate py file. I tried following:
import unittest
from pobocky import TestPobocky_D
TestPobocky_D(unittest.TestCase)
that just gives me this error
"Traceback (most recent call last):
File "C:/Users/KDK/Desktop/Automation_Local_Deploy_PyCharm/starter_local.py", line 4, in <module>
TestPobocky_D(unittest.TestCase)
File "C:\Users\KDK\anaconda3\lib\unittest\case.py", line 433, in __init__
testMethod = getattr(self, methodName)
TypeError: getattr(): attribute name must be string"
Anyone who can help me with this please ? Or point me to the right direction how to go about this.
Thanks in advance for every response
Can you please try as below?
starttest.py
import unittest
from pobocky import TestPobocky_D
if __name__ == '__main__':
unittest.main(argv=[''],verbosity=2, exit=False)
Run the command "python -m unittest starttest.py"
I have tried to do some unit tests using Selenium guide:
https://selenium-python.readthedocs.io/page-objects.html
Also find this youtube tutorial but, this didn't help:
https://www.youtube.com/watch?v=O_sIPPA4euw
And suddenly, I'm stuck on error and I can't handle this. Error:
Urz╣dzenie do│╣czone do komputera nie dzia│a. <- Its says "Device conected to pc don't work"
DevTools listening on ws://127.0.0.1:59733/devtools/browser/b08ba32b-aab7-4000-a232-17ee5f8ee262
[2412:14716:0131/030125.624:ERROR:disk_cache.cc(185)] Unable to create cache
[15264:6784:0131/030127.670:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[15264:6784:0131/030127.671:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[15264:6784:0131/030127.671:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[15264:10740:0131/030127.672:ERROR:device_event_log_impl.cc(214)] [03:01:27.672] USB: usb_device_handle_win.cc:1050 Failed to read descriptor from node connection: Urz╣dzenie do│╣czone
do komputera nie dzia│a. (0x1F)
[15264:10740:0131/030127.673:ERROR:device_event_log_impl.cc(214)] [03:01:27.673] USB: usb_device_handle_win.cc:1050 Failed to read descriptor from node connection: Urz╣dzenie do│╣czone
do komputera nie dzia│a. (0x1F)
[15264:6784:0131/030127.685:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
E
======================================================================
ERROR: test_login (__main__.LoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\thein\PycharmProjects\socialMeUp\main\tests\main.py", line 16, in test_login
login.search_username = "admin"
File "C:\Users\thein\PycharmProjects\socialMeUp\main\tests\element.py", line 7, in __set__
WebDriverWait(driver, 100).until(
File "C:\Users\thein\PycharmProjects\socialMeUp\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 78, in until
value = method(self._driver)
File "C:\Users\thein\PycharmProjects\socialMeUp\main\tests\element.py", line 8, in <lambda>
lambda d: driver.find_elemnt_by_name(self.locator))
AttributeError: 'WebDriver' object has no attribute 'find_elemnt_by_name'
Code:
main.py
import time
import unittest
from selenium import webdriver
import page
class LoginTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(r"E:\operadriver\chromedriver.exe")
self.driver.get('http://127.0.0.1:8000/')
def test_login(self):
login = page.LoginPage(self.driver)
time.sleep(3)
login.search_username = "admin"
login.search_password = "haslo"
time.sleep(3)
login.click_login()
time.sleep(3)
assert login.is_login()
def tearDown(self):
self.driver.close()
if __name__ == '__main__':
unittest.main()
page.py:
from locator import LoginPageLocator, MainPageLocator
from element import BasePageElement
class SearchUsername(BasePageElement):
locator = "username"
class SearchPassword(BasePageElement):
locator = "password"
class BasePage(object):
def __init__(self, driver):
self.driver = driver
class MainPage(BasePage):
def is_title_matches(self):
return "Python" in self.driver.title
def click_add_photo(self):
element = self.driver.find_element(*MainPageLocator.ADD_PHOTO)
element.click()
class LoginPage(BasePage):
search_username = SearchUsername()
search_password = SearchPassword()
def is_login(self):
return 'Profile' in self.driver.page_source
def click_login(self):
element = self.driver.find_element(*LoginPageLocator.SUBMIT_BUTTON)
element.click()
element.py
from selenium.webdriver.support.ui import WebDriverWait
class BasePageElement(object):
def __set__(self, obj, value):
driver = obj.driver
WebDriverWait(driver, 100).until(
lambda d: driver.find_elemnt_by_name(self.locator))
driver.find_elemnt_by_name(self.locator).clear()
driver.find_elemnt_by_name(self.locator).send_keys(value)
def __get__(self, obj, owner):
driver = obj.driver
WebDriverWait(driver, 100).until(
lambda d: driver.find_elemnt_by_name(self.locator))
element = driver.find_elemnt_by_name(self.locator)
return element.get_attribute("value")
locator.py
from selenium.webdriver.common.by import By
class MainPageLocator(object):
ADD_PHOTO = (By.NAME, 'addPhoto')
class LoginPageLocator(object):
SUBMIT_BUTTON = (By.NAME, 'submit_button')
in my project i have to send a numpy board in Instagram dm , sendMessage() funtion works fine i can send str message but can not send that i have created by numpy , please help me
THANKS in advance
My Code
from time import sleep
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\saksh\\Desktop\\codeing\\Projects\\Connect 4\\chrome profiles\\chrome profile - 1")
browser = webdriver.Chrome(options = options , executable_path = r"C:\Users\saksh\Desktop\codeing\imported items\chromedriver v-90.exe")
ROW_COUNT = 6
COLUMN_COUNT = 7
def create_board():
board = np.zeros((ROW_COUNT, COLUMN_COUNT))
return board
def send_board(board):
board = str(np.flip(board, 0))
board = board.replace("0", "🔳")
board = board.replace("1", "🟢")
board = board.replace("2", "⚫")
board = create_board()
def sendMessage(message , browser):
message_box = browser.find_element_by_css_selector(".ItkAi > textarea:nth-child(1)")
message_box.send_keys(message)
message_box.Keys.ENTER
# manually go u any instagram dm
# manually go u any instagram dm
print("manually go u any instagram dm , and press enter")
input("press enter !!")
sleep(5)
sendMessage(send_board(board) , browser)
ERROR
raceback (most recent call last):
File "c:\Users\saksh\Desktop\codeing\Projects\Connect 4\temp1.py", line 46, in
sendMessage(send_board(board) , browser)
File "c:\Users\saksh\Desktop\codeing\Projects\Connect 4\temp1.py", line 35, in sendMessage
message_box.send_keys(message)
File "C:\Users\saksh\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webelement.py", line 478, in send_keys
{'text': "".join(keys_to_typing(value)),
File "C:\Users\saksh\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\common\utils.py", line 150, in keys_to_typing
for i in range(len(val)):
TypeError: object of type 'NoneType' has no len()
From the error trace it's quite clear that in this block
def sendMessage(message , browser):
message_box = browser.find_element_by_css_selector(".ItkAi > textarea:nth-child(1)")
message_box.send_keys(message)
message_box.Keys.ENTER
This line
message_box.send_keys(message)
fails since the message is of NoneType.
That means that you passing there a NoneType object.
This is because you are calling this method by
sendMessage(send_board(board) , browser)
but the send_board method doesn't return a value / object.
So you actually send nothing, NoneType object to sendMessage method as a message to be inserted into the message_box element.
I am new to appium python client and need your suggestions to solve my below issue.PFA uiautomator viewer screen shot.Not sure if this is the reason: after typing into email field, a keyboard opens up so password and sign in button are not located
I have downloaded a free sample xxx.apk and created below script to test it:
class CareZoneAndroidTests(unittest.TestCase):
"Class to run tests against the Care Zone app"
def setUp(self):
"Setup for the test"
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '4.2'
desired_caps['deviceName'] = 'Android Emulator'
# Returns abs path relative to this file and not cwd
desired_caps['app'] = os.path.abspath(os.path.join(os.path.dirname(__file__),'D:/Programs/myapp/CareZone_v6.6.0.0 (flagship)_apkpure.com.apk'))
desired_caps['appPackage'] = 'com.carezone.caredroid.careapp.medications'
desired_caps['appActivity'] = 'com.carezone.caredroid.careapp.ui.activity.LandingActivity'
self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
def tearDown(self):
"Tear down the test"
self.driver.quit()
def test_login(self):
"Test the Login Page launches correctly"
self.driver.implicitly_wait(120)
print "After WAIT----------------->>>>>>>"
#Click on Sign in button
element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_toolbar_action")
self.driver.implicitly_wait(15)
element.click()
element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_mail_edit")
self.driver.implicitly_wait(10)
element.click()
element.send_keys("abc#ini.com");
element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_password_edit")
element.click()
element.send_keys("abc");
self.driver.implicitly_wait(10)
#element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_bton")
#element = self.driver.find_element_by_accessibility_id('Sign In')
element = self.driver.find_element_by_android_uiautomator('new UiSelector().text("Sign In")')
element.click()
Issue:
test_login (main.CareZoneAndroidTests) Test the Login Page
launches correctly ... After WAIT----------------->>>>>>> ERROR
====================================================================== ERROR: test_login (main.CareZoneAndroidTests) Test the Login Page
launches correctly
---------------------------------------------------------------------- Traceback (most recent call last): File
"D:\Programs\myapp\CareZoneTests.py", line 42, in test_login
element = self.driver.find_element_by_android_uiautomator('new UiSelector().text("Sign In")') File
"D:\Programs\Python275\lib\site-packages\appium\webdriver\webdriver.py",
line 133, in find_element_by_android_uiautomator
return self.find_element(by=By.ANDROID_UIAUTOMATOR, value=uia_string) File
"D:\Programs\Python275\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 752, in find_element
'value': value})['value'] File "D:\Programs\Python275\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 236, in execute
self.error_handler.check_response(response) File "D:\Programs\Python275\lib\site-packages\appium\webdriver\errorhandler.py",
line 29, in check_response
raise wde NoSuchElementException: Message: An element could not be located on the page using the given search parameters.
Tried below but all are failing for the same reason:
element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_bton")
element = self.driver.find_element_by_accessibility_id('Sign In')
element = self.driver.find_element_by_android_uiautomator('new
UiSelector().text("Sign In")')
Try to find element by ID :
element = self.driver.find_element_by_id('Sign In')
updated :
Try to put hidekeyboard(); before doing the action of selection an element in order to hide your keyboard !
Below code worked fine for me:
class CareZoneAndroidTests(unittest.TestCase):
"Class to run tests against the Care Zone app"
def setUp(self):
"Setup for the test"
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '4.2'
desired_caps['deviceName'] = 'Android Emulator'
# Returns abs path relative to this file and not cwd
desired_caps['app'] = os.path.abspath(os.path.join(os.path.dirname(__file__),'D:/Programs/myapp/CareZone_v6.6.0.0 (flagship)_apkpure.com.apk'))
desired_caps['appPackage'] = 'com.carezone.caredroid.careapp.medications'
desired_caps['appActivity'] = 'com.carezone.caredroid.careapp.ui.activity.LandingActivity'
self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
def tearDown(self):
"Tear down the test"
self.driver.quit()
def test_login(self):
"Test the Login Page launches correctly"
self.driver.implicitly_wait(120)
print "Sign in Page"
element = self.driver.find_element_by_xpath("//android.widget.TextView[#text='Have an account? Sign In']")
self.driver.implicitly_wait(15)
element.click()
element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_mail_edit")
element.click()
element.send_keys("ja.i#c.com");
self.driver.implicitly_wait(3)
self.driver.keyevent(61)
element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_password_edit")
element.click()
element.send_keys("ni");
self.driver.implicitly_wait(3)
print "Click TABS 2 times to get Sign In button-->>>>>>>"
self.driver.keyevent(61)
self.driver.keyevent(61)
element = self.driver.find_element_by_id("com.carezone.caredroid.careapp.medications:id/welcome_page_sign_bton")
element.click()
self.driver.implicitly_wait(120)
print "TEST OK"
I have a problem in class inheritance in Python; maybe it's not related to inheritance, but I have no other idea. I'm working with selenium web-driver. Here's the code I use:
from selenium import webdriver
class UIInterface(object):
def __init__(self):
self.driver = webdriver.Ie()
self.driver.get('URL')
def parentMethod(self, itemClassName = ''):
allElements = self.getAllElements()
return [el for el in allElements if el.get_attribute('type') == 'checkbox']
def getAllElements(self):
return self.driver.find_elements_by_tag_name('input')
class InterfaceChild(UIInterface):
def __init__(self):
super(InterfaceChild, self).__init__()
def childMethod(self):
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
for item in returnedList:
print item.get_attribute('innerHTML')
This code gives me an error for line returnedList = self.parentMethod(itemClassName = 'SomeClassName'); the error description is this:
(<type 'exceptions.AttributeError'>, AttributeError("'InterfaceChild' object has no attribute 'self'",), <traceback object at 0x000000000418E5C8>)
I thought it might be related to inheritance, so I tried to put parentMethod and getAllElements in the class InterfaceChild; same exception raised. Any idea about this??
EDIT 1:
This is the main method for making instance of classes:
if __name__ == '__main__':
ieInterface = InterfaceChild()
ieInterface.childMethod()
This is the complete stack-trace:
Traceback (most recent call last):
File "C:\Program Files\Eclipse\eclipse-jee-helios-win32\eclipse-jee-helios-win32\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1446, in <module>
debugger.run(setup['file'], None, None)
File "C:\Program Files\Eclipse\eclipse-jee-helios-win32\eclipse-jee-helios-win32\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1092, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "D:\workspace\testCode.py", line 133, in main
ieInterface.childMethod()
File "D:\workspace\testCode.py", line 33, in childMethod
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
File "D:\workspace\testCode.py", line 45, in parentMethod
allElements = self.getAllElements()
AttributeError: 'InterfaceChild' object has no attribute 'self'
I installed selenium with pip under Python 2.7 and changed the code to use Chrome driver[1] instead and changed the checker to make sure there would be some input tags being found. full code below. I'm running the code on Mac OS X. it works just fine.
So I guess the issue here is not the code. (Windows is not a friend of Python, perhaps :).
from selenium import webdriver
class UIInterface(object):
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('http://duckduckgo.com')
def parentMethod(self, itemClassName = ''):
allElements = self.getAllElements()
result = [el for el in allElements]
print('===', result)
return result
def getAllElements(self):
return self.driver.find_elements_by_tag_name('input')
class InterfaceChild(UIInterface):
def __init__(self):
super(InterfaceChild, self).__init__()
def childMethod(self):
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
for item in returnedList:
print item.get_attribute('innerHTML')
if __name__ == '__main__':
ieInterface = InterfaceChild()
ieInterface.childMethod()
The output looks like:
('===', [<selenium.webdriver.remote.webelement.WebElement object at 0x10e145cd0>, <selenium.webdriver.remote.webelement.WebElement object at 0x10e145d10>, <selenium.webdriver.remote.webelement.WebElement object at 0x10e145d50>])
[1] http://chromedriver.storage.googleapis.com/index.html?path=2.9/