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

Python Piyush Automation

The document provides an overview of Python automation concepts, including data types, object-oriented programming (OOP) principles, exception handling, and Selenium for web automation. It covers various programming constructs such as lists, tuples, dictionaries, functions, classes, and methods, as well as testing frameworks like pytest and logging practices. Additionally, it discusses how to handle web elements, alerts, waits, and browser operations in Selenium, along with generating reports and managing test cases.

Uploaded by

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

Python Piyush Automation

The document provides an overview of Python automation concepts, including data types, object-oriented programming (OOP) principles, exception handling, and Selenium for web automation. It covers various programming constructs such as lists, tuples, dictionaries, functions, classes, and methods, as well as testing frameworks like pytest and logging practices. Additionally, it discusses how to handle web elements, alerts, waits, and browser operations in Selenium, along with generating reports and managing test cases.

Uploaded by

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

Python Automation

Data type:-Numeric,string,list(array),tuple,dict

numeric data type:-int,float,long,complex

list=[]is data type that allows multiple values and can be


difference data type.The list is a data type that is mutable.

tuple():-The basic difference between a list and a tuple is that lists are mutable in nature whereas, tuples are
immutable.

dict{}:key:value pair
A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its
associated value

if else:is a condition,its not a loop

functions:if you don't create a class so it will trited function

OOP:=
class:-are the user defined blueprint or prototype
class have methods,variables,instances,constructor
class name should be capital first letter
Object:- An object is simply a collection of data (variables) and methods (functions).
function/method=when you create a class and function inide the
class so it treated as method

constructor:-is one method is automatically called when you create an object of a class.
2 type variable:-class and instance
class variable:-whatever variable you define immidiately inside your class is nothing but the
class variable
instance variable:-the variable that you define inside the constructor is called instance variable

self:-selft keyword is mandatory for calling variable name into method

Inheritance:-is nothing but acquiring the property of parent class


if:when you called parrent class property in child class so declaration the constructor
Exception:-2 way ;when expected condition is not meet ---
1)raise Exception("test failed")
output:-Exception:test failed
2)assertion=
car = "new"
assert(car =="te")
output=
assert(car =="te")
AssertionError

Try and catch:--------------------------------------------------------------


If you dont want failed your test is failed
try:
with open('tes.txt','r') as reader: # invalid
reader.read()

except:
print("doebt send any erroer msg")

Output:- doesn't send any error msg

Its still failed but program is run,without failure

Finally:--keyword-----no matter is test is fail or passed ----------------------------------------------------

try:
with open('tes.txt','r') as reader: # invalid
reader.read()

except Exception as e:
print(e)

finally:
print("test padsss")

Output:-
[Errno 2] No such file or directory: 'tes.txt'
test padsss

Process finished with exit code 0


Static drop down:-------------values fixed:----------------------------------------------------------
Using select class :--- Select()
If you see select tag then use select class <select>
CSS selector:-tagname[attri=’value’]

Dynamic/auto suggestive drop down:-------------------------------------------------------------------


How do you extract the text :- with using get_attribute(“value”)
—---------------------------------------------------------------------------------------------------------------------

Handling Alert pop up java script:------------------------------------------------------------------------

Alert = switch_to.alert :-----------------method using for handling pop ups


Alert.accept() ==accept the pop up
Alert.dismiss()==cancel the pop up

Waits:----------------2 types—--------------------------------------------------------------------
1)Implicit wait
2)Explicit wait

1)Implicit wait:-----syntax:--driver.implicitly_wait(5)
is global time out,if the object is not identified it will wait that particular time.
The Implicit Wait in Selenium is used to tell the web driver to wait for a
certain amount of time before it throws a “No Such Element Exception”

2)Explicit wait:-WebDriverWait its a class


Wait = WebDriverWait(driver, 10)
Wait.until(expected_conditions.presence of element_located(By.ID, “”)

When the message is show up that will show up 5 to 10 second, we don't know

Scroll down;-
Driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
HOVER:-----------------------------

Hover:- with using ActionChains(driver) class


action.move_to_element(driver.find—----).click().perform()

contex_click===right click mouse


double_click()
After writing .perform is mandatory

.move_to_element(on_element)

.click(on_element)

.click_and_hold(on_element)

.context_click(on_element)

.double_click(on_element)

.drag_and_drop(source,target)

.drag_and_drop_by_offset(source,
xoffset, yoffset)

.key_down(value, element)
.key_up(value, element)

.move_by_offset(xoffset, yoffset)

.move_to_element(to_element)

.move_to_element_with_offset(to_element
, xoffset, yoffset)

.pause(seconds).

.perform()

.release(on_element)

.reset_actions()

.send_keys(keys_to_send)

.send_keys_to_element(element,keys_to_s
end)

Handle the Child WIndows:-------------------------------------------------------------

Windows = driver.windows_handles —----------property


driver.switch_to.window(Windows [1])
And again back to window;---
driver.switch_to.window(Windows [0])

driver.close():--------only tab is close


driver.quit():------browser is close

Handles the Frames:---------------------------------------------------------------------

HTML component but this not part of page


<iframe> tag to know that this is a frame
We can use only ID or name
Syntax:--
driver.switch_to.frame(“ID or Name path”)

And switch back to windows:---


driver.switch_to.default_content()
Javascript exicuter:---------

Scroll down:----
Syntax:-
driver.exicute_script(“window.scrollBy(0,document.body.scrollHeight);”)

Screen shot:-------------
driver.get_screenshot_as_file(“filename.png”)

Head Mode AND Headless Mode:-----------------------

Head mode:- that you browsers open and you can see all the actions
Headless Mode:--we will not see the browser invocation/invisible mode

Headless Mode:---
Create class ChromeOptions()
Syntax:-
chrome_options= webdriver.ChromeOptions()
chrome_options.add_argument(‘headless’)

Driver = webdriver.Chrome(service=service_obj, options=chrome_options)

chrome_options= webdriver.ChromeOptions()
chrome_options.add_argument(“--ignore-certificate-errors”)
chrome_options.add_argument(“--start-maximized”)

question:-How to sort the tables:-

Selenium Python Framework Design Plan:-----------------------------------------

1)pytest unit testing framework


2)understand logging and HTML report
3)page object design pattern scratch framework
4)data driven framework with Excel to selenium python tests
5)GIT version control

Pytest methods should be name star from “test”


ALL test run ===== py.test
This command run all test cases
Flags:-----
py.test -v
V stands for vergos, that will give more information

Py.test -v -s
-s is print the output in terminal

Run only 1 file:---------


If you want to run only specific file so give that file
Command :----Py.test test_one.py -v -s

How to run for 1 test case for 1 file and another test for another file:?-----------------
You can put regular expression
-k stands for specific regulation what you giving

Example:-
def test_RBIbankcards():
print("test pass 2")

def test_ICICIbankcards():
print("test pass 3")

Output:-terminal
py.test -k bankcards -v -s

platform win32 -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0 -- C:\Python310\python.exe


cachedir: .pytest_cache
metadata: {'Python': '3.10.4', 'Platform': 'Windows-10-10.0.19044-SP0', 'Packages':
{'pytest': '7.1.2', 'py': '1.11.0', 'pluggy': '1.0.0'}, 'Plugins': {'html': '3.1.1', 'metadata': '2.0.1',
'xdist': '3.0.2'}, 'JAVA_HOME': 'C:\\Pro
gram Files\\Java\\jdk-18.0.1'}
rootdir: C:\Users\Cliffex-Lead\pythonProject46
plugins: html-3.1.1, metadata-2.0.1, xdist-3.0.2
collected 5 items / 3 deselected / 2 selected

test_projects/test_new.py::test_RBIbankcards test pass 2


PASSED
test_projects/test_new.py::test_ICICIbankcards test pass 3
PASSED

-k stands for methods names execution


-s for loggs in output
-v more info

How to run smoke testcases :-we use mark


You can run mark(tag) test and then run with -m

File1:-
@pytest.mark.smoke
def test_print():
print("test pass")

def test_test2(self):
print("test pass 2")

def test_test3(self):
print("test pass 3")

File 2:=
import pytest

def test_RBIbankcards():
print("test pass 2")

@pytest.mark.smoke
def test_ICICIbankcards():
print("test pass 3")

Terminal:-
py.test -m smoke -v -s
platform win32 -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0 --
C:\Python310\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.10.4', 'Platform': 'Windows-10-10.0.19044-SP0',
'Packages': {'pytest': '7.1.2', 'py': '1.11.0', 'pluggy': '1.0.0'}, 'Plugins':
{'html': '3.1.1', 'metadata': '2.0.1', 'xdist': '3.0.2'}, 'JAVA_HOME':
'C:\\Pro
gram Files\\Java\\jdk-18.0.1'}
rootdir: C:\Users\Cliffex-Lead\pythonProject46
plugins: html-3.1.1, metadata-2.0.1, xdist-3.0.2
collected 5 items / 3 deselected / 2 selected

test_projects/test_classes.py::test_print test pass


PASSED
test_projects/test_new.py::test_ICICIbankcards test pass 3
PASSED

==============================================================================
=========================== warnings summary
==============================================================================
============================
test_projects\test_classes.py:4
C:\Users\Cliffex-Lead\pythonProject46\test_projects\test_classes.py:4:
PytestUnknownMarkWarning: Unknown pytest.mark.smoke - is this a typo? You can
register custom marks to avoid this warning - for details, see https://docs.py
test.org/en/stable/how-to/mark.html
@pytest.mark.smoke

test_projects\test_new.py:8
C:\Users\Cliffex-Lead\pythonProject46\test_projects\test_new.py:8:
PytestUnknownMarkWarning: Unknown pytest.mark.smoke - is this a typo? You can
register custom marks to avoid this warning - for details, see
https://docs.pytest
.org/en/stable/how-to/mark.html
@pytest.mark.smoke

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
How to skip the test:-------------------------------
You can skip test with @pytest.mark.skip
import pytest

@pytest.mark.skip
def test_RBIbankcards():
print("test pass 2")

@pytest.mark.smoke
def test_ICICIbankcards():
print("test pass 3")

Terminal:-py.test -v -s

platform win32 -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0 -- C:\Python310\python.exe


cachedir: .pytest_cache
metadata: {'Python': '3.10.4', 'Platform': 'Windows-10-10.0.19044-SP0', 'Packages': {'pytest':
'7.1.2', 'py': '1.11.0', 'pluggy': '1.0.0'}, 'Plugins': {'html': '3.1.1', 'metadata': '2.0.1', 'xdist': '3.0.2'},
'JAVA_HOME': 'C:\\Pro
gram Files\\Java\\jdk-18.0.1'}
rootdir: C:\Users\Cliffex-Lead\pythonProject46
plugins: html-3.1.1, metadata-2.0.1, xdist-3.0.2
collected 5 items

test_projects/test_classes.py::test_print test pass


PASSED
test_projects/test_classes.py::test_test2 ERROR
test_projects/test_classes.py::test_test3 ERROR
test_projects/test_new.py::test_RBIbankcards SKIPPED (unconditional skip)
test_projects/test_new.py::test_ICICIbankcards test pass 3
PASSED
What are FIXTURES:-----------------------------

Fixture use for opening a browser or setting some database instances, creating some
configuration properties and environment variables
Create conftest.py file
Fixture are use to setup and tear down methods for the test cases conftest file generlized
Fixture and make it available to all test cases

@pytest.fixture
def setup():
print("i will 1st")
yield
print("i m lastt")

def test_ICICIbankcards(setup):
print("test pass 3")

Terminal:--

collecting ... collected 1 item

test_new.py::test_ICICIbankcards i will 1st


PASSED [100%]test pass 3
i m lastt

scope=class:------------------------------------------------
IN fixture if you want to print only 1st time and after last then we will use
scope .

import pytest

@pytest.fixture(scope="class")
def setup():
print("i will 1st")
yield
print("i m lastt")

@pytest.mark.usefixtures("setup")
class TestGood:
def test_print(self):
print("test pass")

def test_test2(self):
print("test pass 2")

def test_test3(self):
print("test pass 3")

def test_test4(self):
print("test pass 3")

Terminal;-----------------------------

collecting ... collected 4 items

test_classes.py::TestGood::test_print i will 1st


PASSED [ 25%]test pass

test_classes.py::TestGood::test_test2 PASSED [
50%]test pass 2

test_classes.py::TestGood::test_test3 PASSED [
75%]test pass 3

test_classes.py::TestGood::test_test4 PASSED
[100%]test pass 3
i m lastt

@pytest.mark.usefixtures("dataset") :---- this is only class

How to run a test with multiples datasets:--------


Data driven and parameterization can be done with retur
statement in tuple format
When you define fixture scope to class only, it will run once
before class is initiated at the end

@pytest.fixture(params=['chrome','firefox','IE'])
def dataset(request):
return request.param

def test_crossbrowser(dataset):
print(dataset)

Output:--

collecting ... collected 3 items

test_new.py::test_crossbrowser[chrome] PASSED
[ 33%]chrome
test_new.py::test_crossbrowser[firefox] PASSED
[ 66%]firefox

test_new.py::test_crossbrowser[IE] PASSED
[100%]IE

How to generate the HTML reports:---------------

Pip install pytest-html

Generate the html report;---


Py.test –-html=report.html

How the logs are printed:-----------------------

By using logging class


Logger = logging.getlogger(__name__)

import logging

def test_logging():
logger = logging.getLogger(__name__)

filehandler = logging.FileHandler("logfile.log")
formatter = logging.Formatter("%(asctime)s :
%(levelname)s : %(name)s : %(message)s")
filehandler.setFormatter(formatter)

logger.addHandler(filehandler)

logger.setLevel(logging.INFO)
logger.debug("This is a debug")
logger.info("This is a info")
logger.warning('this is a warning')
logger.error('This is a error')
logger.critical("this is a critical ")

Output:---------------------------------------------------

2023-03-27 18:44:24,181 : INFO : test_projects.test_logging : This is a info


2023-03-27 18:44:24,181 : WARNING : test_projects.test_logging : this is a
warning
2023-03-27 18:44:24,181 : ERROR : test_projects.test_logging : This is a error
2023-03-27 18:44:24,182 : CRITICAL : test_projects.test_logging : this is a
critical

LOGs inject into


Fremeworks:-----------------------------------

File 1;-

import inspect
import logging

class Baseclasses:
def get_logger(self):
loggername= inspect.stack()[1][3]
logger = logging.getLogger(loggername)

filehandler = logging.FileHandler('generate.log')
formatter = logging.Formatter("%(asctime)s : %(name)s : %(levelname)s :
%(message)s")

filehandler.setFormatter(formatter)

logger.addHandler(filehandler)

logger.setLevel(logging.INFO)

return logger
File 2:-

import logging

def test_loggerrr():
logger = logging.getLogger(__name__)

filehandler = logging.FileHandler('generate.log')
formatter = logging.Formatter("%(asctime)s : %(name)s : %(levelname)s :
%(message)s")

filehandler.setFormatter(formatter)

logger.addHandler(filehandler)

logger.setLevel(logging.DEBUG)
logger.debug("this is debuggg")
logger.error("this is debuggg")
logger.info("this is debuggg")
logger.critical("this is debuggg")
logger.warning("this is debuggg")

File 3:--
@pytest.fixture(scope='class')
def datatest():

return ['piyush','dravyakar','class','9th']

File 4:-
import pytest

from test_projects.BaseClass import Baseclasses

@pytest.mark.usefixtures('datatest')
class Test_Example(Baseclasses):
def test_oneandonly(self, datatest):
log = self.get_logger()
log.info(datatest[1])
log.info(datatest[0])
print(datatest[2])

print("good test ")


Output:----
2023-03-28 16:11:14,918 : test_oneandonly : INFO : dravyakar
2023-03-28 16:11:14,918 : test_oneandonly : INFO : piyush

Explicit wait
Explicit wait is used to provide some extra halt in program until that written code is fully
executed for the specific functionality that usually takes time to implement.

Code format:

Wait = WebDriverWait(Driver, Time)


Wait.until(expected_conditions.presence_of_element_located(By.ID, ‘value’))
Implicit wait
Implicit wait is used to halt the program until the written code is executed and it is used as a
common time gap for all the functionality.

Actions
ActionChains are a way to automate low-level interactions such as mouse
movements, mouse button actions, keypress, and context menu interactions.
Action = ActionChains(Driver)
Action.move_to_element(Driver.find_element(By.ID, ‘Value’)).perform()

You might also like