Page Class
Page class contains actual automated code for your test for the required page, screen.
E.g. There is a page in your web application which deals with alerts and popups. The below code shows how alerts are handled in page class.
Similarly, you can create automation scripts for your various web pages.
import utilities.logger as cl import logging from base.basepage import BasePage from page.navigation.navigation_page import NavigationPage from utilities.util import Util class LoginPage(BasePage): log_base = cl.customlogger(loglevel=logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver self.nav = NavigationPage(driver) self.util = Util() def _click_login_link(self): self.element_click(self.util.get_locator('locators', 'login_link'), locatorType="link-text") def _enter_email(self, email): self.wait_for_element(self.util.get_locator('locators', 'email_field'), locatorType='xpath') self.sendKeys(data=email, locator=self.util.get_locator('locators', 'email_field'), locatorType='xpath') def _enter_password(self, password): password_field = self.wait_for_element(locator=self.util.get_locator('locators', 'password_field'), locatorType='xpath') self.sendKeys(data=password, element=password_field, locator="") def _click_login_button(self): self.wait_for_element(self.util.get_locator('locators', 'login_button'), locatorType="name") self.element_click(self.util.get_locator('locators', 'login_button'), locatorType="name") def login(self, email, password): self._click_login_link() self._enter_email(email) self._enter_password(password) self._click_login_button() def verify_login_successful(self): self.wait_for_element("My Courses".strip(), locatorType="link-text") result = self.is_element_present("My Courses".strip(), locatorType="link-text") return result def verify_login_failed(self): result = self.is_element_present("//div[contains(text(),'Invalid email or password')]", locatorType="xpath") return result def verify_login_title(self): return self.verifyPageTitle("Let's Kode It") def logout(self): self.nav.navigate_to_user_settings() self.element_click(locator="//div[@id='navbar']//a[@href='/sign_out']", locatorType="xpath")Test ClassNow that you have created a generic method in Base class and you also have an automation test script for your page in page class, let's create a test method to execute a relative test case.from page.login.login_page import LoginPage from utilities.teststatus import TestStatus from utilities.util import Util from page.login.login_page import LoginPage import page.login.login_page import unittest import pytest import HtmlTestRunner @pytest.mark.usefixtures("oneTimeSetUp", "setUp") class LoginTests(unittest.TestCase): @pytest.fixture(autouse=True) def object_setup(self, oneTimeSetUp): self.login_page = LoginPage(self.driver) self.test_status = TestStatus(self.driver) self.util = Util() @pytest.mark.run(order=1) def test_validLogin(self): self.login_page.login(self.util.get_locator('credentials','username'), self.util.get_locator('credentials','password')) page_title_check = self.login_page.verify_login_title() if page_title_check: self.login_page.capture_screenshot("Login title is verified") self.test_status.mark(page_title_check, "Title Verification") login_status = self.login_page.verify_login_successful() if login_status: self.login_page.capture_screenshot("Login is successful") self.test_status.mark_final("test_validLogin", login_status, "Login Verification") @pytest.mark.run(order=2) def test_invalidLogin(self): self.login_page.logout() self.login_page.login(self.util.get_locator('credentials','invalid_username'), self.util.get_locator('credentials','invalid_password')) result = self.login_page.verify_login_failed() assert result == True
Conftest.py
Conftest.py file is used to define all the fixtures that are referenced by the testscripts during run time. pytest will look for the conftest.py file in the project directory and it will execute all the fixtures as soon as the test class is invoked. There are some class level fixtures and test level fixtures as defined in the below code. 'oneTimeSetUp' fixture will create driver instance for the test. It will accept certainparameters/arguments like browser, url from the command line and then it will be passed to thedriver instance. Similarly setUp method defined below is a fixture that is applicable for every test method i.e. it will be executed before any test method runs.
import pytest from base.webdriverfactory import WebDriverFactory from utilities import handy_utilities from utilities.util import Util import time import sys from utilities.logger import customloggerhand_util = handy_utilities.HandyUtilities() log = customlogger(loglevel='DEBUG') @pytest.yield_fixture(scope="session") def setUp(): print("Running method level setUp") util = Util() locator_list = util.get_locators_list() if locator_list is None: sys.exit() else: print('locators = ' + ":" + str([locator_list])) yield str(locator_list) print("Running method level tearDown") @pytest.yield_fixture(scope="class") def oneTimeSetUp(request, browser, url): print("Running one time setUp") log.info("#############" + __name__ + " ", hand_util.get_locator('Environment_variables', 'OS')) log.info("#############" + __name__ + " ", hand_util.get_locator('Environment_variables', 'OS_version')) wdf = WebDriverFactory(browser, url, 'browsers', 'Chrome', 'urls', 'practice_url') driver = wdf.getWebDriverInstance() util = Util() if request.cls is not None: request.cls.driver = driver yield driver time.sleep(2) driver.quit() util.move_files_to_directory('*.log') util.move_files_to_directory('*.html') print("Running one time tearDown") def pytest_addoption(parser): parser.addoption("--browser") parser.addoption("--osType", help="Type of operating system") parser.addoption("--url") @pytest.fixture(scope="session") def browser(request): return request.config.getoption("--browser") @pytest.fixture(scope="session") def url(request): return request.config.getoption("--url") @pytest.fixture(scope="session") def osType(request): return request.config.getoption("--osType")Driver Instance
There is a class with method which will return a driver instance based on the browser parameter passed to the oneTimeSetUp fixture so as soon as any class is initialized, oneTimeSetUp fixture will be executed to get the driver instance.
from selenium import webdriver from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.firefox.options import Options as FirefoxOptions from utilities.handy_utilities import HandyUtilities from utilities.util import Util from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class WebDriverFactory(): def __init__(self, browser, url, *args): self.browser = browser self.baseURL = url self.handy_utilities = HandyUtilities() self.util = Util() for arg in args: if arg == 'browsers': self.key_browser = arg if arg in ['Chrome', 'Firefox', 'Safari']: self.data_browser = arg if arg == 'urls': self.key_url = arg if arg == 'practice_url': self.data_url = arg self.chrome_options = ChromeOptions() self.firefox_options = FirefoxOptions() self.firefox_capabilities = DesiredCapabilities.FIREFOX.copy() self.chrome_capabilities = DesiredCapabilities.CHROME.copy() self.chrome_capabilities['platform'] = 'macOS' self.chrome_capabilities['version'] = "10.15.3" def getWebDriverInstance(self): if self.browser == "iexplorer": driver = webdriver.Ie() elif self.browser == "firefox": driver = webdriver.Firefox(firefox_options=self.firefox_options, desired_capabilities=self.firefox_capabilities) elif self.browser == "chrome": driver = webdriver.Chrome(chrome_options=self.chrome_options, desired_capabilities=self.chrome_capabilities) else: self.browser = self.util.get_locator(key=self.key_browser, data=self.data_browser) if self.browser == 'Chrome': driver = webdriver.Chrome(chrome_options=self.chrome_options, desired_capabilities=self.chrome_capabilities) elif self.browser == 'Firefox': driver = webdriver.Firefox(firefox_options=self.firefox_options, desired_capabilities=self.firefox_capabilities) else: raise Exception("Browser is not defined in config file") driver.implicitly_wait(3) driver.maximize_window() if self.baseURL is not None: driver.get(self.baseURL) else: url = self.util.get_locator(key=self.key_url, data=self.data_url) driver.get(url) return driverwhen there are no parameters, arguments passed in the oneTimeSetUp fixture in conftest.py file,
values/data will be fetched from the config.yaml file and it will be supplied to driver instance class
above to get the required driver instance.
Comments
Post a Comment