Notes
Notes
Note: Each curly brace will store the value of one variable. In this example 'Value is' is stored in first {}
and value of b in second {}
b=3
print(type(b))
Output - [1, 2, 3]
Output -
25
first name
Section 5:
1. How to use If else condition?
listOfNumber = [1, 2, 5, 6, 8]
for i in listOfNumber:
print(i)
Note:
- for is loop which helps to iterate over the list, tuple or dictionary, String etc.
- Variable ‘I’ used in the above example will help to iterate through the list
- Colon(:) is used to indicate the start of a new block of code
- Code indentation is important for python to understand the code format.
it = 10
while it > 5:
print(it)
it = it - 1
print(a)
Note:
- while loop while continue iterating until the condition is false
- There are 2 keywords that can be used with while loop – break and continue
- break keyword – it will terminate the entire loop
-continue keyword – It will terminate the current execution of the loop and will start from top of
the loop
- Colon(:) is used to indicate the start of a new block of code
- Code indentation is important for python to understand the code format.
Section 6:
1. What is class?
- Class is a user defined blueprint or prototype
- Class includes – Methods, Class variables, Instance variables, Constructor, etc.
class NewClass:
num = 190 # Class variable
3. What is constructor?
- Constructor is a method which is called when the object of the class is created.
- There are 2 types of constructor,
Default Constructor: It is a default constructor which is called when there is no user defined
constructor. It doesn’t accept any arguments
Parameterized Constructor: Constructor with parameters is known as parameterized constructor
Example:
class ConstTest: # class created
num = 20 # class variable
4. What is Inheritance?
- Accessing properties of all the Parent class in the Child class
class ChildImpl(ConstTest):
5. What is String?
- In Python, a string is a sequence of characters
name = "Rahul"
7. How to print a String?
name = "Rahul"
print(name)
8. How to print 4th character from the String
name = "QAClick"
print(name[3])
9. How to print substring from a String?
name = "QAClick"
print(name[0:4]) # Print substring 0 to n-1
Section 7:
1. How to read characters from a text file?
file = open('Content.txt')
for line in file.readlines():
print(line)
Section 8:
1. How to raise an exception?
-Using raise Exception keyword
-Using assert keyword
ItemsInCart = 0
ItemsInCart = 0
assert (ItemsInCart == 1)
#In this example, the filelog.txt file is missing which will raise an
exception and will be caught in except block
try:
with open('filelog.txt', 'r') as reader:
reader.read()
except:
print("File not present")
# finallly block is used with try and except block. finally block will
always execute.
try:
with open('Content.txt', 'r') as reader:
reader.read()
except Exception as e:
print(e)
finally:
print("Test Pass: Clean up process")
Section 9:
1. How to install selenium package in python interpreter?
- Windows: File à Settings à Project Interpreter à Click + icon à Install Selenium
- MAC OS: Preferences à Project Interpreter à Click + icon à Install Selenium
service_obj = Service("path\to\chromedriver.exe")
driver = webdriver.Chrome(service=service_obj)
driver.get("https://rahulshettyacademy.com/loginpagePractise/")
driver.maximize_window()
4. How to print title of the page and current url?
print(driver.title)
print(driver.current_url)
5. How to invoke Firefox and Edge browser?
# Firefox
from selenium.webdriver.firefox.service import Service
service_obj = Service(("path\to\geckodriver.exe"
driver = webdriver.Firefox(service=service_obj)
# Edge
from selenium.webdriver.edge.service import Service
service_obj = Service("path\to\msedgedriver.exe")
driver = webdriver.Edge(service=service_obj)
Section 10:
1. Which locator’s strategies are supported by Selenium?
ID
class name
name
Xpath
tagName
link text
Partial link text
CSS
Example,
driver.find_element(By.XPATH, "//input[@type='email']")
Section 11:
1. Websites for practice?
- https://rahulshettyacademy.com/angularpractice/
- https://rahulshettyacademy.com/AutomationPractice/#/
-https://rahulshettyacademy.com/seleniumPractise/#/
select_by_index(index)
select_by_value(“value”)
select_by_visible_text(“visible text”)
5. Below is the example on how to select option from dropdown using select_by_index()
#Iterating checkboxes using for loop and checking the checkbox 'option3'
for checkbox in checkboxes:
if checkbox.get_attribute("value") == "option3":
checkbox.click()
driver.switch_to.alert
#Switch to alert
alert = driver.switch_to.alert
driver.implicitly_wait(seconds)
#WebDriverWait is class
#It takes 2 arguments – web driver and seconds(time to wait)
wait = WebDriverWait(driver, 10)
Section 13:
Assignment 2:
driver.maximize_window()
driver.implicitly_wait(2)
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element(By.XPATH, "//input[@type='search']").send_keys("ber")
sleep(3)
results = driver.find_elements(By.XPATH, "//div[@class='products']/div")
count = len(results)
print(count)
assert count > 0
#Assignment 1:
for result in results:
actualVegetables.append(result.find_element(By.XPATH, "h4").text)
result.find_element(By.XPATH, "div/button").click()
print(actualVegetables)
assert expectedVegetables == actualVegetables
driver.find_element(By.XPATH, "//img[@alt='Cart']").click()
driver.find_element(By.XPATH, "//button[text()='PROCEED TO
CHECKOUT']").click()
#Sum Validation
prices = driver.find_elements(By.XPATH, "//td[5]//p[@class='amount']")
sum = 0
for price in prices:
sum = sum + int(price.text)
print(sum)
totalAmount = int(driver.find_element(By.XPATH,
"//span[@class='totAmt']").text)
assert sum == totalAmount
driver.find_element(By.XPATH,
"//input[@class='promoCode']").send_keys("rahulshettyacademy")
driver.find_element(By.XPATH, "//button[@class='promoBtn']").click()
#Explicit wait - It is used to wait explicitly based on the given time for a
particular element
wait = WebDriverWait(driver, 10)
wait.until(expected_conditions.presence_of_element_located((By.XPATH,
"//span[@class='promoInfo']")))
print(driver.find_element(By.XPATH, "//span[@class='promoInfo']").text)
action.move_to_element(driver.find_element(By.XPATH,
"//button[@id='mousehover']")).perform() #mouse hover
2. How to right click on an element?
action.move_to_element(driver.find_element(By.LINK_TEXT,
"Reload")).click().perform() #mouse hover + click
4. What is the import statement for Actions class?
7. How to scroll at a certain axis on the web page using Javascript Executor?
driver.execute_script("window.scrollBy(0,700);")
8. How to scroll at the bottom of the web page using Javascript Executor?
sort()
10. What is ChromeOptions?
- ChromeOptions is used for customizing the ChromeDriver session
chrome_options.add_argument("--headless")
chrome_options.add_argument("--ignore-certificate-errors")
chrome_options.add_argument("--start-maximized")
Section 16: Complete code is provided in the last lecture of this section.
2. What is Pytest?
- The pytest framework makes it easy to write small, readable tests, and can scale to support
complex functional testing for applications and libraries.
#Method declaration
def test_firstProgram():
print("Hello")
10. How to run a particular python file in pytest from command prompt?
- py.test python_file_name -v –s
11. How to execute test cases using method/function name from command prompt?
- py.test -k <partial_method_name> -v –s
@pytest.mark.skip
def test_CreditCard1():
print("Credit Card 1")
@pytest.mark.xfail
def test_tag():
print("Tag 1")
18. Example:
print("First demo")
19. Which keyword helps to execute the set of code after the test case execution completion?
- yeild
Conftest.py
# Formatter will help to format the log, asctime: timestamp, levelname: debug,
info, error etc., name: File name, messsage: message
formatter = logging.Formatter("%(asctime)s :%(levelname)s :%(name)s :%
(message)s")
# created object of logging and __name__ will help use to get the file name
logger = logging.getLogger(__name__)
# filehandler is passed in logger which has file path and file format
logger.addHandler(filehandler)
# setLevel will print the value from Info. It will skip debug
logger.setLevel(logging.INFO)
logger.warning("Warning message")