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.
Related
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
I am using this body(desired_caps are set properly in config file)
Whatever I do I receive 'AttributeError: 'ClassName' object has no attribute 'driver'' or similar errors - no find_element_by_xpath attribute or whatever.
Do you have any suggestions? I am doing in the same way as in lectures, maybe anything related to appium + python setups?
import unittest
from appium import webdriver
import time
import tracemalloc
tracemalloc.start()
from config import desired_caps
# self = webdriver
# self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
class BaseTest(unittest.TestCase):
def test_testcase1(self):
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
def test_credentials(self):
email = self.driver.find_element_by_xpath("proper Xpath")
email.send_keys("Test")
save = self.driver.find_element_by_link_text("Log In")
save.click()
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(BaseTest)
unittest.TextTestRunner(verbosity=3).run(suite)
you need to make your driver in a function named setUp(). The unit test suite executes kinda like this.
setUp()
run test_testcase1()
tearDown()
setUp()
run test_credentials()
teardown()
...etc...
if driver driver is not made in setup() the other tests will not know about it. Unless you make driver in every single test. Same goes for any other test variables you'd need.
This way each test is independent of each other, and each test gets a fresh start.
I am using unittest example in selenium python
tried google did not get correct solution
from selenium import webdriver
import unittest
#import HtmlTestRunner
class googlesearch(unittest.TestCase):
driver = 'driver'
#classmethod
def setupClass(self):
self.driver = webdriver.Chrome(chrome_options=options)
self.driver.implicitly_wait(10)
self.driver.maximize_window()
def test_search_automationstepbystep(self):
self.driver.get("https://google.com")
self.driver.find_element_by_name("q").send_keys("Automation Step By step")
self.driver.find_element_by_name("btnk").click()
def test_search_naresh(self):
self.driver.get("https://google.com")
self.driver.find_element_by_name("q").send_keys("Naresh")
self.driver.find_element_by_name("btnk").click()
#classmethod
def teardownClass(self):
self.driver.close()
self.driver.quit()
print("Test completed")
if __name__== "__main__":
unittest.main()
As mentioned #Error - Syntactical Remorse , driver is a string due to your first line of code in your class.
If you are planning to access the driver globally make sure to declare the driver as global.
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)
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.