0% found this document useful (0 votes)
23 views15 pages

Automation Testing Case Study Solution

Solution

Uploaded by

urvashi4301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views15 pages

Automation Testing Case Study Solution

Solution

Uploaded by

urvashi4301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

1.

Find Element by different methods

 By Id and Name
 driver.find_element_by_id()

 from selenium import webdriver


 import time
 from selenium.webdriver.common.keys import Keys

 driver = webdriver.Firefox()
 driver.get("http://google.com")
 driver.maximize_window()
 time.sleep(5)
 inputElement = driver.find_element_by_id("lst-ib")
 inputElement.send_keys("Techbeamers")
 inputElement.submit()
 time.sleep(20)

 driver.close()

 driver.find_element_by_name()

 from selenium import webdriver


 import time
 from selenium.webdriver.common.keys import Keys

 driver = webdriver.Firefox()
 driver.get("http://google.com")
 driver.maximize_window()
 time.sleep(5)
 inputElement = driver.find_element_by_name("q")
 inputElement.send_keys("Techbeamers")
 inputElement.submit()
 time.sleep(20)

 driver.close()
 By XPath and CSS

 driver.find_element_by_xpath()
 <html>
 <body>
 <form id="signUpForm">
 form_element=driver.find_element_by_xpath("//
form[@id='signUpForm']")
 email_input=driver.find_element_by_xpath("//form[input/
@name='emailId/mobileNo']")
 <input name="emailId/mobileNo" type="text" />
 <input name="password" type="password" />
 <input name="continue" type="submit" value="SignUp" />
 <input name="continue" type="button" value="Clear" />
 </form>
 </body>
 <html>

 driver.find_element_by_css_selector()

 <html>
 <body>
 get_div = driver.find_element_by_css_selector('div.round
button')
 <div class="round-button">Click Here</p>
 </body>
 <html>
 By Link Text and Partial Link Text

 driver.find_element_by_link_text()

 from selenium import webdriver


 import time
 from selenium.webdriver.common.keys import Keys

 driver = webdriver.Firefox()
 driver.get("http://google.com")
 driver.maximize_window()
 time.sleep(5)
 inputElement = driver.find_element_by_name("q")
 inputElement.send_keys("Techbeamers")
 inputElement.submit()
 time.sleep(5)
 elem = driver.find_element_by_link_text("Python
Tutorial")
 elem.click()
 time.sleep(20)

 driver.close()

 driver.find_element_by_partial_link_text()

 from selenium import webdriver


 import time
 from selenium.webdriver.common.keys import Keys

 driver = webdriver.Firefox()
 driver.get("http://google.com")
 driver.maximize_window()
 time.sleep(5)
 inputElement = driver.find_element_by_name("q")
 inputElement.send_keys("Techbeamers")
 inputElement.submit()
 time.sleep(5)
 elem = driver.find_element_by_partial_link_text("Python")
 elem.click()
 time.sleep(20)

 driver.close()
 By Class Name and Tag

 driver.find_element_by_class_name()

 <html>
 <body>
 get_div = driver.find_element_by_class_name('round-
button')
 <div class="round-button">Click Here</div>
 </body>
 <html>

 driver.find_element_by_tag_name()
 <html>
 <body>
 get_div = driver.find_element_by_tag_name('title')
 <title>Hello Python</title>
 <p>Learn test automation using Python</p>
 </body>
 <html>
 Find List of Elements
- ID
- Name
- Class Name
- Tag Name
- Link Text
- XPath
- CSS Selectors

 Using Ids with CSS Selectors to Find Element

With ID

- Verify the locator value

- css=<HTML tag><#><Value of ID attribute>


- HTML tag – It is the tag which is used to denote the web element which we want to access.
- # – The hash sign is used to symbolize ID attribute. It is mandatory to use hash sign if ID
attribute is being used to create CSS Selector.
- Value of ID attribute – It is the value of an ID attribute which is being accessed.

With Class

- css=<HTML tag><.><Value of Class attribute>


- . – The dot sign is used to symbolize Class attribute. It is mandatory to use dot sign if a Class
attribute is being used to create a CSS Selector.

With Attribute

- css=<HTML tag><[attribute=Value of attribute]>


- Attribute – It is the attribute we want to use to create CSS Selector. It can value, type, name
etc. It is recommended to choose an attribute whose value uniquely identifies the web
element.
- Value of attribute – It is the value of an attribute which is being accessed.

With Sub-string

- css=<HTML tag><[attribute^=prefix of the string]>


- ^ – Symbolic notation to match a string using prefix.
- Prefix – It is the string based on which match operation is performed. The likely string is
expected to start with the specified string.

With Inner Text

- css=<HTML tag><:><contains><(text)>
- : – The dot sign is used to symbolize contains method
- Contains – It is the value of a Class attribute which is being accessed.
- Text – The text that is displayed anywhere on the web page irrespective of its location.
 Using Wildcards with CSS Selectors
- [attribute*="value"]
- * wildcard also known as containing wildcard.
- [attribute^=”value”]
- [attribute$=”value”]
Example:
<!DOCTYPE html>

<html>
<head>
<style>

/* Define styles of selected items, h1 and


rest of the body */
[class*="str"] { /* WE USE * HERE */
background: green;
color: white;
}
h1 {
color:green;
}
body {
text-align:center;
width:60%;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>

<!-- Since we have used * with str, all items with


str in them are selected -->
<div class="first_str">The first div element.</div>
<div class="second">The second div element.</div>
<div class="my-strt">The third div element.</div>
<p class="mystr">Paragraph Text</p>
</body>
</html>
Output:
2. Selenium Webdriver Activities

 To Get the Text on Element


- element = driver.find_element_by_class_name("class_name").text

 To Get Value of Element


- The get_attribute() method is capable of obtaining the value we have entered in an input
box.
- Let us consider the below input box where we shall enter some texts - Selenium Python and
then fetch the value with get_attribute().

-
- Example:
- from selenium import webdriver
- driver = webdriver.Chrome(executable_path="C:\\
chromedriver.exe")
- driver.implicitly_wait(0.5)
- driver.get("https://www.google.com/")
- #identify element
- l= driver.find_element_by_name("q")
- l.send_keys("q")
- #get_attribute() to get value of input box
- print("Value of input box: " + l.get_attribute('value'))
- driver.close()

 To Check if Element is present


- We can also verify if an element is present in the page, with the help of find_elements()
method.

 How to find the state of a Web Element (displayed and Enabled)


- driver.findElement(By.id(“gbqfb”)).isEnabled();
- driver.findElement(By.id(“gbqfba”)).isDisplayed();
- driver.findElement(By.id(“male”)).isSelected();

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class VisibilityConditions {

/**
* @param args
*/

public static void main(String[] args) {

// objects and variables instantiation


WebDriver driver = new FirefoxDriver();
String appUrl = "https://google.com";

// launch the firefox browser and open the application url


driver.get(appUrl);

// maximize the browser window


driver.manage().window().maximize();

// declare and initialize the variable to store the


expected title of the webpage.
String expectedTitle = "Google";

// fetch the title of the web page and save it into a


string variable
String actualTitle = driver.getTitle();

// compare the expected title of the page with the actual


title of the page and print the result
if (expectedTitle.equals(actualTitle))
{
System.out.println("Verification Successful - The
correct title is displayed on the web page.");
}
else
{
System.out.println("Verification Failed - An
incorrect title is displayed on the web page.");
}

// verify if the “Google Search” button is displayed and


print the result
boolean
submitbuttonPresence=driver.findElement(By.id("gbqfba")).isDisplayed();
System.out.println(submitbuttonPresence);
// enter the keyword in the “Google Search” text box by
which we would want to make the request
WebElement searchTextBox =
driver.findElement(By.id("gbqfq"));
searchTextBox.clear();
searchTextBox.sendKeys("Selenium");

// verify that the “Search button” is displayed and enabled


boolean searchIconPresence =
driver.findElement(By.id("gbqfb")).isDisplayed();
boolean searchIconEnabled =
driver.findElement(By.id("gbqfb")).isEnabled();

if (searchIconPresence==true && searchIconEnabled==true)


{
// click on the search button
WebElement searchIcon =
driver.findElement(By.id("gbqfb"));
searchIcon.click();
}

// close the web browser


driver.close();
System.out.println("Test script executed successfully.");

// terminate the program


System.exit(0);
}
- }

 Radio Buttons and Checkboxes


- We can select a radio in a page in Selenium with the help of click() method.

# identifying the radio button with xpath then click


driver.find_element_by_xpath("//input[@value='Female']").click()

 We can check a checkbox in a page in Selenium with the help of click() method.
 # identifying the checkbox with xpath, then click
 driver.find_element_by_xpath("//input[@value='Automation
Tester']").click()

 Working with iFrames


- An iframe is identified with a <iframe> tag in an html document.
- Let us see a html document of a frame.
Example:

from selenium import webdriver


driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://the-internet.herokuapp.com")
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# switch to frame with name
driver.switch_to.frame("frame-bottom")
# identify element and get text method
s = driver.find_element_by_xpath("//body").text
print ("Test inside frame: " + s)
# move out of frame to parent page
driver.switch_to.default_content()
driver.quit()

 The following methods help to switch between iframes:


1. switch_to.frame(args) – The frame index is put as an argument to the method. The starting
index of iframe is 0.
- Syntax − driver.switch_to.frame(0), switching to the first iframe.

2. switch_to.frame(args) - The frame name or id is put as an argument to the method.


- Syntax − driver.switch_to.frame("nm"), switching to the iframe with name nm.

3. switch_to.frame(args) - The frame webelement is put as an argument to the method.


- Syntax − driver.switch_to.frame(f),switching to the iframe with webelement f.

4. switch_to.default_content() – To shift to the parent page from the iframe.


- Syntax − driver.switch_to.default_content()
3. Different Waits in selenium

 Implicit Wait
- An implicit wait is a global wait applied to all the elements on the page. The wait time is
provided as arguments to the method. For example, if the wait time is 5 seconds, it shall
wait this period of time before throwing a timeout exception.
- An implicit wait is a dynamic wait which means if the element is available at the third
second, then we shall move to the next step of the test case instead of waiting for the
entire five seconds.

- driver.implicitly_wait(2)
- #setting implicit wait 5 seconds
- driver.implicitly_wait(5)

 Explicit Wait
- The explicit wait is also a dynamic in nature which means the wait will be there as long
as necessary. Thus, if the wait time is five seconds and our given condition is satisfied at
the third second, we need not halt the execution for the next two seconds.

- w = WebDriverWait(driver, 7)
- w.until(expected_conditions.presence_of_element_located((
By.ID, "Tutorialspoint")))
- The expected conditions commonly used in explicit wait are listed below:
- title_contains
- visibility_of_element_located
- presence_of_element_located
- title_is
- visibility_of
- element_selection_state_to_be
- presence_of_all_elements_located
- element_located_to_be_selected
- alert_is_present
- element_located_selection_state_to_be
- staleness_of
- element_to_be_clickable
- invisibility_of_element_located
- frame_to_be_available_and_switch_to_it
- text_to_be_present_in_element_value
- text_to_be_present_in_element
- element_to_be_selected
Example for both the waits

from selenium import webdriver


from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which
will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#setting implicit wait 10 seconds
driver.implicitly_wait(10)
# to maximize the browser window
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/tutor_connect/
index.php")
#to refresh the browser
driver.refresh()
# identifying the link with the help of link text locator
driver.find_element_by_link_text("Search Students").click()
w.(expected_conditions.presence_of_element_located((By.
CSS_SELECTOR, "input[name = 'txtFilterLocation']")))
#to close the browser
driver.close()

4. Different Logging Activities

 Logging to console
- We can get console.log output from Chrome with Selenium Python API bindings. We will
perform this with the DesiredCapabilities class. We shall enable the logging from the
browser with DesiredCapabilities.Chrome setting.
- We have to pass this browser capability to the driver object by passing it as a parameter to
the Chrome class. To enable logging we shall set the property goog:loggingPrefs of the
browser to 'browser':'ALL'.
- Syntax
Syntax:dc = DesiredCapabilities.CHROME
dc['goog:loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(desired_capabilities=dc)
Example:

from selenium import webdriver


from selenium.webdriver.common.desired_capabilities import
DesiredCapabilities
#set browser log
dc = DesiredCapabilities.CHROME
dc['goog:loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",
desired_capabilities=dc)
#launch browser
driver.get ("https://www.tutorialspoint.com/index.htm")
#obtain with get_log()
for e in driver.get_log('browser'):
print(e)
driver.quit()

 Logging to File
- A log configuration consists of formatter and FileHandler methods. We need to import a
logging package and then create an object which will be responsible for entire logging.
- Syntax
logger = logging.getLogger(_name_)
- The different types of logger level are listed below. We can add all, some or at least one
logger in our test case.
- logger.debug("Debug log")
- logger.info("Information log")
- logger.warning("Warning log")
- logger.error("Error log")
- logger.critical("Critical log")

Example:

import logging
def loggingDmo():
# getLogger() method takes the test case name as input
logger = logging.getLogger(__name__)
# FileHandler() method takes location and path of log file
fileHandler = logging.FileHandler('logfile.log')
# Formatter() method takes care of the log file formatting
formatter = logging.Formatter("%(asctime)s :%(levelname)s :
%(name)s :%(message)s")
fileHandler.setFormatter(formatter)
# addHandler() method takes fileHandler object as parameter
logger.addHandler(fileHandler)
# setting the logger level
logger.setLevel(logging.DEBUG)
logger.debug("Debug log")
logger.info("Information log ")
logger.warning("Warning log")
logger.error("Error log")
logger.critical("Critical log")

5. Different Pytest Activities

 Activities on Pytest Fixtures


- Fixtures are functions, which will run before each test function to which it is applied.
Fixtures are used to feed some data to the tests such as database connections, URLs to test
and some sort of input data. Therefore, instead of running the same code for every test, we
can attach fixture function to the tests and it will run and return the data to the test before
executing each test.
- A function is marked as a fixture by:

- @pytest.fixture
- A test function can use a fixture by mentioning the fixture name as an input parameter.
- Create a file test_div_by_3_6.py and add the below code to it

- import pytest
-
- @pytest.fixture
- def input_value():
- input = 39
- return input
-
- def test_divisible_by_3(input_value):
- assert input_value % 3 == 0
-
- def test_divisible_by_6(input_value):
- assert input_value % 6 == 0

 Pytest Naming conventions


- Here is the example in which we are going to see how naming convention for function
works.
- File name is test_arithmetic.py, in which four functions are with test_naming convention.
Where as third function doesn't follow the naming convention. If we try to execute this file,
only three functions data was collected and the other function multiply() was not passed.
- Input:
- def test_subtract():
- a=6
- b=6
- assert a - b == 0
- def test_divide():
- a=6
- b=6
- assert a / b == 1
- def multiply():
- a=6
- b=6
- assert a - b == 0
- def test_multiply():
- a=6
- b=6
- assert a * b == 36
- Output:
- collected 3 items
-
- test_arithmetic.py ...
[100%]

You might also like