Error: Writing tests in Python using selenium - python

I am trying to write a automation test using selenium and python webdriver
class UserAccountsTest(unittest.TestCase):
def setup(self):
self.driver=webdriver.Firefox()
def testFirstUser(self):
driver = self.driver
driver.implicitly_wait(15)
driver.get('website.com')
driver.implicitly_wait(15)
My error:
object has no attribute 'driver'
Im not sure why I can't assign driver to self.driver. Am I passing in self correctly?

You need to call your setup() function setUp() as described in unittest wiki.
Luckily, we can factor out such set-up code by implementing a method
called setUp(), which the testing framework will automatically call
for us when we run the test

Related

How to include test classes with init in a Pytest test suite?

I'm trying to create a test suite with pytest and Selenium using Page Object Models for pattern designing. For using my page classes on my tests, I just imported them inside my TestClass __init__ method, since they need to instanced with a driver.
I know that, by default, pytest ignores classes with an __init__ method. I also know, by reading here that it's possible to configure where pytest collects tests. Is it also possible to make it consider class tests with __init__, instead of returning an "Empty Suite" error?
#pytest.fixture(scope="session")
def driver_init(request):
from selenium import webdriver
driver = webdriver.Chrome()
session = request.node
page = PageFunctions(driver)
login_page = LoginPage(driver)
registration_page = RegistrationPage(driver)
for item in session.items:
cls = item.getparent(pytest.Class)
setattr(cls.obj, "driver", driver)
setattr(cls.obj, "page", page)
setattr(cls.obj, "login", login_page)
setattr(cls.obj, "registration", registration_page)
Pytest and Unittest have some different conventions. Mixing the two in the same test function is usually worth avoiding.
If you're working exclusively with Pytest, you would pass in your fixtures as arguments to your test function, e.g.:
import pytest
from selenium import webdriver
#pytest.fixture
def driver():
driver = webdriver.Chrome()
return driver
def test_func(driver):
# `driver` is found by pytest in the fixture above and
# automatically passed in
request = ... # Instantiate your request (not in your included code)
session = request.node
page = PageFunctions(driver)
login_page = LoginPage(driver)
registration_page = RegistrationPage(driver)
# Make some assertions about your data, e.g.:
assert page is not None
You haven't included all of the object definitions/imports so it's hard to see what you're trying to accomplish with the test, but hopefully that gives you an idea of the pytest conventions.

Robot Framework: How to use User created browser instance in Robot framework

I have created a python code to initialise a chrome browser and I want to pass this driver instance to Robot Framework so that the keywords of RF will work on this instance. Please let me know how could i do the same.
The Py code for intializing a file is :
'class SeleniumKeywords:
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self):
self.driver = None
def open_browser(self, browser="chrome"):
driver_class = drivers[browser]
self.driver = driver_class()
def go_to(self, url):
self.driver.get(url)'
Now when using it in Robot framework, the browser opens but the RF keywords doesnt work on it(selenium2library keywords). Basically I opening an browser instance using the custom keyword and maximizing using selenium2library keywords in RF. Unfortunately it doesnt work. Please let me know how to pass this browser instance to RF:
'*** Settings ***
Library ExtendedSelenium2Library
Library ../Resources/SeleniumKeywords.py
Resource ../Global/GlobalConfig.robot
*** Test Cases ***
Reuse Session ID
SeleniumKeywords.Open Browser chrome
maximize browser window
SeleniumKeywords.Go To ${URL} '
The maximize browser window is a RF keyword and I want it to work on my browserinstance
I have written my own library, but I extended the Selenium2Library and i can mix the Selenium2Library keywords with my own. The Selenium2Library or in your case, the ExtendedSelenium2Library will not recognize the session you just started in Python and will give the "No browser is open" error. The "Maximize Browser Window" keyword relies on a browser that was previoulsy opened with the "Open Browser" keyword.
If you really need your own Selenium library, you can do something like this:
class SeleniumKeywords(ExtendedSelenium2Library):
def go_to(self, url, browser="chrome"):
self.open_browser(url, browser)

Trouble getting python selenium tests to run

I am creating an automation framework from scratch using selenium with python and would really like some input and advice on the best way to do so.
So far I have the following but my test script will not run. Please help!
script.py
from selenium import webdriver
class WebDriver(object):
def __init__(self, driver=None):
"""
__init__ setup webdriver test script class
"""
self.driver = driver
def setup(self):
self.driver = webdriver.Chrome()
def teardown(self):
self.driver.quit()
test.py
import script
class Test(script.WebDriver):
def search(self):
self.driver.get("www.google.com")
self.driver.find_element_by_id("lst-ib").clear()
I'm assuming you are trying to run this with python unittest. If so, your class should inherit from unittest.TestCase in order to mark that it contains test cases:
class WebDriver(unittest.TestCase)
...
class Test(script.WebDriver)
And second missing piece is "boiler plate code to run the test suite" (see explanation here) in test.py:
if __name__ == "__main__":
test.main()

selenium test not opening a browser django

I am trying to run a selenium test and this seems nothing happening. I tested the following code to make sure the setting was working: the firefox browser loaded as it is expected.
In functional_tests.py
browser = webdriver.Firefox()
broswer.get('http://localhost:8000')
But when I changed it to as follows:
import unittest
from selenium import webdriver
class NewVistorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
self.browser.quit()
def test_can_open_browser(self):
self.browser.get('http://localhost:8000')
self.assertIn('Test', self.browser.title)
It was not opening the browser, nothing was happening. I ran this python functional_tests.py
What is the best way to organize unit tests and selenium tests. I'd like to run it by module name, not all in tests.py or test_abc.py, not by nose.
How do you expect it to run? Python won't automatically run tests, just because they're in a class. You need to add a couple more lines to the end of your file:
class NewVistorTest(unittest.TestCase):
...
if __name__ == '__main__':
unittest.main(warnings='ignore')
This conditional is how a Python script checks if it has been executed from the command line, rather than just imported by another script. We call unittest.main() to launch the unittest test runner, which will automatically find test and methods in the file and run them.
Without that block, as you've seen, nothing happens.

Closing the webdriver instance automatically after the test failed

My English is very poor but I'll try my best to describe the problem I encountered.
I used selenium webdriver to test a web site and the language that I used to write my script is python.Because of this,I used Pyunit.
I know that if my test suite have no exceptions,the webdriver instance will be closed correctly,(by the way, I used chrome) however,once a exception was threw,the script will be shut down and I have to close chrome manually.
I wonder that how can I achieved that when a python process quits , any remaining open WebDriver instances will also be closed.
By the way, I used Page Object Design Pattern,and the code below is a part of my script:
class personalcenter(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.page = personalCenter(self.driver,"admin","123456")
def testAddWorkExp(self):
blahblahblah...
def tearDown(self):
self.page.quit()
self.driver.quit()
if __name__ == "__main__":
unittest.main()
I haved searched the solution of this problem for a long time ,but almost every answer is depended on java and junit or testNG.How can I deal with this issue with Pyunit?
Thanks for every answer.
From the tearDown() documentation:
Method called immediately after the test method has been called and
the result recorded. This is called even if the test method raised an
exception, so the implementation in subclasses may need to be
particularly careful about checking internal state. Any exception
raised by this method will be considered an error rather than a test
failure. This method will only be called if the setUp() succeeds,
regardless of the outcome of the test method. The default
implementation does nothing.
So, the only case where tearDown will not be called is when setUp fails.
Therefore I would simply catch the exception inside setUp, close the driver, and re-raise it:
def setUp(self):
self.driver = webdriver.Chrome()
try:
self.page = personalCenter(self.driver,"admin","123456")
except Exception:
self.driver.quit()
raise
Hope!! this will help you. you might need to close the driver with boolean expression as False
from selenium import webdriver
import time
class Firefoxweb(object):
def __init__(self):
print("this is to run the test")
def seltest(self):
driver=webdriver.Chrome(executable_path="C:\\Users\Admin\PycharmProjects\Drivers\chromedriver.exe")
driver.get("URL")
driver.find_element_by_xpath("//*[#id='btnSkip']").click()
driver.find_element_by_xpath("//*[#id='userInput']").send_keys("ABC")
driver.find_element_by_xpath("//*[#id='passwordInput']").send_keys("*******")
driver.find_element_by_xpath("//*[#id='BtnLogin']").click()
driver.close(False)
FF=Firefoxweb()
FF.seltest()

Categories