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"
Related
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')
I have written a python script that communicates with the web page and makes an online order. In addition to that I have added some GUI, which allows the user to select the day of the order. Here is the python script
import easygui
import sys
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import tkinter as tk
import tkinter.font as tkFont
badge_number = 111111
# Widget pop up for selection of the order day
root = tk.Tk()
def center_window(w=300, h=200):
# get screen width and height
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate position x, y
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.geometry("400x450")
Label = tk.Label(root, text = "Select lunch Order Day", font = ("Helvetica", 15))
Label.pack(pady=50, padx=40)
helv15 = tkFont.Font(family = "Helvetica", size = 15)
root.lift()
v = tk.StringVar()
v.set("Today")
tk.Label(root, textvariable = v).pack()
def close_window():
root.destroy()
today = tk.Radiobutton(root, text = "Today", variable = v, value = "Today", font = helv15).pack()
tomorrow = tk.Radiobutton(root, text = "Tomorrow", variable = v, value = "Tomorrow", font = helv15).pack()
cancel = tk.Radiobutton(root, text = "Cancel", variable = v, value = "Cancel", font = helv15).pack()
submit = tk.Button(root, text = "Submit", command = close_window, font = helv15).pack()
center_window(400, 400)
root.mainloop()
if v.get() == "Cancel":
sys.exit("Ordering was terminated")
driver = webdriver.Chrome(executable_path = "C:\webdrivers\chromedriver.exe")
driver.get("http://web_page/")
element = driver.find_element_by_name('employee_id')
element.send_keys(badge_number)
driver.find_element_by_xpath("/html/body/section/header/form/div/button").click()
# /html/body/section/header/form/div/button
delay = 60
todayBut = "/html/body/section/div[1]/div[2]/div/div/div/span[2]/span[1]/form/button"
tomorBut = "/html/body/section/div[1]/div[2]/div/div/div/span[1]/span[1]/form/button"
favorButToday = "/html/body/section/div/div[1]/button"
favorButTomor = "/html/body/section/div/div[1]/button/a"
myFavOrderID = "fav_order_view"
try:
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, todayBut)))
except TimeoutException:
print ("Loading Day Selection page took too much time!")
if v.get() == "Today":
driver.find_element_by_xpath(todayBut).click()
#favorite choice
try:
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, favorButToday)))
driver.find_element_by_xpath(favorButToday).click()
try:
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, myFavOrderID)))
driver.find_element_by_id(myFavOrderID).click()
### select floor, order date and order now
select_floor = Select(driver.find_element_by_name("floor_number"))
select_floor.select_by_index("9")
select_day = Select(driver.find_element_by_name("order_date"))
select_day.select_by_value("today")
orderNowBtn = "/html/body/div[1]/div[2]/div/div/div[3]/form/button"
driver.find_element_by_xpath(orderNowBtn).click()
print("Today's order was successfully made!")
except TimeoutException:
print ("Loading Favorites page took too much time!")
except TimeoutException:
print ("Loading took too much time!")
else:
driver.find_element_by_xpath(tomorBut).click()
#favorite choice
try:
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, favorButTomor)))
driver.find_element_by_xpath(favorButTomor).click()
try:
myFavOrderIDTomor = "fav_order_view"
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, myFavOrderIDTomor)))
driver.find_element_by_id(myFavOrderIDTomor).click()
### select floor, order date and order now
select_floor = Select(driver.find_element_by_name("floor_number"))
select_floor.select_by_index("9")
select_day = Select(driver.find_element_by_name("order_date"))
select_day.select_by_value("tomorrow")
orderNowBtnTomor = "/html/body/div[1]/div[2]/div/div/div[3]/form/button"
driver.find_element_by_xpath(orderNowBtnTomor).click()
print("Tomorrow's order was successfully made!")
except TimeoutException:
print ("Loading Favorites page took too much time!")
except TimeoutException:
print ("Loading took too much time!")
However, I wanted to have it as an .exe file to run it with just double-click from my desktop. So, I have installed pyinstaller from git and run the simple line in the cmd (pyinstaller.exe --onefile --windowed --icon=app.ico LunchOrder.py). Unfortunately, the .exe isn't doign anything, it just pops up the "Fatal error detected" message, without any GUI (that I have written into the script itself). Any help would be appreciated!
Here i will tell you a better way to make .py to .exe . First make sure your python is added to system PATH, which i assume is. If not check some tutorials on how to add python to PATH then you can open your cmd and type in:
pip install pyinstaller
After this, you go to your path where the LunchOrder.py exists and open a cmd there, in windows you can type simply type in cmd in the address bar (after clearing adressbar), or else open a cmd and navigate to your path where LunchOrder.py file exists and simply type in:
pyinstaller -w -F -i "app.ico" LunchOrder.py
This should make a folder dist inside which your .exe will be there. MAKE SURE TO COPY THE .exe to outside the dist folder and run it there. Or else you might still get fatal error message. You can delete all the other extra files that was generated like build and LunchOrder.spec . If it still gives you error try following this method https://www.youtube.com/watch?v=OZSZHmWSOeM
I'm trying to save a website as PDF through printing dialog. My code allows me to save as pdf, but asks me to input a filename, which I don't know how to pass a filename to the pop up box.
Attached is my code:
import time
from selenium import webdriver
import os
class printing_browser(object):
def __init__(self):
self.profile = webdriver.FirefoxProfile()
self.profile.set_preference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", False)
self.profile.set_preference("pdfjs.disabled", True)
self.profile.set_preference("print.always_print_silent", True)
self.profile.set_preference("print.show_print_progress", False)
self.profile.set_preference("browser.download.show_plugins_in_list",False)
foxdriver = r'C:\Users\AShen\Documents\Workspace\geckodriver.exe'
self.driver = webdriver.Firefox(executable_path=foxdriver,firefox_profile = self.profile)
time.sleep(5)
def get_page_and_print(self, page):
self.driver.get(page)
time.sleep(5)
self.driver.execute_script("window.print();")
if __name__ == "__main__":
browser_that_prints = printing_browser()
browser_that_prints.get_page_and_print('http://www.google.com/')
These days I had the same question.
I solved it without using the pyautogui in these case, because I use different PCs and monitors and I didn't want to depend on the position of the click.
I was able to solve it using the about:config... changing them with each necessary print (in PDF).
The name of my printer "in PDF" in Ubuntu is "Print to File" (defined in print_printer) and the settings of about:config need to be this printer...
For example: print.printer_Print_to_File.print_to_file: true
import os
import time
from selenium import webdriver
class printing_browser(object):
def __init__(self):
self.profile = webdriver.FirefoxProfile()
self.profile.set_preference('services.sync.prefs.sync.browser.download.manager.showWhenStarting', False)
self.profile.set_preference('pdfjs.disabled', True)
self.profile.set_preference('print.always_print_silent', True)
self.profile.set_preference('print.show_print_progress', False)
self.profile.set_preference('browser.download.show_plugins_in_list', False)
self.profile.set_preference('browser.download.folderList', 2)
self.profile.set_preference('browser.download.dir', '')
self.profile.set_preference('browser.download.manager.showWhenStarting', False)
self.profile.set_preference('browser.aboutConfig.showWarning', False)
self.profile.set_preference('print.print_headerright', '')
self.profile.set_preference('print.print_headercenter', '')
self.profile.set_preference('print.print_headerleft', '')
self.profile.set_preference('print.print_footerright', '')
self.profile.set_preference('print.print_footercenter', '')
self.profile.set_preference('print.print_footerleft', '')
self.profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream;application/vnd.ms-excel;text/html')
foxdriver = r'C:\Users\AShen\Documents\Workspace\geckodriver.exe'
self.driver = webdriver.Firefox(
executable_path=foxdriver,
firefox_profile=self.profile
)
time.sleep(1)
def get_page_and_print(self, page, filepath):
# Get about:config
self.driver.get('about:config')
time.sleep(1)
# Define Configurations
script = """
var prefs = Components.classes['#mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setBoolPref('print.always_print_silent', true);
prefs.setCharPref('print_printer', 'Print to File');
prefs.setBoolPref('print.printer_Print_to_File.print_to_file', true);
prefs.setCharPref('print.printer_Print_to_File.print_to_filename', '{}');
prefs.setBoolPref('print.printer_Print_to_File.show_print_progress', true);
""".format(filepath)
# Set Configurations
self.driver.execute_script(script)
time.sleep(1)
# Get site to print in pdf
self.driver.get(page)
time.sleep(2)
self.driver.execute_script("window.print();")
browser_that_prints = printing_browser()
browser_that_prints.get_page_and_print('http://www.google.com', os.path.join(os.getcwd(), 'mywebpage.pdf'))
Oh, it is very easy if you know about pyautogui.
This is an amazing module that allows you to automate your curser.
So essentially, you need to figure out the place where the popup appears and use pyautogui to click it for you.
All you need to add is:
time.sleep(3)
i=random.randint(0,1000)
file_name=('name_pdf '+str(i))
print (file_name)
pyautogui.typewrite(file_name)
pyautogui.click(512,449)
Entire code structure will look like this:
import time
import pyautogui
from selenium import webdriver
import os
class printing_browser(object):
def __init__(self):
self.profile = webdriver.FirefoxProfile()
self.profile.set_preference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", False)
self.profile.set_preference("pdfjs.disabled", True)
self.profile.set_preference("print.always_print_silent", True)
self.profile.set_preference("print.show_print_progress", False)
self.profile.set_preference("browser.download.show_plugins_in_list",False)
foxdriver = r'C:\Users\Pranjal Pathak\Desktop\Titanic Kaggle\geckodriver.exe'
self.driver = webdriver.Firefox(executable_path=foxdriver,firefox_profile = self.profile)
time.sleep(5)
def get_page_and_print(self, page):
self.driver.get(page)
time.sleep(5)
self.driver.execute_script("window.print();")
if __name__ == "__main__":
browser_that_prints = printing_browser()
browser_that_prints.get_page_and_print('http://www.python.org/')
time.sleep(3)
i=random.randint(0,1000)
file_name=('name_pdf '+str(i))
print (file_name)
pyautogui.typewrite(file_name)
pyautogui.click(512,449)
Note: 1. I have selected the name of the file as name+any random integer between 1 to 1000 to change name every time you save the file. This way it will save every time you run the code as the names will be different every time.
If this types the name but does not save the file, you might want to change the coordinates of your curser. Let me know if that happens.
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")))
My python script is listed:
==========================================
class ExampleTestCase(unittest.TestCase):
capabilities = None
def setUp(self):
self.driver = webdriver.Remote(desired_capabilities={ "browserName": broswer, "platform": platform, "node": node })
def test_example(self):
self.driver.get("www.360logica.com")
self.assertEqual(self.driver.title, "360logica")
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
#unittest.main()
args = sys.argv
port = args[1]
platform = args[2]
broswer = args[3]
suite = unittest.TestSuite()
suite.addTest(ExampleTestCase("test_example"))
runner = XMLTestRunner(file('results_ExampleTestCase_%s.xml' % (broswer), "w"))
runner.run(suite)
==============================================
The run command as:
$ ./python.exe Grid_1.py 5555 WINDOW firefox
==============================================
The build error log is:
$ ./python.exe Grid_1.py 5555 WINDOW firefox
Traceback (most recent call last):
File "Grid_1.py", line 31, in <module>
suite.addTest(ExampleTestCase("test_example"))
File "C:\Python27\Lib\unittest\case.py", line 191, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class '__main__.ExampleTestCase'>: test_example
===================================================
Please help me. I am so headache with that build error and don't know how to fix it.
You have suite.addTest(ExampleTestCase("test_example")), but your def is outside the scope of the class (if it is indeed your indentation). Make sure that test_example is part of the class.
class ExampleTestCase(unittest.TestCase):
capabilities = None
def setUp(self):
self.driver = webdriver.Remote(desired_capabilities={ "browserName": broswer, "platform": platform})
def test_example(self):
self.driver.get("www.360logica.com")
self.assertEqual(self.driver.title, "360logica")
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
#unittest.main()
args = sys.argv
port = args[1]
platform = args[2]
broswer = args[3]
suite = unittest.TestSuite()
suite.addTest(ExampleTestCase("test_example"))
runner = XMLTestRunner(file('results_ExampleTestCase_%s.xml' % (broswer), "w"))
runner.run(suite)
python substring.py 5555 WINDOW firefox
This ends up dumping the results (as expected) as results_ExampleTestCase_firefox.xml