I started selenium-server-standalone-2.29.0 server. I have python 2.7. I also downloaded selenium package. When I run this script I expect Firefox should be launched. But nothing happens. Am I missing something?
import unittest,selenium
class NewTest(unittest.TestCase):
def setUp(self):
self.selenium = selenium("localhost", 4444, "*firefox",
"http://www.google.com/")
self.selenium.start()
def test_new(self):
self.selenium.open("/")
selenium.type("q","selenium rc")
def tearDown(self):
self.selenium.stop()
Perhaps something like this instead?
import unittest
from selenium import webdriver
class NewTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def test_new(self):
self.browser.get("http://www.google.com")
elem = self.browser.switch_to_active_element()
elem.send_keys('some search query')
def tearDown(self):
self.browser.quit()
Note, for testing stuff like this, I would err to use BDD testing (perhaps with lettuce) instead...
Related
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class CorrecaoEfetivaNota(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome('/Users/r13/dev/chromedriver')
def teste_login_avaliador(self):
driver = self.driver
driver.get("")
cpf = driver.find_element_by_xpath('//input[#placeholder="CPF"]')
cpf.send_keys("")
password = driver.find_element_by_xpath('//input[#placeholder="SENHA"]')
password.send_keys("")
login = driver.find_element_by_tag_name('button')
login.click()
driver.implicitly_wait(3)
def teste_buscar_mais_um(self):
driver = self.driver
buscar = driver.find_element_by_xpath("//section[1]/div/div/section[2]/div/div/div[1]/div/div[2]/button")
buscar.click()
def tearDown(self):
self.driver.close()
I'm trying to write this tests in Python, the first function is ok, but the second one inside the class is not being executed in the tests. How can I organize this?
While working with Python and unittest module with Selenium you have to consider a few facts as follows :
Indentation for class and test_method are different.
Instead of driver.close() always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.
If you are using unittest module you have to call the __main__.
Here is your own code with the required minor modifications which will execute the first method teste_login_avaliador() as well as the second method teste_buscar_mais_um() within the Class CorrecaoEfetivaNota():
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class CorrecaoEfetivaNota(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r'C:\WebDrivers\chromedriver.exe')
def teste_login_avaliador(self):
driver = self.driver
driver.get("http://d3dyod5mwyu6xk.cloudfront.net/")
cpf = driver.find_element_by_xpath('//input[#placeholder="CPF"]')
cpf.send_keys("27922797885")
password = driver.find_element_by_xpath('//input[#placeholder="SENHA"]')
password.send_keys("enccejaregular")
login = driver.find_element_by_tag_name('button')
login.click()
driver.implicitly_wait(3)
def teste_buscar_mais_um(self):
driver = self.driver
buscar = driver.find_element_by_xpath("//section[1]/div/div/section[2]/div/div/div[1]/div/div[2]/button")
buscar.click()
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
Note: Though both the test_methods are being called still you will face the following exception:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//section[1]/div/div/section[2]/div/div/div[1]/div/div[2]/button"}
At the line:
buscar = driver.find_element_by_xpath("//section[1]/div/div/section[2]/div/div/div[1]/div/div[2]/button")
This exception can be solved easily following the actual Test Steps of your usecase and if required you can raise a new question/ticket.
You write that the first function is ok, which I assume must be the setUp() function you are referring to (provided that in your code you indented correctly).
As Andersson comments, your unittest methods needs to begin with "test_" not "teste_". Providing "test_" is your way of telling unittest that this method should be tested.
In your unittest you probably also want to test something such as self.assertEqual(1,1) otherwise your tests will pass no matter what.
Next time please provide us with a more thorough description of what is wrong. How did you make the call to unittest? What error is python giving you? What result did you expect? Etc. It makes solving your problem much faster.
I encourage you to make a simple test first and ensure that it runs:
import unittest
class TestingUnittest(unittest.TestCase):
def setUp(self):
print("SetUp called")
def tearDown(self):
print("tearDown called")
def test_Method(self):
print("Testing 1==1")
self.assertEqual(1,1)
Call this from your terminal:
>>>python -m unittest "name-of-test.py"
In my PyCharm editor I have a test_suite.py file and a functions.py file. In the functions file I have written a Class to establish a Chrome webdriver and a separate class to establish the Firefox webdriver. In this file I am currently copy/pasting every function for the firefox section to the chrome section as well and I am worried that this will create a massive page of test cases that is not properly organized.
Functions.py file looks like:
import libraries
from libraries import *
import ini
from ini import *
class ChromeBase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.base_url = baseurl
self.verificationErrors = []
self.accept_next_alert = True
self.driver.implicitly_wait(3)
def testcase1(self):
global resultfail
resultfail = 'unable to do what you want'
try:self.driver.find_element_by_link_text("sign in").click()
except failed() as e: self.verificationErrors.append(str(e))
def testcase2(self):
self.signin('test#user.com', 'xxx')
def testcase3(self):
self.driver.set_window_size(1920, 1020)
self.signin('test2#user.com', 'xxx')
class baseline(unittest.TestCase):
def setUp(self):
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', os.path.join(os.path.expanduser("~"), "Downloads\\"))
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv, application/octet-stream')
self.driver = webdriver.Firefox(profile)
self.base_url = baseurl
self.verificationErrors = []
self.accept_next_alert = True
self.driver.implicitly_wait(3)
def testcase1(self):
global resultfail
resultfail = 'unable to do what you want'
try:self.driver.find_element_by_link_text("sign in").click()
except failed() as e: self.verificationErrors.append(str(e))
def testcase2(self):
self.signin('test#user.com', 'xxx')
def testcase3(self):
self.driver.set_window_size(1920, 1020)
self.signin('test2#user.com', 'xxx')
And in my test_suite file I am calling the different webdrivers as such:
class TestCase(baseline):
def test_case1(self):
print('testcase1')
self.driver.get(self.base_url)
self.testcase1()
self.testcase2()
self.testcase3()
class TestCase(ChromeBase):
def test_case1(self):
print('testcase1')
self.driver.get(self.base_url)
self.testcase1()
self.testcase2()
self.testcase3()
Can I organize the project in my PyCharm editor to be easily readable and to call on different Webdrivers in a neat manner?
How would I go about doing this so that when I click the green Play button i can manage whether to run the cases for all web browsers or for just a specific web browser?
Cheers
I am writing a program in python that will generate more robust data and reports from Selenium tests. I want to be able to export a test case from Selenium IDE from Firefox, and without modifying that specific exported python file, inject it into my script and allow my script to make modifications such as changing the webdriver (part of the implementation is for a Nagios server, which will use PhantomJS as the driver) and pulling request information and screenshots for reporting (Btw, I know I can change the driver in the IDE template, but it's just an example).
Lets say I have a file exported from the IDE path/to/mytests/search.py:
import...
class Search(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.base_url = 'http://www.example.com'
def test_search(self):
driver = self.driver
driver.get(self.base_url)
elem = self.driver.find_element_by_name('q')
elem.send_keys('nagios')
elem.send_keys(Keys.RETURN)
assert 'No results found.' not in self.driver.page_source
driver.get(self.base_url + '/status')
assert 'OK' in self.driver.page_source
def tearDown(self):
self.driver.quit()
I want my script to be able to do this:
python -m my_wrapper mytests.search --url 'http://www.google.com'
Which will somehow import search.py, create a new testcase from it, and allow me to override the setUp/tearDown methods (changing the driver to PhantomJS, modifying the base URL from the sys.argv), and allow for catching errors and writing information related to where a failed test might have stopped (since there are two different URL calls, a screenshot of that page will be exported for wherever the driver is currently at).
I'm thinking something like my_wrapper.__main__:
# get 'mytests.search' from argparse
dirname, module = os.path.split('mytests.search'.replace('.', '/'))
suite = unittest.TestLoader().discover(dirname, pattern='%s.py' % module)
# Modify testcases here <-- THIS IS THE HARD PART
#
# Is there a way to inject the tests into another testCase class?
#
# class BaseClass(unittest.TestCase):
# def setUp(self):
# self.driver = webdriver.PhantomJS()
# ...
#
# def runTest(self): pass
#
# def tearDown(self): ...
#
# then...
new_suite = unittest.TestSuite()
for sub_suite in master_suite: #<-- iterating over the above suite here
for tests in sub_suite._tests: #<-- why do you have to do this twice?
for test_name in tests._tests:
# This doesn't work but show's my thought process
mytest = BaseClass(methodName=test_name)
setattr(mytest, test_func, getattr(tests, test_name))
new_suite.addTest(mytest)
try:
result = unittest.TextTestRunner(verbosity=2).run(new_suite)
except (SOME_SELENIUM_ERROR):
# get the screenshot, save to file <-- don't know how to do this either
Anyway, any help into this would be appreciated. I would really like to keep this code as simple as possible using as much of what's available as I can.
Note: Other than selenium and PhantomJS, I'm also wary of using other dependencies like non-standard libraries, etc, for a number of policy reasons.
...
Hi my friend i have been searchin something like this for few days. I found this question in stackoverflow
Python unittest passing arguments
so you code should be like this:
import sys
import unittest
class Search(unittest.TestCase):
URL = ""
def setUp(self):
self.driver = webdriver.Firefox()
self.base_url = 'http://www.example.com'
def test_search(self):
driver = self.driver
driver.get(self.base_url)
elem = self.driver.find_element_by_name('q')
elem.send_keys('nagios')
elem.send_keys(Keys.RETURN)
assert 'No results found.' not in self.driver.page_source
driver.get(self.base_url + '/status')
assert 'OK' in self.driver.page_source
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
Search.URL=sys.argv.pop()
unittest.main()
I hope this is what you was looking for.
to execute you should do:
python mySearchTest.py "http://example.com"
I'm attempting to pass parameters to unittest subclass methods. Please forgive my ignorance - I've only started coding in Python a few days ago. I could obviously just hardcode the parameters in the subclass itself but that would eliminate its reuse with other username/password combos. When I run run_tests.py below, I get the error "TypeError: runTest() takes exactly 3 arguments (4 given)".
Here is run_tests.py:
from selenium import webdriver
import unittest
from testcases import login
def my_suite():
suite = unittest.TestSuite()
suite.addTest (login.Login().runTest("username1", "password1", "page title"))
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(my_suite())
Here is testcases/basetestcase.py:
from selenium import webdriver
import unittest
class BaseTestCase (unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://website"
def tearDown(self):
self.driver.quit()
Here is testcases/login.py
import common_page_elements
from basetestcase import BaseTestCase
class Login (BaseTestCase):
def runTest(username, password, verification):
""" Test logging in. """
driver = self.driver
driver.get(self.base_url)
driver.find_element_by_id(common_page_elements.textfield_username).clear()
driver.find_element_by_id(common_page_elements.textfield_username).send_keys(username)
driver.find_element_by_id(common_page_elements.textfield_password).clear()
driver.find_element_by_id(common_page_elements.textfield_password).send_keys(password)
driver.find_element_by_name(common_page_elements.button_submit).click()
self.assertTrue(verification in self.driver.title)
Since runTest has become a class method, you'll have to include the self argument:
class Login (BaseTestCase):
def runTest(self, username, password, verification):
^^^^
I'm trying to retrieve the session id of a selenium webdriver session during the execution of a test as such:
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def testSomething(self):
"""selenium tests go here"""
self.driver.get('http://www.example.com')
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
testResult = unittest.TextTestRunner(verbosity=2).run(suite)
session_id = ???
I know I could do self.driver.session_id side the setUp method. The problem is I need to get the session id outside of the class instance. Any ideas?
Probably, you can create property/function inside the class instance which could return you sessionID.