Automation Testing
Automation Testing
Testing
Regression Testing
Automated testing will work out if the test content volume is large
Automated testing allows tests like load testing, stress testing etc.
which can be done very easily
What is Python?
Python is a simple and easy-to-understand language that feels like
reading simple English. This Pseudo code nature of Python makes
it easy to learn and understandable for beginners
Features of Python
High-level language
Pip
Package manager – to download and install external modules
pip install –U selenium - command to install external module
Python is a fantastic language that automatically identifies the type of data for us.
Rules for defining a variable name
type function is used to find the data type of a given variable in Python.
a = 31
type(a) #class<int>
b = “31”
type(b) #class<str>
Typecasting
A number can be converted into a string and vice versa (if possible)
There are many functions to convert one data type into another.
This function allows the user to take input from the keyboard as a string.
aVariable = “Welcome”
String Functions
\ - backslash
/ - forward slash
Practice Set 3
Python Lists are containers to store a set of values of any data type. (Mutable datatype)
a = {"key" : "value",
"harry": "code",
"marks" : "100",
"list": [1,2,9]
}
a["key"] # Prints value
a["list"] # Prints [1,2,9]
Dictionary Methods
Get – will return value of specified key and if key not present then returns None
[“key”] – this will return value of specified key and if key is not present then
gives error
Sets in Python
Properties of Sets
1. Sets are unordered # Elements order doesn’t matter
2. Sets are unindexed # Cannot access elements by index
3. There is no way to change items in sets - Immutable items
Set is as whole mutable but inside items are immutable
4. Sets cannot contain duplicate values
Note : If we specify empty set with {} then default type will be dictionary <class 'dict'>
Conditional Expressions
The if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or
group of statements based on the value of an expression.
a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.
Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is
checked such as whether a counter has reached a prescribed number.
i=0
while i<5: # condition to be checked on every iteration
print(“Hello”)
i = i+1
Note: if the condition never becomes false, the loop keeps getting executed.
For Loop
A for loop is used to iterate through a sequence like a list, tuple, or string (iterables)
An optional else can be used with a for loop if the code is to be executed when the loop exhausts.
Example:
l = [1, 7, 8]
for item in l:
print(item)
else:
print(“Done”) #This is printed when the loop exhausts!
Loop Statements
1. Break
‘break’ is used to come out of the loop when encountered. It instructs the program to – Exit
the loop now
2. Continue
‘continue’ is used to stop the current iteration of the loop and continue with the next
one. It instructs the program to “skip this iteration.”
3. Pass
pass is a null statement in python. It instructs to “Do nothing.”
Function
Reuse
--------------------------------------------------------------------------------------------------------------
func1() #This is called function call
Types of Function
A function can accept some values it can work with. We can put these values in the parenthesis. A function can
also return values as shown below:
def greet(name):
gr = “Hello” + name
return gr
--------------------------------------------------------------
a = greet(“Credence”) #“Credence” is passed to greet in name
# a will now contain “Hello Credence”
Functions arguments with Default Parameter Value
For Example:
def greet(name=’Credence’):
#function body
-----------------------------------------------------------------------------------
greet() #Name will be ‘Credence’ in function body(default)
greet(“Credence”) #Name will be “Credence” in function body(passed)
Recursion
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program.
Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error.
Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception
are written inside except clause.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different exceptions.
try:
# statement(s)
except ZeroDivisionError:
# statement(s)
except IndexError:
# statement(s)
except:
# statements(s)
else and finally block
else : Sometimes we want to run a piece of code when try was successful
finally : finally block will always executed regardless exception occurred or not
try:
a = 10
except:
print("Exception handled")
else:
print("Else block executed")
finally:
print("finally block executed")
File I/O
Modes of opening a file
Instance/object attributes take preference over class attributes during assignment and retrieval.
objEmployee.attribute1 :
1. Is attribute1 present in the object?
2. Is attribute1 present in class?
3. If not present in both instance and class then error
__init__() constructor
The task of constructors is to initialize(assign values) to the data members(attributes) of the class when an
object of the class is created.
Types of constructors:
1. default constructor
2. parameterized constructor
default constructor:
# default constructor
def __init__(self):
self.name = "Credence"
# creating object of the class
obj = Employee()
parameterized constructor
• Accepts arguments
• takes its first argument as a reference to the instance being constructed known as self and the rest of the
arguments are provided by the programmer.
class Addition:
first = 0
second = 0
answer = 0 # creating object of the class
# this will invoke parameterized constructor
# parameterized constructor obj = Addition(1000, 2000)
def __init__(self, f, s):
self.first = f
self.second = s
Static method
• Automation testing uses the specialized tools to automate the execution of manually designed test
cases without any human intervention.
• Automation testing tools can access the test data, controls the execution of tests and compares the
actual result against the expected result.
• Consequently, generating detailed test reports of the system under test.
• advantages for improving long-term efficiency of any software
• Automation testing supports frequent regression testing
• Automated testing has long been considered beneficial for big software organizations. Although, it is
often thought to be too expensive or difficult for smaller companies to implement.
• It provides rapid feedback to developers.
• It provides unlimited iterations of test case execution.
• It provides disciplined documentation of test cases.
• Automated test generates customized defect reports.
• Less error prone as compared to manual testing.
What is Selenium?
• Most widely used open source Web UI (User Interface) automation testing suite
• supports automation across different browsers, platforms and programming languages.
Selenium Suite
• WebDriver
successor to Selenium RC. Test scripts are written in order to identify web elements on web pages and then
desired actions are performed on those elements
• Selenium Grid
allows us to run our tests on different machines against different browsers in parallel.
follows the Hub-Node Architecture to achieve parallel execution of test scripts
Selenium getting started
• Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads
• https://sites.google.com/chromium.org/driver/
• Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
• Firefox: https://github.com/mozilla/geckodriver/releases
• Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/
• Import webdriver
from selenium import webdriver
https://seleniumbase.io/demo_page
https://the-internet.herokuapp.com/
http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html
Basic Commands
• Get/locate element by id
driver.find_element_by_id("txtUsername")
OR
driver.find_element(By.ID, “txtUsername")
• What is XPATH –
• XPath is the language used for locating nodes in an XML document.
• main reasons for using XPath is when you don’t have a suitable id or name attribute for the
element you wish to locate.
Read value from input field
• Read value
row = driver.find_element_by_id("myTextInput2").get_attribute("value")
• Clear value
driver.find_element_by_id("myTextInput2").clear()
Conditional Commands
driver.switch_to.alert().accept()
- closes alert window using OK button
driver.switch_to.alert().dismiss()
-closes alert by using cancel button
Frame
Browser handle
driver.current_window_handle
gives unique id for current or parent browser window
driver.window_handles
returns all the handle values of opened browser windows
we can iterate list using loop for get particular window
driver.switch_to.window(handle)
to switch between multiple browser window
Implicit wait
• An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any
element (or elements) not immediately available.
• The default setting is 0 (zero). Once set, the implicit wait is set for the life of the WebDriver object.
• An explicit wait is a code you define to wait for a certain condition to occur before proceeding further
in the code
• There are some convenience methods provided that help you write code that will wait only as long as
required.
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
List of expected conditions commonly used in explicit wait
• 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
• 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
Scrolling page
• MouseHover
actions = ActionChains(driver)
actions.move_to_element(firstElement). move_to_element(secondElement).click().perform()
• Double click
• Right Click
actions = ActionChains(driver)
action.context_click(buttonElement).perform()
actions = ActionChains(driver)
actions.drag_and_drop(source_element, target_element).perform()
Upload and Download
• Upload file
element.send_keys(file_path)
• Download file
element.click()
Table
• driver.Save_screenshot(‘filename’)
• driver.Get_screenshot_as_file(‘filename’) #filename could be any name given to file. If you provide file
name with full path then file will be stored at location other wise will be at current working directory
Logging
• Logging is very useful tool in a programmer’s toolbox. It can help you develop a better understanding of the
flow of a program and discover scenarios that you might not even have thought of while developing
• Log Levels
• DEBUG
• INFO
• WARNING
• ERROR
• CRITICAL
Logging
• Import logging