Python Piyush Automation
Python Piyush Automation
Data type:-Numeric,string,list(array),tuple,dict
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
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
except:
print("doebt send any erroer msg")
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
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”
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:-----------------------------
.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)
Scroll down:----
Syntax:-
driver.exicute_script(“window.scrollBy(0,document.body.scrollHeight);”)
Screen shot:-------------
driver.get_screenshot_as_file(“filename.png”)
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’)
chrome_options= webdriver.ChromeOptions()
chrome_options.add_argument(“--ignore-certificate-errors”)
chrome_options.add_argument(“--start-maximized”)
Py.test -v -s
-s is print the output in terminal
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
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
==============================================================================
=========================== 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
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:--
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;-----------------------------
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.fixture(params=['chrome','firefox','IE'])
def dataset(request):
return request.param
def test_crossbrowser(dataset):
print(dataset)
Output:--
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
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:---------------------------------------------------
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
@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])
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:
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()