How to Conditionally Skip tearDown for Webdriver tests - python-3.x

I'm making a few simple selenium tests using Python 3 and the unittest module. I'm wondering if there is a way to not run the tearDown function between every test? I understand I could simply omit the tearDown completely from the class, but this will not return results on every test result. Also, if I were to write the 2nd test where the first test leaves off, I am given an exception stating that the Safari instance is already paired with another WebDriver Session.
Below is my current code. In the following example, I basically write the second test, containing the steps from the first. This is what I'd like to avoid.
import unittest
from selenium import webdriver
import time
class Login_Tests(unittest.TestCase):
username = 'XXXX'
password = 'XXXX'
def setUp(self):
self.driver = webdriver.Safari()
def test_1_LogIn(self):
driver = self.driver
driver.get('PRIVATE URL')
driver.maximize_window()
driver.find_element_by_id('j_id0:eCommerceSiteTemplate:j_id14:username').send_keys(self.username)
driver.find_element_by_id('j_id0:eCommerceSiteTemplate:j_id14:password').send_keys(self.password, '\n')
time.sleep(4)
element = driver.find_element_by_xpath('//*[#id="globalHeaderNameMink"]/span/text()').text
self.assertIn('Chris GExecutive', element)
def test_2_Store_Load(self):
driver = self.driver
driver.get('PRIVATE URL')
driver.maximize_window()
driver.find_element_by_id('j_id0:eCommerceSiteTemplate:j_id14:username').send_keys(self.username)
driver.find_element_by_id('j_id0:eCommerceSiteTemplate:j_id14:password').send_keys(self.password, '\n')
time.sleep(4)
driver.find_element_by_css_selector(
'#bodyCell > div:nth-child(9) > table > tbody > tr:nth-child(3) > td:nth-child(4) > h2 > a').click()
time.sleep(5)
elem = driver.find_element_by_css_selector(
'body > div.container.hidden-phone.deskLayout > header > div.row-fluid.headerRow > '
'div > div.top_navigation > p > span > span.loginoutsec > a').text
self.assertIn('Logout', elem)
def tearDown(self):
self.driver.close()
self.driver.quit()
if __name__ == "__main__":
unittest.main()

You really don't want to do that. Each test should be independent and a full test. If you find that you are repeating code in multiple tests then you should start using the page object model or create some functions so you can increase your code reuse.

Related

Send arguments to Pytest fixture for Selenium

Update1:
Thank you for your answer.
It almost solves the problem. If I could be more precise:
How to instantiate the two drivers in 'init_pages', instead of creating two same methods for each driver?
The new snippet as you suggested:
#pytest.mark.usefixtures("driver_init")
class BaseTestFF:
#pytest.fixture
def init_data(self, driver_init):
self.web_driver = driver_init('firefox') #how to inject data via external commands? jenkins?
self.web_driver2 = driver_init('chrome')
#pytest.fixture(autouse=True)
#pytest.mark.usefixtures('init_data')
def init_pages(self, init_data):
#how to instanciate the two drivers here? istead of creating two same methods for each driver
self.login_page = LoginPage(self.web_driver)
self.application_page = ApplicationPage(self.web_driver)
In my selenium project, I would like to be able to send arguments, instead of them to be fixed in the conftest file.
For each different method, I would like it to use different browsers for different things.
Is there any way to send arguments TO the fixture??
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import DesiredCapabilities
#pytest.fixture(scope="class", params=['chrome']) #i would like to send here dynamic fixtures.
def driver_init(request):
if request.param == 'firefox':
web_driver = webdriver.Firefox()
elif request.param == 'edge':
web_driver = webdriver.Edge() # dk:needs to be added the path
else:
options = Options()
options.add_argument(
r'user-data-dir=Users/dannyk/Library/Application Support/Google/Chrome/Default')
web_driver = webdriver.Chrome(chrome_options=options)
request.cls.driver = web_driver
yield
web_driver.close()
#pytest.mark.usefixtures("driver_init")
class BaseTest:
#pytest.fixture(autouse=True)
def init_pages(self):
self.login_page = lambda driver_type=self.driver: LoginPage(driver_type)
self.application_page = lambda driver_type=self.driver: ApplicationPage(driver_type)
class TestT4(BaseTest):
# #pytest.fixture(autouse=True)
#pytest.mark.run(order=1) #here i would like to use firefox for the driver
def test_init_firefox(self):
self.getting_start_page.go_home_page()
#pytest.mark.run(order=2) #here i would like to use chrome for the driver
def test_init_chrome(self):
self.getting_start_page.go_home_page()
You can use the "factory as fixture" pattern in conftest, which is basically an inner function inside the fixture that accepts parameters. You can then pass them from your test as arguments.
In conftest:
#pytest.fixture
def driver_init():
web_drivers = []
def _driver_init(browser):
if browser == 'firefox':
web_driver = webdriver.Firefox()
web_drivers.append(web_driver)
elif browser == 'edge':
web_driver = webdriver.Edge() # dk:needs to be added the path
web_drivers.append(web_driver)
else:
options = Options()
options.add_argument(
r'user-data-dir=Users/dannyk/Library/Application Support/Google/Chrome/Default')
web_driver = webdriver.Chrome(chrome_options=options)
web_drivers.append(web_driver)
return web_driver
yield _driver_init
for web_driver in web_drivers:
web_driver.quit()
Then, in your test:
class TestT4(BaseTest):
#pytest.mark.run(order=1) #here i would like to use firefox for the driver
def test_init_firefox(self, driver_init):
web_driver = driver_init("firefox")
#pytest.mark.run(order=2) #here i would like to use chrome for the driver
def test_init_chrome(self, driver_init):
web_driver = driver_init("chrome")
Or you can use the same concept on your def_init_pages(self): fixture to instantiate the pages and send the arguments from your tests.
Please check the official documentation here.
Update
For your first new question:
how to inject data via external commands? jenkins?
I believe what you're looking for is the def pytest_addoption(parser) fixture. It allows you to pass arguments to your test automation through the command line, when running Pytest. So you could pass the browser you want your tests to run with, locally or with Jenkins, with something like this:
In conftest:
def pytest_addoption(parser):
parser.addoption("--browser")
#pytest.fixture
def browser(request):
return request.config.getoption("--browser")
Then, on your driver_init fixture you wouldn't use the "factory as fixture" pattern:
#pytest.fixture
def driver_init(browser):
if browser == 'firefox':
web_driver = webdriver.Firefox()
elif browser == 'edge':
web_driver = webdriver.Edge() # dk:needs to be added the path
else:
options = Options()
options.add_argument(
r'user-data-dir=Users/dannyk/Library/Application Support/Google/Chrome/Default')
web_driver = webdriver.Chrome(chrome_options=options)
yield web_driver
web_driver.quit()
Then, to run your tests, you would pass the browser as argument:
pytest --browser=firefox
Please check these documents:
Pass different values to a test function, depending on command line options
pytest_addoption(parser: Parser, pluginmanager: PytestPluginManager) → None
For your second new question:
how to instanciate the two drivers here? istead of creating two same methods for each driver
I think what might be the answer is the fixture parametrization that you used on your original question, but then with the driver_init fixture I suggested earlier (you wouldn't need the def init_data(self, driver_init): fixture you wrote):
#pytest.fixture(autouse=True, params=["firefox", "chrome", "edge"])
def init_pages(self, request, driver_init):
self.login_page = LoginPage(driver_init(request.param))
self.application_page = ApplicationPage(driver_init(request.param))
Please note that I have removed the #pytest.mark.usefixtures as it has no effect when applied to another fixture. You need to declare what fixture you're using as a parameter:
#pytest.fixture(autouse=True)
def init_pages(self, init_data):
Please check the pytest.mark.usefixtures documentation
I hope this gives you more tools to figure out what you need to do to sort your problem. I'm not sure if I understand completely what you're trying to accomplish.

How to run tearDown and setUp in conftest.py

I need help with my pytest/selenium code.
I have the following code in my conftest.py file.
import pytest
from base.webdriverfactory import WebDriverFactory
from pages.login_page import LoginPage
#pytest.fixture(scope="class")
def oneTimesetUp(request, browser):
print("Running one time setUp")
wdf = WebDriverFactory(browser)
driver = wdf.getWebDriverInstance()
lp = LoginPage(driver)
lp.login("haykpo", "Aaaa4321")
if request.cls is not None:
request.cls.driver = driver
yield driver
lp.log_out_from_wp_page()
driver.quit()
print("Running one time tearDown")
And here is my test file where I use this fixture
#pytest.mark.usefixtures("oneTimesetUp", "tearDown")
class TestPublishWithOfflinewAsset:
#pytest.fixture(autouse=True)
def objectSetup(self, oneTimesetUp):
self.pub = TestPublishofflineWOMedia(self.driver)
def test_publish_with_off_w_media(self):
self.pub.select_project('Test cases - Avallain')
self.pub.check_lo_plays_normally(15292)
I know that whatever comes after yield is meant to be code as tearDown. So I have written these 2 lines in order to log out from the app and quit the browser at the end of the test execution.
lp.log_out_from_wp_page()
driver.quit()
However, the problem is that the log out part (not the quit one interestingly) is always being executed after few steps when my test starts and when browser focus switch to iframe during test execution (or may be this is just a coincidence am not sure if iframe is guilty here). How can I compose my code to run my teardown log out or whatever I want after yield as intended but not during test execution?
For more details here is the detailed files with code.
The below one is my Login page
from base.basepage import BasePage
class LoginPage(BasePage):
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
### Locators ###
_name_field = "form1:Name"
_password_field = "form1:Password"
_login_button = "form1:loginButton"
_work_packages = "wpButton"
_user_logout_dropdown_button = 'rolebutton_button'
_logout_button = 'blogout'
def log_out_from_wp_page(self):
self.elementClick(locator=self._user_logout_dropdown_button)
self.driver.implicitly_wait(5)
self.elementClick(locator=self._logout_button)
And below one is webdriver factory
class WebDriverFactory:
def __init__(self, browser):
self.browser = browser
def getWebDriverInstance(self):
"""
Get WebDriver Instance based on the browser configuration
Returns:
'WebDriver Instance'
"""
global driver
baseURL = "https://example.com"
if self.browser == "iexplorer":
# Set ie driver
driver = webdriver.Ie()
elif self.browser == "firefox":
driver = webdriver.Firefox()
elif self.browser == "chrome":
# Set chrome driver
driver = webdriver.Chrome()
#driver.set_window_size(1440, 900)
else:
driver = webdriver.Chrome()
# Setting Driver Implicit Time out for An Element
driver.implicitly_wait(10)
# Maximize the windows
driver.maximize_window()
# Loading browser with App URL
driver.get(baseURL)
return driver
The below one is BasePsge
class BasePage(SeleniumDriver):
def __init__(self, driver):
super(BasePage, self).__init__(driver)
self.driver = driver

why i am not able to execute 2 nd function i.e. going_first_page

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import HtmlTestRunner
class Environment(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path="F:\\automation\\chromedriver.exe")
# login
def test_login(self):
driver = self.driver
driver.maximize_window()
driver.get("http://localhost/dashboatd")
self.driver.find_element_by_id('uemail').send_keys('xyz#gmail.com')
self.driver.find_element_by_id('upwd').send_keys('1234567890')
self.driver.find_element_by_id('upwd').send_keys(Keys.RETURN)
# login page
def going_first_page(self):
going_first_page = self.find_element_by_class_name('color7')
self.execute_script("arguments[0].click();", going_first_page)
new_notification = self.driver.find_element_by_class_name('fa-paper-plane')
self.driver.execute_script("arguments[0].click();", new_notification)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='F:\\automation\\reports'))
As per python guidelines-
"A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests."
So, you should rename it to test_going_first_page(self) from going_first_page(self)

Python automation: How to assert if string is lower or upper case?

I'm VERY new to automation, fair warning.
I have an automation script to verify that the canonical tag of a page is present. I also need to assert that it's all lower case. Would I just create an assert after "driver.find_element..." to assert islower() ?
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import unittest
class homepage_canonical(unittest.TestCase):
def setUp(self):
global driver
driver = webdriver.Firefox()
driver.get("websiteurlhere")
def test_hpcanonical(self):
WebDriverWait(driver, 10)
driver.find_element_by_css_selector("link[href='canonicalurlhere'][rel='canonical']")
def tearDown(self):
driver.quit()
if __name__ == "__main__":
unittest.main()
I would use assertTrue :
def test_hpcanonical(self):
wait = WebDriverWait(driver, 10)
element = driver.find_element_by_css_selector("link[href='canonicalurlhere'][rel='canonical']")
self.assertTrue(element.text.islower())

Scroll down pages with selenium and python

this is the problem:
I am using selenium to download all the successful projects from this webpage ("https://www.rockethub.com/projects"). The url does not change if a click on any button.
I'm interested in successful project, thus I click on the button status and then I click on successful.
Once on this page I need to scroll down repedetly to make other urls appear.
Here is the problem. So far I have been not able to scroll down the page
This is my code:
from selenium.webdriver import Firefox
from selenium import webdriver
url="https://www.rockethub.com/projects"
link=[]
wd = webdriver.Firefox()
wd.get(url)
next_button = wd.find_element_by_link_text('Status')
next_button.click()
next_but = wd.find_element_by_link_text('Successful')
next_but.click()
wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Any idea on how to solve this?
Thanks
Giangi
Since the content is updated dynamically, you need to wait for a change of the content before executing the next step:
class element_is_not(object):
""" An expectation for checking that the element returned by
the locator is not equal to a given element.
"""
def __init__(self, locator, element):
self.locator = locator
self.element = element
def __call__(self, driver):
new_element = driver.find_element(*self.locator)
return new_element if self.element != new_element else None
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)
driver.get("https://www.rockethub.com/projects")
# get the last box
by_last_box = (By.CSS_SELECTOR, '.project-box:last-of-type')
last_box = wait.until(element_is_not(by_last_box, None))
# click on menu Status > Successful
driver.find_element_by_link_text('Status').click()
driver.find_element_by_link_text('Successful').click()
# wait for a new box to be added
last_box = wait.until(element_is_not(by_last_box, last_box))
# scroll down the page
driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")
# wait for a new box to be added
last_box = wait.until(element_is_not(by_last_box, last_box))
Run the wd.execute_script("window.scrollTo(0, document.body.scrollHeight);") in loop, since each time the script is executed only certain number of data is rerieved, so you have to execute it in a loop.
If you are just looking to retrieve all the successful projects at once and not interested in simulating the scrolling down to the page, then look at this answer, it may help.

Resources