0% found this document useful (0 votes)
50 views

Automation Testing

Regression testing ensures that previously developed and tested software performs as expected after any changes. It is important when requirements or code change, new features are added, or defects are fixed. Manual testing involves testing software manually with knowledge of its functionality, and is suitable for small/medium projects with low budgets. Automation testing writes test scripts to automate execution, using tools to validate software. It is faster than manual testing but has initial investment costs. Both approaches have pros and cons depending on factors like resources, budget, test volumes, and frequency of changes.

Uploaded by

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

Automation Testing

Regression testing ensures that previously developed and tested software performs as expected after any changes. It is important when requirements or code change, new features are added, or defects are fixed. Manual testing involves testing software manually with knowledge of its functionality, and is suitable for small/medium projects with low budgets. Automation testing writes test scripts to automate execution, using tools to validate software. It is faster than manual testing but has initial investment costs. Both approaches have pros and cons depending on factors like resources, budget, test volumes, and frequency of changes.

Uploaded by

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

Introduction to Automation

Testing
Regression Testing

 Regression testing is re-running functional and non-functional tests to ensure that


previously developed and tested software still performs after a change
 When
 change in requirements and code is modified according to the requirement
 New feature that is added to the software
 Defect fixing done for the bugs already raised
Manual Testing

Procedure that involves testing a software manually by QA


What ?
Small\Medium Project which under development
Where ?
Assure quality with low budget
Why ?

Who ? Testers with project functional knowledge


Automation testing is to write code/test scripts to automate
What ? test execution

Use appropriate automation tools to develop the test scripts


Where ? to validate the software

The goal is to complete test execution in less amount of


Why ? time

Who ? Testers with basic programing knowledge

When ? Not every time & everywhere


1. Processing Time

Automated testing is faster when directly compared to manual


testing

Manual testing consumes human resources is time-


consuming in general
2. Exploratory Testing

Automated testing does not allow for exploratory testing or random


testing in general.
Exploratory testing is a type of software testing where the test
cases are not created in advance but testers check the system on fly.
They may note down ideas about what to test before test execution.
The focus of exploratory testing is more on testing as a “Thinking”
activity.

Manual testing does allow for exploratory testing or


random testing methodologies to be implemented
3. Initial Investment

Automated testing involves spending a bigger amount but it pays


off well because the return on investment is better for long term

Manual testing involves spending a significantly smaller


amount but ROI is comparatively low
4. Reliability

Automated testing is very robust and reliable as the task is carried


out by various tools and scripts

Manual testing does not have a high rate of accuracy


because it involves human error
5. UI Changes

Automated testing has a small disadvantage because scripts need to


be changed completely if there is a UI change

Manual testing Can work fine with changes comparatively


simple and quicker when compared
6. Resources

Automated testing calls for testing tools and automation engineers

Manual testing calls for investing in human resources


7. Value for money

Automated testing will work out if the test content volume is large

Manual testing will not be cost effective for high volume


testing
8. Performance Testing

Automated testing allows tests like load testing, stress testing etc.
which can be done very easily

Manual testing does not offer feasibility when performance


testing is a main point of concern
9. Programming Knowledge

Automated testing involves a lot of programming, hence, it is must

Manual testing does not call for any requirement for


programming knowledge
10. Use in DevOps

Automated testing helps in build verification and testing which are


integral to the DevOps life cycle

Manual testing defeats the automated build principle of


DevOps entirely and lowers efficiency
11. Ideal Use Case

Automated testing is very well suited for regression testing, load


testing, highly repeatable functional test cases and more

Manual testing is suitable for AdHoc testing, exploratory


testing and cases where there are frequent changes
12. Summary

Automated testing brings about efficiency numbers to the table


unlike any other

Manual testing is one of those legacy systems which are


still needed across a spectrum of cases
What is Programming?
Just like we use Hindi or English to communicate with each other,
we use a Programming language to communicate with the
computer

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

 Easy to understand = Less development time

 Free and open source

 High-level language

 Portable – works on Windows/Linux/Mac

 + Fun to work with :)

Prog write + Byte code (intermediate code) => machine language


Comments
Single line comment #
Multiline comment “””str””” ‘’’str’’’
Modules
Built-in modules - e.g. os, math
External Modules - e.g. flask

Pip
Package manager – to download and install external modules
pip install –U selenium - command to install external module

REPL – Read, Evaluate , Print , Loop


Practice programs

Practice program set 1:

1. Write a program to print * or # pattern in python.


#
##
###
####
#####
 
2. Use REPL and print the table of 10 using it.
3. Label the program written in problem 4 with comments.
Variables and datatypes

Variable – Container to store a value


Keywords – Reserved words in Python
Identifiers – class/function/variable name

Primarily there are the following data types in Python:


1. Integers 10, -20
2. Floating point numbers 10.50 55.5
3. Strings “Hello” ‘Hi’ “””Hello””” ‘’’Hi’’’
4. Booleans True False
5. None

Python is a fantastic language that automatically identifies the type of data for us.
Rules for defining a variable name

1. A variable name can contain alphabets, digits, and underscore.


someName123 = “hello”
2. A variable name can only start with an alphabet and underscore.
3. A variable can’t start with a digit.
4. No white space is allowed to be used inside a variable name.
some_name = “Hello” #Valid
some name = “hello” #invalid
5. Variable names are case sensitive
type() function

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.

Str(31) # ”31” Integer to string conversion


 
int(“32”) # 32 String to int conversion
 
float(32) #32.0 Integer to float conversion

Here “31” is a string literal, and 31 is a numeric literal.


Operators in Python

The following are some common operators in Python:

1. Arithmetic Operators (+, -, *, /, etc.)


2. Assignment Operators (=, +=, -=, *=, /=, etc.)
3. Comparison Operators (==, >=, <=, >, <, !=, etc.)
4. Logical Operators (and, or, not)
input() function

This function allows the user to take input from the keyboard as a string.

a = input(“Enter name”) #if a is “harry”, the user entered harry


Practice set 2

1. Write a python program to print the contents of a directory using os module.


Search online for the function which does that.
2. Install an external module and use it to perform an operation of your interest.
(e.g. play MP3 audio)  
3. Write a Python program to add two numbers.
4. Write a Python program to find the remainder when a number is divided by Z(Integer).
5. Check the type of the variable assigned using the input() function.
6. Use a comparison operator to find out whether a given variable a is greater than b or not.
(Take a=34 and b=80)
7. Write a Python program to find the average of two numbers entered by the user.
8. Write a Python program to calculate the square of a number entered by the user.
String Slicing

A string in Python can be sliced for getting a part of the string.

The index in a string starts from 0 to (length-1) in Python.

aVariable = “Welcome”
String Functions

1. len() function : It returns the length of the string.


len(‘harry’) #Returns 5
2. endswith(“rry”) : This function tells whether the variable string ends with the string “rry” or not.
If string is “harry”, it returns for “rry” since harry ends with rry.
3. count(“c”) : It counts the total number of occurrences of any character.
4. capitalize() : This function capitalizes the first character of a given string.
5. find(word) : This function finds a word and returns the index of first occurrence of
that word in the string.
6. replace(oldword, newword) : This function replaces the old word with the new word
in the entire string.
Escape Sequence Characters

Sequence of characters after backslash ‘\’ [Escape Sequence Characters]

Escape Sequence Characters comprises of more than one character


but represents one character when used within the string.

Examples: \n (new line), \t (tab), \’ (single quote), \\ (backslash), etc.

\ - backslash
/ - forward slash
Practice Set 3

1. Write a program to detect double spaces in a string. (count of double space


or count of any char)
2. Write a program to format the following letter using escape sequence
characters.
Dear Candidate,
We are delight to inform you that you have cleared all rounds of interview
and we are extending offer to join us.
Thank you,
HR
3. From above solution (2) replace ‘Candidate’ with your name and HR name
with some other name. By using some string operation function
4. Replace the double spaces from problem 3 with single spaces.
Lists

Python Lists are containers to store a set of values of any data type. (Mutable datatype)

colors = [‘Red’, ‘Yellow’, ‘Green’, 7, False]

List Indexing - A list can be index just like a string.


Friends[0] #Red
List Slicing
Friends[0:2] #Red, Yellow
List Methods
Consider the following list:
L1 = [1, 8, 7, 2, 21, 15] #len = 6

sort() – updates the list to [1,2,7,8,15,21]


reverse() – updates the list to [15,21,2,7,8,1]
append(8) – adds 8 at the end of the list
insert(3,8) – This will add 8 at 3 index and rest items will shift index by 1
pop(2) – It will delete the element at index 2 and return its value
by default it take default last index if not provided
remove(21) – It will remove 21 from the last
Tuples

A tuple is an immutable (can’t change or modified) data type in Python

Once defined, tuple elements can’t be manipulated or altered

a = () #It is an example of empty tuple


a = (1,) #Tuple with only one element needs a comma
a = (1, 7, 2) #Tuple with more than one element

Tuple parentheses are basically optional


a = 1, 7, 2 # is also valid tuple

An empty tuple can also be created with tuple() without an argument.


empty_tuple = ()
Tuple methods

1. count(1) – It will return the number of times 1 occurs in a.

2. index(1) – It will return the index of the first occurrence of 1 in a.


Dictionary

Dictionary is a collection of key-value pairs.

Properties of Python Dictionaries


1. It is unordered
2. It is mutable
3. It is indexed by key
4. It cannot contain duplicate keys but can contain duplicate values

a = {"key" : "value",
"harry": "code",
"marks" : "100",
"list": [1,2,9]
}
a["key"]    # Prints value
a["list"]   # Prints [1,2,9] 
Dictionary Methods

1. items() : returns a list of (key,value) tuple.


2. keys() : returns a list containing dictionary’s keys.
3. update({“friend”: “Sam”}) : updates the dictionary with supplied key-value pairs.
4. get(“name”) : returns the value of the specified keys (and value is returned
e.g., “Harry” is returned here)

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

Set is a collection of non-repetitive elements

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

# Add multiple elements in set by passing them as a tuple


sample_set.update((10, 20, 30))
Operations on Sets

Consider the following set:


S = {1,8,2,3}

Len(s) : Returns 4, the length of the set


remove(8) : Updates the set S and removes 8 from S
pop() : Removes an random element from the set and returns the element removed.
clear() : Empties the set S
union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}
intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}

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.

if (condition1): // if condition 1 is true a = 22


print(“yes”) if (a>9):
elif (condition2): // if condition 2 is true
print(“No”) print(“Greater”)
else: // otherwise else:
print(“May be”)
print(“lesser”)
elif and else block are optional. You if you wish to use both, either or none which is fine.
Loops in Python

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.

Primarily there are two types of loops in Python


1. While loop
2. For loop
While Loop

The block keeps executing until the condition becomes false

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)

The syntax of a for loop looks like this:


l = [1, 7, 8]
for item in l:
print(item)
Range function in Python

The range function in python is used to generate a sequence of numbers.

We can also specify the start, stop, and step-size as follows:


range(start, stop, step_size)
• step size is usually not used with range()
For loop with else

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

A function is a group of statements performing a specific task.

To make program modular

Reuse

The syntax of a function declaration looks as follows:


def func1():
print(“Hello”) # function body # function code

--------------------------------------------------------------------------------------------------------------
func1() #This is called function call
Types of Function

1. Built-in functions #Already present in Python


Examples of built-in function includes len(), print(), range(), etc

2. User-defined functions #Defined by the user


The func1() function we defined is an example of a user-defined function.
Functions with arguments

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

We can have a value as the default argument in a function

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

Recursion is a function which calls itself.

This function can be defined as follows:


def factorial(n):
if i == 0 or i == 1 : #Base condition which doesn’t call the function any further
return i
else:
return n*factorial(n-1) #Function calling itself
Recursion
Syntax Error VS Exceptions

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.

Note: Exception is the base class for all the exceptions in Python.


Try and Except Statement – Catching Exceptions

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.

Specific exceptions handled in respective except block

All other exception handled in except: block

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

r – open for reading


w – open for writing, creates a new file if it does not exist or
truncates the file if it exists.
x - Opens a file for exclusive creation. If the file already exists,
the operation fails.
a – Opens a file for appending at the end of the file without
truncating it.
Creates a new file if it does not exist.
+ -> Opens a file for updating (reading and writing)
‘rb’ will open for read in binary mode
Class VS Object

OOPs - in oops Everything is considered as object


A class is a blueprint for creating objects. Is also collection of attributes/variable and functions/methods
An object is an instantiation of a class.
When class is defined, a template(info) is defined. Memory is allocated only after object instantiation.
Class VS Object

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

__init__() is a special method which runs as soon as the object is created.


__init__() method is also known as constructor.
It takes self-argument and can also take further arguments.

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:

• Doesn’t accept any arguments.


• Its definition has only one argument which is a reference to the instance being constructed.

# 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

• are bound to a class rather than its object


• They do not require a class instance (object/variable) creation
• they are not dependent on the state of the object
• Static method knows nothing about the class and just deals with the parameters
• @staticmethod #decorator to mark greet as a static method

@staticmethod #decorator to mark greet as a static method


def greet():
print(“Hello user”)
What is Automation Testing?

• 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

Four major components which include:

• Selenium Integrated Development Environment (IDE)


Firefox extension which provides record and playback functionality on test scripts
• Selenium Remote Control (Now Deprecated)
allows testers to write automated web application UI test. It also involves an HTTP proxy server which enables the
browser to believe that the web application being tested comes from the domain provided by proxy server.

• 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

• pip install –U selenium # put on cmd

Get WebDrivers and put under python installed directory

• 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

• Initialize driver or get browser driver


driver = webdriver.Chrome() # for chrome
driver = webdriver.Ie() # for IE browser
Testing demo sites

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

• Open website or visit URL


driver.get("https://facebook.com/") # open url or visit url

• Capturing title of page


driver.title

• Capture Url of page


driver.current_url

• Closing and quitting browsers

driver.close() # close currently focused browser


driver.quit() #close all browers opened by script
Navigation Commands

• visit previous url OR Back button on browser


driver.back() # visit previous url

• Forward button on browser


driver.forward()
Element Locater

• Get/locate element by id
driver.find_element_by_id("txtUsername")
OR
driver.find_element(By.ID, “txtUsername")

• Get/locate element by name


driver.find_element_by_name("txtUsername")
OR
driver.find_element(By.NAME, “txtUsername")

• Get/locate element by class name


driver.find_element_by_className("txtUsername")
OR
driver.find_element(By.ID, “txtUsername")
Element Locater

• Get/locate element by XPATH


driver.find_element_by_xpath("//*[@id='origin']/span/input")
OR
driver.find_element(By.XPATH, “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

• Check element is displayed or not


user_ele = driver.find_element_by_name(“userName”)
user_ele .is_displayed() # returns true false

• Check element is enabled or not


user_ele = driver.find_element_by_name(“userName”)
user_ele .is_enabled() # returns true false

• Check element is selected or not


user_ele = driver.find_element_by_name(“userName”)
user_ele .is_selected() # returns true false
Radio button and Checkbox
Dropdown control
Link control
Alert control

Operation or handle popup alert

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

Handle - Unique ID for browser window

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.

from selenium import webdriver


 
driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")
Explicit wait

• 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.

element = WebDriverWait(driver, 10).until(


EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

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

• Scroll down the page by pixel


driver.execute_script(“window.scrollBy(0,1000)”, “")

• Scroll down the page till element found


element = driver.find_element(By.ID, "id")
driver.execute_script(“arguments[0].scrollIntoView();”, element)
# element is actual element of page located with any selector

• Scroll to end of page


driver.execute_script(“window.scrollBy(0, document.body.scrollHeight)”)
Mouse Action

Module - from selenium.webdriver import ActionChains

• MouseHover

actions = ActionChains(driver)
actions.move_to_element(firstElement). move_to_element(secondElement).click().perform()

#until you call perform() click operation will not happen

• Double click

actions = ActionChains(driver) # create instance/object of ActionChain


actions.double_click(element).perform()
Mouse Action

Module - from selenium.webdriver import ActionChains

• Right Click

actions = ActionChains(driver)
action.context_click(buttonElement).perform()

• Drag and Drop

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

Table is collection of rows and columns


Excel Operations

• Read data from file


• Write data to file

• Install below module/package


• pip install openpyxl
Screenshot

• 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

• Write logs into file for future reference


• Logs need to debug or find what went right what went wrong
• With logs we can easily analyze errors or failures

• 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

• logging.debug(“This is debug msg”)


• logging.info(“This is info msg”)
• logging.warning(“This is warning msg”)
• logging.error(“This is error msg”)
• logging.critical(“This is critical msg”)

• Default logging setting is “warning”

You might also like