├── Python_basics
├── base
│ ├── __init__.py
│ ├── configreader.py
│ └── basetestcase.py
├── utilities
│ ├── __init__.py
│ ├── custom_logger.py
│ ├── driver_session.py
│ ├── using_wrappers_demo1.py
│ └── handy_wrappers.py
├── wait_types
│ ├── __init__.py
│ ├── implicit_wait_demo.py
│ ├── explicit_wait_demo2.py
│ ├── explicit_wait_type.py
│ └── explicit_wait_demo1.py
├── AdvancedDataTypes
│ ├── __init__.py
│ ├── 025 dictnested.py
│ ├── 027 tuplesdemo.py
│ ├── 026 dictmethods.py
│ ├── 022 listdemo.py
│ ├── 023 listmethods.py
│ └── 024 dictdemo.py
├── Exceptionhandling
│ ├── __init__.py
│ ├── 051 exceptionHandlingHomework.py
│ ├── 050 exceptionhandling2.py
│ └── 049 exceptionhandling1.py
├── LaunchBrowsers
│ ├── __init__.py
│ ├── Save_screenshot.py
│ ├── AllLinks.py
│ ├── GetImageIinks.py
│ ├── WriteDataToTxt.py
│ ├── interactingWithPage.py
│ ├── SeleniumClickButton.py
│ └── HeadlessBrowser.py
├── WorkingWithFiles
│ ├── __init__.py
│ ├── firstfile.txt
│ ├── 055 firstfile.txt
│ ├── 054 filedemo1.py
│ └── 056 withasdemo.py
├── unittestpackage
│ ├── __init__.py
│ ├── .cache
│ │ └── v
│ │ │ └── cache
│ │ │ └── lastfailed
│ ├── .DS_Store
│ ├── __init__.pyc
│ ├── 142 UnitTest-Introduction.pdf
│ ├── .pytest_cache
│ │ └── v
│ │ │ └── cache
│ │ │ └── nodeids
│ ├── test_case_demo1.py
│ ├── assert_demo.py
│ ├── test_suite_demo.py
│ ├── test_suite_html_report.py
│ ├── test_class2.py
│ ├── test_case_demo2.py
│ ├── test_class1.py
│ ├── test.py
│ └── assets
│ │ └── style.css
├── AdvancedLocators_CSS
│ ├── __init__.py
│ ├── 093 XPath-Cheat-Sheet.pdf
│ ├── 080 Interview-Questions.pdf
│ ├── 073 FindByIdName.py
│ ├── 075 FindByXPathCSS.py
│ ├── 076 FindByLinkText.py
│ ├── 077 FindByClassTag.py
│ ├── 079 ListOfElements.py
│ ├── 078 ByDemo.py
│ └── 074 FindByIdName.py
├── Data_Driven_Testing
│ ├── __init__.py
│ ├── 189 testdata.csv
│ ├── 188 3-read-data.py
│ └── 187 2-register-courses-multiple-data-set.py
├── Logging_infrastructure
│ ├── __init__.py
│ ├── 137 logging-demo1.py
│ ├── 138 logging-format.py
│ ├── 140 logging.txt
│ ├── 139 logger-demo-console.py
│ └── 141 logging-demo2.py
├── ProgramControlFlow
│ ├── __init__.py
│ ├── 036 rangedemo.py
│ ├── 031 conditional.py
│ ├── 032 whiledemo.py
│ └── 033 breakcontinue.py
├── AutomationFramework_Part_1
│ ├── __init__.py
│ ├── 165 4-login-tests.py
│ ├── 163 3-login-tests.py
│ ├── 166 5-login-page.py
│ ├── 167 6-selenium-driver.py
│ └── 168 7-selenium-driver.py
├── AutomationFramework_Part_2
│ ├── __init__.py
│ ├── 171 3-login-tests.py
│ ├── 173 5-webdriverfactory.py
│ ├── 169 1-selenium-driver.py
│ ├── 170 2-selenium-driver.py
│ └── 172 4-selenium-driver.py
├── AutomationFramework_Part_3
│ ├── __init__.py
│ ├── 175 2-teststatus.py
│ ├── 176 3-teststatus.py
│ ├── 178 5-teststatus.py
│ ├── 179 6-util.py
│ ├── 180 7-util.py
│ └── 174 1-selenium-driver.py
├── AutomationFramework_Part_4
│ ├── __init__.py
│ ├── 185 5-register-courses-tests.py
│ ├── 183 3-register-courses-pages.py
│ └── 184 4-register-courses-pages.py
├── ObjectOrientedProgramming
│ ├── __init__.py
│ ├── 053 modules-car.py
│ ├── 043 classdemo1.py
│ ├── 052 modules-demo1.py
│ ├── 044 classdemo2.py
│ ├── 045 classdemo3.py
│ ├── 046 classdemo-inheritance1.py
│ ├── 048 classexercise.py
│ └── 047 classdemo-inheritance2.py
├── RunningCompleteTestSuite
│ ├── __init__.py
│ ├── 192 3-test-suite-demo.py
│ ├── 191 2-login-tests.py
│ ├── 190 1-register-courses-csv-data.py
│ └── 193 4-webdriverfactory.py
├── SeleniumWebDriver_Advanced
│ ├── __init__.py
│ ├── 128 Interview-Questions.pdf
│ ├── RegularExpression.py
│ ├── UploadingFile.py
│ ├── 126 window-size.py
│ ├── Copypaste.py
│ ├── 125 javascript-execution.py
│ ├── right_click.py
│ ├── 122 auto-complete.py
│ ├── 123 screenshots.py
│ ├── 127 scrolling-element.py
│ ├── 124 screenshots-generic.py
│ ├── download.py
│ ├── DynamicWebTable1.py
│ ├── add_cookies.py
│ ├── Pyautogui.py
│ ├── DatePicker.py
│ ├── 120 calendar-selection.py
│ └── JavaScriptExamples.py
├── ComparisonAndBooleanOperators
│ ├── __init__.py
│ ├── 030 boolean-precedence.py
│ ├── 028 comparators.py
│ └── 029 boolean-opertors.py
├── MethodsWorkingWithReusableCode
│ ├── __init__.py
│ ├── 037 methodsdemo1.py
│ ├── 039 methodsdemo3.py
│ ├── 040 methodsdemo4.py
│ ├── 038 methodsdemo2.py
│ ├── 041 built-in-functions.py
│ └── 042 methodexercise.py
├── Pytest_AdvancedTestingFramework
│ ├── __init__.py
│ ├── 149 -PyTest Guide.pdf
│ ├── 148 test-case-demo1.py
│ ├── 150 test-case-demo2.py
│ ├── 154 conftest.py
│ ├── 155 conftest.py
│ ├── 152 test-case-demo3.py
│ ├── 157 conftest.py
│ ├── 156 conftest.py
│ ├── 158 conftest.py
│ └── 160 conftest.py
├── UnderstandingVariablesAndDataType
│ ├── __init__.py
│ ├── 012 Variables-Rules.pdf
│ ├── 011 variables.py
│ ├── 021 strings-formatting.py
│ ├── 014 numbers-operations.py
│ ├── 016 boolean.py
│ ├── 019 string-methods2.py
│ ├── 013 numbers.py
│ ├── 017 strings.py
│ └── 018 string-methods1.py
├── SeleniumWebDriverWorkingWithWebElements
│ ├── __init__.py
│ ├── 104 Interview-Questions.pdf
│ ├── 094 Browser-Interaction-And-Navigating-Web-Pages.pdf
│ ├── 099 WorkingWithElementsList.py
│ ├── 097 ElementState.py
│ ├── 101 DropdownSelect.py
│ ├── 098 RadioButtonsAndCheckboxes.py
│ ├── 095 BrowserInteractions.py
│ └── 103 HiddenElements.py
├── SeleniumWebDriver_SwitchWindowAndIFrame
│ ├── __init__.py
│ ├── 133 switch-to-alert.py
│ ├── SwitchToNewTab.py
│ ├── 132 switch-to-frame.py
│ └── 130 switch-to-window.py
├── SeleniumWebDriver_WorkingWithActionsClass
│ ├── __init__.py
│ ├── 136 sliders.py
│ ├── 135 drag-and-drop.py
│ └── 134 mouse-hovering.py
├── SeleniumWebDriverRunningTestsOnVariousBrowsers
│ ├── __init__.py
│ ├── 071 Interview-Questions.pdf
│ ├── 066 RunChromeTestsWindows.py
│ ├── 064 RunFFTests.py
│ └── 070 RunSafariTests.py
├── SeleniumWebDriverUsefulMethodsAndProperties
│ ├── __init__.py
│ ├── 112 Interview-Questions.pdf
│ ├── 107 getText.py
│ ├── 108 getAttribute.py
│ ├── 110 element-present-check.py
│ ├── 111 dynamic-xpath-format.py
│ └── 106 2-airbnb-exercise1.py
├── Au3Record.rar
├── PythonTutorial.rar
├── Drivers
│ ├── chromedriver.exe
│ └── geckodriver.exe
├── SeleniumWD2Tutorial.rar
├── .project
└── .pydevproject
├── index.rst
└── README.md
/Python_basics/base/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/utilities/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/wait_types/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedDataTypes/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/Exceptionhandling/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/WorkingWithFiles/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/Data_Driven_Testing/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/Logging_infrastructure/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/ProgramControlFlow/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_1/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_2/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_3/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_4/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/RunningCompleteTestSuite/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/ComparisonAndBooleanOperators/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/MethodsWorkingWithReusableCode/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/.cache/v/cache/lastfailed:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_SwitchWindowAndIFrame/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_WorkingWithActionsClass/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/WorkingWithFiles/firstfile.txt:
--------------------------------------------------------------------------------
1 | 1
2 | 2
3 | 3
4 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverRunningTestsOnVariousBrowsers/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Python_basics/WorkingWithFiles/055 firstfile.txt:
--------------------------------------------------------------------------------
1 | first line
2 | second line
3 | third line
--------------------------------------------------------------------------------
/Python_basics/Au3Record.rar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/Au3Record.rar
--------------------------------------------------------------------------------
/Python_basics/PythonTutorial.rar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/PythonTutorial.rar
--------------------------------------------------------------------------------
/Python_basics/Drivers/chromedriver.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/Drivers/chromedriver.exe
--------------------------------------------------------------------------------
/Python_basics/Drivers/geckodriver.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/Drivers/geckodriver.exe
--------------------------------------------------------------------------------
/Python_basics/SeleniumWD2Tutorial.rar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/SeleniumWD2Tutorial.rar
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/unittestpackage/.DS_Store
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/unittestpackage/__init__.pyc
--------------------------------------------------------------------------------
/Python_basics/Data_Driven_Testing/189 testdata.csv:
--------------------------------------------------------------------------------
1 | courseName,ccNum,ccExp,ccCVV
2 | JavaScript for beginners,10,1220,10
3 | Learn Python 3 from scratch,20,1220,20
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/142 UnitTest-Introduction.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/unittestpackage/142 UnitTest-Introduction.pdf
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/093 XPath-Cheat-Sheet.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/AdvancedLocators_CSS/093 XPath-Cheat-Sheet.pdf
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/080 Interview-Questions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/AdvancedLocators_CSS/080 Interview-Questions.pdf
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/149 -PyTest Guide.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/Pytest_AdvancedTestingFramework/149 -PyTest Guide.pdf
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/128 Interview-Questions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/SeleniumWebDriver_Advanced/128 Interview-Questions.pdf
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/012 Variables-Rules.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/UnderstandingVariablesAndDataType/012 Variables-Rules.pdf
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/104 Interview-Questions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/SeleniumWebDriverWorkingWithWebElements/104 Interview-Questions.pdf
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/112 Interview-Questions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/112 Interview-Questions.pdf
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverRunningTestsOnVariousBrowsers/071 Interview-Questions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/SeleniumWebDriverRunningTestsOnVariousBrowsers/071 Interview-Questions.pdf
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/053 modules-car.py:
--------------------------------------------------------------------------------
1 | """
2 | This is our own module which does not exist in python builtins
3 | """
4 |
5 | def info(make, model):
6 | print("Make of the car: " + make)
7 | print("Model of the car: " + model)
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/043 classdemo1.py:
--------------------------------------------------------------------------------
1 | """
2 | Object Oriented Programming
3 | """
4 |
5 | s = "this is a string"
6 | a = "one more string"
7 | s.upper()
8 | s.lower()
9 |
10 | print(type('s'))
11 | print(type('a'))
12 | print(type([1, 2, 3]))
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/094 Browser-Interaction-And-Navigating-Web-Pages.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/venkywarriors/selenium_with_python/HEAD/Python_basics/SeleniumWebDriverWorkingWithWebElements/094 Browser-Interaction-And-Navigating-Web-Pages.pdf
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/.pytest_cache/v/cache/nodeids:
--------------------------------------------------------------------------------
1 | [
2 | "test_suite_demo.py::TestClass1::test_class1_methodA",
3 | "test_suite_demo.py::TestClass1::test_class1_methodB",
4 | "test_suite_demo.py::TestClass2::test_class2_methodA",
5 | "test_suite_demo.py::TestClass2::test_class2_methodB"
6 | ]
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/011 variables.py:
--------------------------------------------------------------------------------
1 | """
2 | table
3 | object reference count
4 | """
5 |
6 | a="nyc"
7 | b="nyc"
8 |
9 | print(a)
10 |
11 | a=123
12 |
13 | print(a)
14 | print(b)
15 |
16 | b=456
17 | print(b)
18 |
19 | c='nyc'
20 | d=c
21 |
22 | print(c==d)
23 | print(d is c)
--------------------------------------------------------------------------------
/Python_basics/ComparisonAndBooleanOperators/030 boolean-precedence.py:
--------------------------------------------------------------------------------
1 | """
2 | 1. not
3 | 2. and
4 | 3. or
5 | """
6 |
7 | bool_output = True or not False and False
8 | # True
9 | print(bool_output)
10 |
11 | bool_output_1 = (10 == 10 or not 10 > 10) and 10 > 10
12 | # True or True -> True and False -> False
13 | print(bool_output_1)
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/021 strings-formatting.py:
--------------------------------------------------------------------------------
1 | """
2 | Examples to show how string formatting works in python
3 | """
4 |
5 | city = "nyc"
6 | event = "show"
7 |
8 | print("Welcome to " + city + " and enjoy the " + event)
9 | print("Welcome to %s" % city)
10 | print("Welcome to %s and enjoy the %s" % (city, event))
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/052 modules-demo1.py:
--------------------------------------------------------------------------------
1 | """
2 | https://docs.python.org/3/library/
3 | """
4 | import math
5 | from math import sqrt
6 |
7 | class ModulesDemo():
8 |
9 | def builtin_modules(self):
10 | print(math.sqrt(100))
11 | print(sqrt(100))
12 |
13 |
14 | m = ModulesDemo()
15 | m.builtin_modules()
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/014 numbers-operations.py:
--------------------------------------------------------------------------------
1 | # This is a one line comment
2 | # Exponentiation
3 | # 10 * 10 ... 20
4 | exponents = 10 ** 20
5 | print(exponents)
6 |
7 |
8 | """
9 | This is a multi-line comment
10 | Modulo - It returns the remainder
11 | """
12 |
13 | remainder = 11 % 3
14 | print(remainder)
15 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedDataTypes/025 dictnested.py:
--------------------------------------------------------------------------------
1 | """
2 | Nested Dictionary:
3 | d = {'k1': {'nestk1':'nestvalue1', 'nestk2': 'nestvalue2'}}
4 | d['k1']['nestk1']
5 | """
6 |
7 | cars = {'bmw': {'model': '550i', 'year': 2016}, 'benz': {'model': 'E350', 'year': 2015}}
8 | bmw_year = cars['bmw']['year']
9 | print(bmw_year)
10 | print(cars['benz']['model'])
--------------------------------------------------------------------------------
/Python_basics/WorkingWithFiles/054 filedemo1.py:
--------------------------------------------------------------------------------
1 | """
2 | File I/O
3 | 'w' -> Write-Only Mode
4 | 'r' -> Read-only Mode
5 | 'r+' -> Read And Write Mode
6 | 'a' -> Append Mode
7 | """
8 |
9 | my_list = [1, 2, 3]
10 |
11 | my_file = open("firstfile.txt", "w")
12 |
13 | for item in my_list:
14 | my_file.write(str(item) + "\n")
15 |
16 | my_file.close()
--------------------------------------------------------------------------------
/Python_basics/Logging_infrastructure/137 logging-demo1.py:
--------------------------------------------------------------------------------
1 | """
2 | Logging Demo 1
3 | Logging Levels
4 | DEBUG
5 | INFO
6 | WARNING
7 | ERROR
8 | CRITICAL
9 | """
10 | import logging
11 |
12 | logging.basicConfig(filename="test.log", level=logging.DEBUG)
13 | logging.warning("warning message")
14 | logging.info("info message")
15 | logging.error("error message")
--------------------------------------------------------------------------------
/Python_basics/ProgramControlFlow/036 rangedemo.py:
--------------------------------------------------------------------------------
1 | """
2 | Built-in function
3 | Creates a sequence of numbers but does not save them in memory
4 | Very useful for generating numbers
5 | """
6 |
7 | a = range(0, 20, 6)
8 | print(a)
9 | print(type(a))
10 |
11 | print(list(a))
12 |
13 |
14 | l = [1, 2, 3]
15 |
16 | for num in range(1, 4):
17 | print(num)
--------------------------------------------------------------------------------
/Python_basics/ProgramControlFlow/031 conditional.py:
--------------------------------------------------------------------------------
1 | """
2 | Conditional Logic
3 | """
4 |
5 | if 100 > 10:
6 | print("Hundred is greater than 10")
7 |
8 | value = 'red'
9 |
10 | if value == 'green':
11 | print("Go")
12 | elif value == 'yellow':
13 | print("Prepare to stop")
14 | else:
15 | print("Stop")
16 |
17 | print("It will always print")
18 |
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/044 classdemo2.py:
--------------------------------------------------------------------------------
1 | """
2 | Object Oriented Programming
3 | """
4 |
5 | class Car(object):
6 |
7 | def __init__(self, make, model="550i"):
8 | self.make = make
9 | self.model = model
10 |
11 | c1 = Car('bmw')
12 | print(c1.make)
13 | print(c1.model)
14 |
15 | c2 = Car('benz')
16 | print(c2.make)
17 | print(c2.model)
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/016 boolean.py:
--------------------------------------------------------------------------------
1 | """
2 | Examples to show how boolean works in python
3 | """
4 |
5 | a = True
6 | b = False
7 |
8 | print(a)
9 | print(b)
10 |
11 | print("**************************")
12 | print(bool(0))
13 | print(bool(1))
14 | print(bool(2))
15 |
16 | c = ""
17 | print(bool(c))
18 |
19 | c = "Some Value"
20 | print(bool(c))
--------------------------------------------------------------------------------
/Python_basics/MethodsWorkingWithReusableCode/037 methodsdemo1.py:
--------------------------------------------------------------------------------
1 | """
2 | A group of code statements which can perform some specific task
3 | Methods are reusable and can be called when needed in the code
4 | """
5 | def sum_nums(n1, n2):
6 | print(n1 + n2)
7 |
8 | sum_nums(2, 8)
9 |
10 | sum_nums(3, 3)
11 |
12 | l = [1, 2, 3]
13 | print(l.append(4))
14 | print(l)
15 |
16 | print(len(l))
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/148 test-case-demo1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 |
7 | @pytest.fixture()
8 | def setUp():
9 | print("Running demo1 setUp")
10 |
11 | def test_demo1_methodA(setUp):
12 | print("Running demo1 method A")
13 |
14 | def test_demo1_methodB(setUp):
15 | print("Running demo1 method B")
16 |
--------------------------------------------------------------------------------
/Python_basics/ComparisonAndBooleanOperators/028 comparators.py:
--------------------------------------------------------------------------------
1 | """
2 | == --> Value Equality
3 | != --> Not equal to
4 | < --> Less than
5 | > --> Greater than
6 | <= --> Less than or equal to
7 | >= --> Greater than or equal to
8 | """
9 |
10 | bool_one = 10 == 11
11 | not_equal = 10 != 11
12 | less_than = 10 < 11
13 | greater_than = 10 > 9
14 | lt_eq = 10 <= 10
15 | gt_eq = 10 >= 11 - 1
16 | print (gt_eq)
--------------------------------------------------------------------------------
/Python_basics/Exceptionhandling/051 exceptionHandlingHomework.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | def exceptionHandling():
6 | try:
7 | car = {"make": "bmw", "model": "550i", "year": "2016"}
8 | print(car["color"])
9 | except:
10 | print("Key not found")
11 | finally:
12 | print("Please try a different key")
13 |
14 | exceptionHandling()
15 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedDataTypes/027 tuplesdemo.py:
--------------------------------------------------------------------------------
1 | """
2 | Tuple
3 | Like list but they are immutable
4 | It means you can't change them
5 | """
6 |
7 | my_list = [1, 2, 3]
8 | print(my_list)
9 |
10 | my_list[0] = 0
11 | print(my_list)
12 |
13 | my_tuple = (1, 2, 3, 2, 2, 3)
14 | print(my_tuple)
15 |
16 | print(my_tuple[0])
17 |
18 | print(my_tuple[1:])
19 |
20 | print(my_tuple.index(2))
21 |
22 | print(my_tuple.count(3))
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/Save_screenshot.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 21, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 |
7 | import os
8 | from selenium import webdriver
9 |
10 | chrome_driver_path = os.path.dirname(__file__) + "\chromedriver.exe"
11 |
12 | driver=webdriver.Chrome(chrome_driver_path)
13 | driver.get('https://python.org')
14 | driver.save_screenshot("capture.png")
15 |
16 | driver.close()
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/019 string-methods2.py:
--------------------------------------------------------------------------------
1 | """
2 | Examples to show available string methods in python
3 | """
4 |
5 | # Replace Method
6 | a = "1abc2abc3abc4abc"
7 | print(a.replace('abc', 'ABC'))
8 |
9 | # Sub-Strings
10 | # starting index is inclusive
11 | # Ending index is exclusive
12 | sub = a[1:6]
13 | step = a[1:6:2]
14 |
15 | print("****************")
16 |
17 | print(sub)
18 | print(step)
--------------------------------------------------------------------------------
/Python_basics/MethodsWorkingWithReusableCode/039 methodsdemo3.py:
--------------------------------------------------------------------------------
1 | """
2 | Positional Parameters
3 | They are like optional parameters
4 | And can be assigned a default value, if no value is provided from outside
5 | """
6 |
7 | def sum_nums(n1, n2=4):
8 | """
9 | Get sum of two numbers
10 | :param n1:
11 | :param n2:
12 | :return:
13 | """
14 | return n1 + n2
15 |
16 | sum1 = sum_nums(4, n2=12)
17 | print(sum1)
--------------------------------------------------------------------------------
/Python_basics/ProgramControlFlow/032 whiledemo.py:
--------------------------------------------------------------------------------
1 | """
2 | Execute statements repeatedly
3 | Conditions are used to stop the execution of loops
4 | Iterable items are Strings, List, Tuple, Dictionary
5 | """
6 |
7 | x = 0
8 | while x < 10:
9 | print("Value of x is: " + str(x))
10 | x = x + 1
11 |
12 | l = []
13 | num = 0
14 | while num < 10:
15 | l.append(num)
16 | print("Value of num is: " + str(num))
17 | num += 1
18 |
19 | print(l)
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/150 test-case-demo2.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 | @pytest.yield_fixture()
7 | def setUp():
8 | print("Running demo2 setUp")
9 | yield
10 | print("Running demo2 tearDown")
11 |
12 | def test_demo2_methodA(setUp):
13 | print("Running demo2 method A")
14 |
15 | def test_demo2_methodB(setUp):
16 | print("Running demo2 method B")
17 |
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/013 numbers.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | int_num = 10
6 | float_num = 20.0
7 |
8 | print(int_num)
9 | print(float_num)
10 |
11 | a = 10
12 | b = 20
13 |
14 | print("*******************")
15 |
16 | add = a + b
17 | print(add)
18 |
19 | sub = b - a
20 | print(sub)
21 |
22 | multi = a * b
23 | print(multi)
24 |
25 | div_mychoice = b / a
26 | print(div_mychoice)
27 |
--------------------------------------------------------------------------------
/Python_basics/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Python_basics
4 |
5 |
6 |
7 |
8 |
9 | org.python.pydev.PyDevBuilder
10 |
11 |
12 |
13 |
14 |
15 | org.python.pydev.pythonNature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/AllLinks.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 21, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import os
7 | from selenium import webdriver
8 |
9 | chrome_driver_path = os.path.dirname(__file__) + "\chromedriver.exe"
10 |
11 | driver=webdriver.Chrome(chrome_driver_path)
12 |
13 | driver.get('https://www.w3.org/')
14 | for a in driver.find_elements_by_xpath('.//a'):
15 | print(a.get_attribute('href'))
16 |
17 | driver.close()
18 |
--------------------------------------------------------------------------------
/Python_basics/Exceptionhandling/050 exceptionhandling2.py:
--------------------------------------------------------------------------------
1 | """
2 | Exceptions are errors
3 | """
4 |
5 | def exceptionHandling():
6 | try:
7 | a = 10
8 | b = 20
9 | c = 0
10 |
11 | d = (a + b) / c
12 | print(d)
13 | except:
14 | print("In the except block")
15 | else:
16 | print("Because there was no exception, else is executed")
17 | finally:
18 | print("Finally, always executed")
19 |
20 | exceptionHandling()
--------------------------------------------------------------------------------
/Python_basics/Logging_infrastructure/138 logging-format.py:
--------------------------------------------------------------------------------
1 | """
2 | Logging Format
3 | https://docs.python.org/3/library/logging.html#logrecord-attributes
4 | https://docs.python.org/3/library/time.html#time.strftime
5 | """
6 | import logging
7 |
8 | logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',
9 | datefmt='%m/%d/%Y %I:%M:%S %p',level=logging.DEBUG)
10 | logging.warning("warning message")
11 | logging.info("info message")
12 | logging.error("error message")
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/017 strings.py:
--------------------------------------------------------------------------------
1 | """
2 | Examples to show how strings works in python
3 |
4 | Sequence of characters
5 | Contains a-z, 0-9, @
6 | In double or single quotes
7 | """
8 |
9 | a = "This is a simple string"
10 | b = 'Using single quotes'
11 |
12 | print(a)
13 | print(b)
14 |
15 | c = "Need to use 'quotes' inside a string"
16 | print(c)
17 |
18 | d = "Another way to handle \"quotes\""
19 | print(d)
20 |
21 | a = "This is a single\
22 | string"
23 | print(a)
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/154 conftest.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 |
7 | @pytest.yield_fixture()
8 | def setUp():
9 | print("Running method level setUp")
10 | yield
11 | print("Running method level tearDown")
12 |
13 |
14 | @pytest.yield_fixture(scope="module")
15 | def oneTimeSetUp():
16 | print("Running conftest demo one time setUp")
17 | yield
18 | print("Running conftest demo one time tearDown")
19 |
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/155 conftest.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 |
7 | @pytest.yield_fixture()
8 | def setUp():
9 | print("Running method level setUp")
10 | yield
11 | print("Running method level tearDown")
12 |
13 |
14 | @pytest.yield_fixture(scope="module")
15 | def oneTimeSetUp():
16 | print("Running conftest demo one time setUp")
17 | yield
18 | print("Running conftest demo one time tearDown")
19 |
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/GetImageIinks.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 21, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import os
7 | from selenium import webdriver
8 |
9 | chrome_driver_path = os.path.dirname(__file__) + "\chromedriver.exe"
10 |
11 | driver=webdriver.Chrome(chrome_driver_path)
12 | driver.get('http://imgur.com/')
13 |
14 | images = driver.find_elements_by_tag_name('img')
15 |
16 |
17 | for image in images:
18 | print(image.get_attribute('src'))
19 |
20 |
21 | driver.close()
22 |
23 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedDataTypes/026 dictmethods.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | """
6 | Dictionary Methods
7 | """
8 |
9 | car = {'make': 'bmw', 'model': '550i', 'year': 2016}
10 | cars = {'bmw': {'model': '550i', 'year': 2016}, 'benz': {'model': 'E350', 'year': 2015}}
11 |
12 | print(car.keys())
13 | print(cars.keys())
14 | print(car.values())
15 | print(cars.values())
16 | print(car.items())
17 |
18 | car_copy = car.copy()
19 | print(car_copy)
20 |
21 | print(car.pop('model'))
22 | print(car)
23 |
--------------------------------------------------------------------------------
/Python_basics/Data_Driven_Testing/188 3-read-data.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import csv
6 | def getCSVData(fileName):
7 | # create an empty list to store rows
8 | rows = []
9 | # open the CSV file
10 | dataFile = open(fileName, "r")
11 | # create a CSV Reader from CSV file
12 | reader = csv.reader(dataFile)
13 | # skip the headers
14 | next(reader)
15 | # add rows from reader to list
16 | for row in reader:
17 | rows.append(row)
18 | return rows
19 |
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/045 classdemo3.py:
--------------------------------------------------------------------------------
1 | """
2 | Object Oriented Programming
3 | """
4 |
5 | class Car(object):
6 |
7 | wheels = 4
8 |
9 | def __init__(self, make, model):
10 | self.make = make
11 | self.model = model
12 |
13 | def info(self):
14 | print("Make of the car: " + self.make)
15 | print("Model of the car: " + self.model)
16 |
17 |
18 |
19 | c1 = Car('bmw', '550i')
20 | print(c1.make)
21 | #c1.info()
22 |
23 | c2 = Car('benz', 'E350')
24 | print(c2.make)
25 | #c2.info()
26 |
27 | print(Car.wheels)
--------------------------------------------------------------------------------
/Python_basics/.pydevproject:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | /${PROJECT_DIR_NAME}
5 | /${PROJECT_DIR_NAME}/PDF_documents
6 | /${PROJECT_DIR_NAME}/bc
7 |
8 | python interpreter
9 | Default
10 |
11 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedDataTypes/022 listdemo.py:
--------------------------------------------------------------------------------
1 | """
2 | Data type to store more than one value in one variable name
3 | List items are in brackets, separated with "," [ 1, 2, 3 ]
4 | """
5 |
6 | cars = [ "bmw", "honda", "audi"]
7 | empty_list = []
8 | print(empty_list)
9 | print(cars)
10 |
11 | print("*#"*20)
12 |
13 | print(cars[1])
14 |
15 | num_list = [1, 2, 3]
16 | sum_num = num_list[0] + num_list[1]
17 |
18 | print(sum_num)
19 |
20 | more_cars = [ "bmw", "honda", "audi"]
21 | print(more_cars[1])
22 |
23 | more_cars[1] = "Benz"
24 |
25 | print(more_cars[1])
26 | print(more_cars)
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/test_case_demo1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import unittest
6 |
7 | class TestCaseDemo1(unittest.TestCase):
8 |
9 | def setUp(self):
10 | print("I will run once before every testdemo")
11 |
12 | def test_methodA(self):
13 | print("Running method A")
14 |
15 | def test_methodB(self):
16 | print("Running method B")
17 |
18 | def tearDown(self):
19 | print("I will run after every testdemo")
20 |
21 | if __name__ == '__main__':
22 | unittest.main(verbosity=2)
23 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedDataTypes/023 listmethods.py:
--------------------------------------------------------------------------------
1 | """
2 | Built-in methods to help manipulating a list
3 | """
4 |
5 | cars = [ "bmw", "honda", "audi"]
6 |
7 | length = len(cars)
8 | print(length)
9 |
10 | cars.append("Benz")
11 | print(cars)
12 |
13 | cars.insert(1, "Jeep")
14 | print(cars)
15 |
16 | x = cars.index("honda")
17 | print(x)
18 |
19 | y = cars.pop()
20 | print(y)
21 | print(cars)
22 |
23 | cars.remove("Jeep")
24 | print(cars)
25 |
26 | slicing = cars[0:2]
27 | a = cars[1:]
28 | print(slicing)
29 | print(a)
30 |
31 | print("*#"*20)
32 | print(cars)
33 | cars.sort()
34 |
35 | print(cars)
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/assert_demo.py:
--------------------------------------------------------------------------------
1 | """
2 | https://docs.python.org/3/library/unittest.html#unittest.TestCase
3 | """
4 | import unittest
5 |
6 | class AssertDemo(unittest.TestCase):
7 |
8 | def test_assertTrueFalse(self):
9 | a = True
10 | self.assertTrue(a, "a is not false")
11 | b = False
12 | self.assertFalse(b, "b is not true")
13 |
14 | def test_assertEqual(self):
15 | a = "Test"
16 | b = "Test"
17 | self.assertEqual(a, b, msg="'a' is not equal to 'b'")
18 |
19 |
20 | if __name__ == '__main__':
21 | unittest.main(verbosity=2)
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/test_suite_demo.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import unittest
6 | from unittestpackage.test_class1 import TestClass1
7 | from unittestpackage.test_class2 import TestClass2
8 |
9 | # Get all tests from TestClass1 and TestClass2
10 | tc1 = unittest.TestLoader().loadTestsFromTestCase(TestClass1)
11 | tc2 = unittest.TestLoader().loadTestsFromTestCase(TestClass2)
12 |
13 | # Create a test suite combining TestClass1 and TestClass2
14 | smokeTest = unittest.TestSuite([tc1, tc2])
15 |
16 | unittest.TextTestRunner(verbosity=2).run(smokeTest)
17 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedDataTypes/024 dictdemo.py:
--------------------------------------------------------------------------------
1 | """
2 | Data type to store more than one value in one variable name, in terms of key value pairs
3 | Dictionary items are in brackets {} in key:value pairs, separated with "," {'k1':'v1', 'k2':'v2'}
4 | Not sequenced, no indexing -> Mapping
5 | """
6 |
7 | car = {'make': 'bmw', 'model': '550i', 'year': 2016}
8 | print(car)
9 |
10 | d = {}
11 |
12 | model = car['model']
13 |
14 | print(car['make'])
15 | print(model)
16 |
17 | d['one'] = 1
18 | d['two'] = 2
19 |
20 | print(d)
21 |
22 | sum_1 = d['two'] + 8
23 | print(sum_1)
24 | print(d)
25 | d['two'] = d['two'] + 8
26 | print(d)
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/046 classdemo-inheritance1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | class Car(object):
6 |
7 | def __init__(self):
8 | print("You just created the car instance")
9 |
10 | def drive(self):
11 | print("Car started...")
12 |
13 | def stop(self):
14 | print("Car stopped")
15 |
16 | class BMW(Car):
17 |
18 | def __init__(self):
19 | Car.__init__(self)
20 | print("You just created the BMW instance")
21 |
22 | c = Car()
23 | c.drive()
24 | c.stop()
25 |
26 | b = BMW()
27 | b.drive()
28 | b.stop()
29 |
--------------------------------------------------------------------------------
/Python_basics/UnderstandingVariablesAndDataType/018 string-methods1.py:
--------------------------------------------------------------------------------
1 | """
2 | Examples to show available string methods in python
3 | """
4 |
5 | # Accessing characters in a string
6 | # index starts from zero
7 | first = "nyc"[0]
8 | city = "sfo"
9 | print(first)
10 | ft = city[0]
11 | print(ft)
12 |
13 |
14 | """
15 | len()
16 | lower()
17 | upper()
18 | str()
19 | """
20 |
21 | stri = "This Is a Mixed Case"
22 | print(stri.lower())
23 | print(stri.upper())
24 | print(len(stri))
25 |
26 | print(stri + str(2))
27 |
28 | """
29 | Concatenation
30 | """
31 | print("Hello " + " " + " World !!!")
32 | print(first + " " + city)
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/WriteDataToTxt.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 21, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import os
7 | from selenium import webdriver
8 | import io
9 |
10 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
11 |
12 | driver=webdriver.Chrome(chrome_driver_path)
13 |
14 | driver.get('https://python.org')
15 |
16 | html = driver.page_source
17 |
18 | if(os.path.isfile("pageSource.txt")):
19 |
20 | os.remove("pageSource.txt")
21 |
22 | with io.FileIO("pageSource.txt", "w") as file:
23 | file.write(html.encode("utf-8"))
24 |
25 | driver.close()
--------------------------------------------------------------------------------
/Python_basics/RunningCompleteTestSuite/192 3-test-suite-demo.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import unittest
6 | from tests.home.login_tests import LoginTests
7 | from tests.courses.register_courses_csv_data import RegisterCoursesCSVDataTests
8 |
9 | # Get all tests from the test classes
10 | tc1 = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
11 | tc2 = unittest.TestLoader().loadTestsFromTestCase(RegisterCoursesCSVDataTests)
12 |
13 | # Create a test suite combining all test classes
14 | smokeTest = unittest.TestSuite([tc1, tc2])
15 |
16 | unittest.TextTestRunner(verbosity=2).run(smokeTest)
17 |
--------------------------------------------------------------------------------
/Python_basics/WorkingWithFiles/056 withasdemo.py:
--------------------------------------------------------------------------------
1 | """
2 | With / As Keywords
3 | """
4 | # print("Normal Write Start")
5 | # my_write = open("textfile.txt", "w")
6 | # my_write.write("Trying to write to the file")
7 | # my_write.close()
8 | #
9 | #
10 | # print("Normal Read Start")
11 | # my_read = open("textfile.txt", "r")
12 | # print(str(my_read.read()))
13 |
14 | print("With As Write Start")
15 | with open("withas.txt", "w") as with_as_write:
16 | with_as_write.write("This is an example of with as write/read")
17 |
18 | print()
19 | print("With As Read Start")
20 | with open("withas.txt", "r") as with_as_read:
21 | print(str(with_as_read.read()))
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/test_suite_html_report.py:
--------------------------------------------------------------------------------
1 | """
2 | pip3 install pytest-html
3 | py, pytest, pytest-html
4 |
5 | Command: py.test test_suite_demo.py --html=report.html
6 | """
7 |
8 | import unittest
9 | from unittestpackage.test_class1 import TestClass1
10 | from unittestpackage.test_class2 import TestClass2
11 |
12 | # Get all tests from TestClass1 and TestClass2
13 | tc1 = unittest.TestLoader().loadTestsFromTestCase(TestClass1)
14 | tc2 = unittest.TestLoader().loadTestsFromTestCase(TestClass2)
15 |
16 | # Create a test suite combining TestClass1 and TestClass2
17 | smokeTests = unittest.TestSuite([tc1, tc2])
18 |
19 | unittest.TextTestRunner(verbosity=2).run(smokeTests)
--------------------------------------------------------------------------------
/Python_basics/ProgramControlFlow/033 breakcontinue.py:
--------------------------------------------------------------------------------
1 | """
2 | Break: To break out of the closest enclosing loop
3 | Continue: Go to the start of the closest enclosing loop
4 | """
5 |
6 | x = 0
7 | while x < 10:
8 | print("Value of x is: " + str(x))
9 | x = x + 1
10 |
11 | if x == 8:
12 | break
13 | print("This example is awesome")
14 | print("*"*20)
15 | else:
16 | print("Just broke out of the loop")
17 |
18 | # x = 0
19 | # while x < 10:
20 | # print("Value of x is: " + str(x))
21 | # x = x + 1
22 | #
23 | # if x == 8:
24 | # continue
25 | # print("This example is awesome")
26 | # print("*"*20)
27 | #
28 | # print("Just broke out of the loop")
--------------------------------------------------------------------------------
/Python_basics/Exceptionhandling/049 exceptionhandling1.py:
--------------------------------------------------------------------------------
1 | """
2 | Exceptions are errors
3 | We should handle exceptions in our code
4 | to make sure the code is working the way we want and is handling all the unwanted issues
5 | Link to 3.5 built-in exceptions - https://docs.python.org/3/library/exceptions.html
6 | """
7 |
8 | def exceptionHandling():
9 | try:
10 | a = 10
11 | b = 20
12 | c = 0
13 |
14 | d = (a + b) / c
15 | print(d)
16 | # except ZeroDivisionError:
17 | # print("Zero Division")
18 | # except TypeError:
19 | # print("Can't add string to integer")
20 | except:
21 | print("In the except block")
22 |
23 | exceptionHandling()
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/152 test-case-demo3.py:
--------------------------------------------------------------------------------
1 | """
2 | file name should start with test
3 | test method name should start with test
4 |
5 | py.test test_mod.py # run tests in module
6 | py.test somepath # run all tests below somepath
7 | py.test test_module.py::test_method # only run test_method in test_module
8 |
9 | -s to print statements
10 | -v verbose
11 | """
12 |
13 | import pytest
14 |
15 | @pytest.yield_fixture()
16 | def setUp():
17 | print("Running demo3 setUp")
18 | yield
19 | print("Running demo3 tearDown")
20 |
21 | def test_demo3_methodA(setUp):
22 | print("Running demo3 method A")
23 |
24 | def test_demo3_methodB(setUp):
25 | print("Running demo3 method B")
--------------------------------------------------------------------------------
/Python_basics/MethodsWorkingWithReusableCode/040 methodsdemo4.py:
--------------------------------------------------------------------------------
1 | """
2 | Variable Scope
3 | """
4 |
5 | a = 10
6 |
7 | def test_method(a):
8 | print("Value of local 'a' is: " + str(a))
9 | a = 2
10 | print("New value of local 'a' is: " + str(a))
11 |
12 | print("Value of global 'a' is: " + str(a))
13 | test_method(a)
14 | print("Did the value of global 'a' change? " + str(a))
15 |
16 | a = 10
17 |
18 | def test_method():
19 | global a
20 | print("Value of 'a' inside the method is: " + str(a))
21 | a = 2
22 | print("New value of 'a' inside the method is changed to: " + str(a))
23 |
24 | print("Value of global a is: " + str(a))
25 | test_method()
26 | print("Did the value of global 'a' change? " + str(a))
--------------------------------------------------------------------------------
/Python_basics/MethodsWorkingWithReusableCode/038 methodsdemo2.py:
--------------------------------------------------------------------------------
1 | """
2 | A group of code statements which can perform some specific task
3 | Methods are reusable and can be called when needed in the code
4 | """
5 |
6 | def sum_nums(n1, n2):
7 | """
8 | Get sum of two numbers
9 | :param n1:
10 | :param n2:
11 | :return:
12 | """
13 | return n1 + n2
14 |
15 | sum1 = sum_nums(2, 8)
16 |
17 | sum2 = sum_nums(3, 3)
18 |
19 | string_add = sum_nums('one', 2)
20 | print(string_add)
21 |
22 | print(sum1)
23 | print("*************")
24 |
25 | def isMetro(city):
26 | l = ['sfo', 'nyc', 'la']
27 |
28 | if city in l:
29 | return True
30 | else:
31 | return False
32 |
33 | x = isMetro('boston')
34 | print(x)
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverRunningTestsOnVariousBrowsers/066 RunChromeTestsWindows.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import os
7 |
8 | class RunChromeTestsWindows():
9 | # https://sites.google.com/a/chromium.org/chromedriver/downloads
10 | # http://chromedriver.storage.googleapis.com/index.html?path=2.21/
11 | def test(self):
12 | driverLocation = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 | os.environ["webdriver.chrome.driver"] = driverLocation
14 | driver = webdriver.Chrome(driverLocation)
15 | driver.get("http://www.letskodeit.com")
16 |
17 | chromeTest = RunChromeTestsWindows()
18 | chromeTest.test()
19 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverRunningTestsOnVariousBrowsers/064 RunFFTests.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import os
7 | import time
8 |
9 | class RunFFTests():
10 |
11 | def test(self):
12 |
13 | #executable_path = os.path.abspath('..') + "\\Drivers\\geckodriver.exe"
14 | # Instantiate FF Browser Command
15 | driver = webdriver.Firefox(executable_path=r'C:\\Users\venkateshwara.d\\git\\selenium_with_python\\Python_basics\\Drivers\\geckodriver.exe')
16 | # Open the provided URL
17 | driver.get("http://www.letskodeit.com")
18 |
19 | time.sleep(10)
20 | driver.quit()
21 |
22 | ff = RunFFTests()
23 | ff.test()
24 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverRunningTestsOnVariousBrowsers/070 RunSafariTests.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import os
7 |
8 | class RunSafariTests():
9 | # https://github.com/SeleniumHQ/selenium/wiki/SafariDriver
10 | # http://selenium-release.storage.googleapis.com/index.html
11 |
12 | def test(self):
13 | serverLocation = "/Users/atomar/Documents/workspace_personal/selenium/selenium-server-standalone-2.53.0.jar"
14 | os.environ["SELENIUM_SERVER_JAR"] = serverLocation
15 | # Instantiate Safari Browser Command
16 | driver = webdriver.Safari(quiet=True)
17 | # Open the provided URL
18 | driver.get("http://www.letskodeit.com")
19 |
20 | safari = RunSafariTests()
21 | safari.test()
22 |
--------------------------------------------------------------------------------
/Python_basics/utilities/custom_logger.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 24, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import inspect
6 | import logging
7 |
8 | def customLogger(logLevel=logging.INFO):
9 | # Gets the name of the class / method from where this method is called
10 | loggerName = inspect.stack()[1][3]
11 | logger = logging.getLogger(loggerName)
12 | # By default, log all messages
13 | logger.setLevel(logging.DEBUG)
14 |
15 | fileHandler = logging.FileHandler("{0}.log".format(loggerName), mode='w')
16 | fileHandler.setLevel(logLevel)
17 |
18 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s',
19 | datefmt='%m/%d/%Y %I:%M:%S %p')
20 | fileHandler.setFormatter(formatter)
21 | logger.addHandler(fileHandler)
22 |
23 | return logger
24 |
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/048 classexercise.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | class Fruit(object):
6 |
7 | def __init__(self):
8 | print("I am a fruit")
9 |
10 | def nutrition(self):
11 | print("I am full of vitamins")
12 |
13 | def fruit_shape(self):
14 | print("Every fruit can have different shape")
15 |
16 | class Orange(Fruit):
17 |
18 | def __init__(self):
19 | Fruit.__init__(self)
20 | print("I am Orange")
21 |
22 | def nutrition(self):
23 | print("I am full of vitamin c")
24 |
25 | def color(self):
26 | print("I keep it simple, the color is also orange")
27 |
28 | f = Fruit()
29 | f.nutrition()
30 | f.fruit_shape()
31 |
32 | o = Orange()
33 | o.nutrition()
34 | o.fruit_shape()
35 | o.color()
36 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/107 getText.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from utilities.handy_wrappers import HandyWrappers
8 | import time
9 |
10 | class GetText():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | driver = webdriver.Firefox()
15 | driver.maximize_window()
16 | driver.implicitly_wait(10)
17 | driver.get(baseUrl)
18 |
19 | openTabElement = driver.find_element(By.ID, "opentab")
20 | elementText = openTabElement.text
21 | print("Text on element is: " + elementText)
22 | time.sleep(1)
23 | driver.quit()
24 |
25 | ff = GetText()
26 | ff.test()
27 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/RegularExpression.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 23, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | from selenium import webdriver
7 | import re
8 | import os
9 |
10 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
11 |
12 | driver=webdriver.Chrome(chrome_driver_path)
13 | driver.maximize_window()
14 | driver.get("http://www.airindia.in/contact-details.htm")
15 | driver.implicitly_wait(3)
16 |
17 | doc = driver.page_source
18 |
19 | emails = [email.text for email in driver.find_elements_by_class_name('linkText') if "@" in email.text]
20 | '''emails = re.findall(r'[\w\.-]+@[\w\.-]+', doc)
21 | list_new = []
22 | for email in emails:
23 | list_new.append(str(email))
24 | print(email)'''
25 |
26 | driver.quit()
27 |
28 | print(emails)
29 |
--------------------------------------------------------------------------------
/Python_basics/Logging_infrastructure/140 logging.txt:
--------------------------------------------------------------------------------
1 | Please change the extension of this file to .conf and then use it
2 | Please also delete these line before using the file
3 | Udemy does not allow to upload .conf files, this is why I had to change the extension to .txt
4 | [loggers]
5 | keys=root,LoggerDemoConf
6 |
7 | [handlers]
8 | keys=fileHandler
9 |
10 | [formatters]
11 | keys=simpleFormatter
12 |
13 | [logger_root]
14 | level=DEBUG
15 | handlers=fileHandler
16 |
17 | [logger_LoggerDemoConf]
18 | level=INFO
19 | handlers=fileHandler
20 | qualname=demoLogger
21 | propagate=0
22 |
23 | [handler_fileHandler]
24 | class=FileHandler
25 | level=DEBUG
26 | formatter=simpleFormatter
27 | args=('test.log', 'w')
28 |
29 | [formatter_simpleFormatter]
30 | format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
31 | datefmt=%m/%d/%Y %I:%M:%S %p
--------------------------------------------------------------------------------
/Python_basics/ObjectOrientedProgramming/047 classdemo-inheritance2.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | class Car(object):
6 |
7 | def __init__(self):
8 | print("You just created the car instance")
9 |
10 | def drive(self):
11 | print("Car started...")
12 |
13 | def stop(self):
14 | print("Car stopped")
15 |
16 | class BMW(Car):
17 |
18 | def __init__(self):
19 | Car.__init__(self)
20 | print("You just created the BMW instance")
21 |
22 | def drive(self):
23 | super(BMW, self).drive()
24 | print("You are driving a BMW, Enjoy...")
25 |
26 | def headsup_display(self):
27 | print("This is a unique feature")
28 |
29 | c = Car()
30 | c.drive()
31 | c.stop()
32 |
33 | b = BMW()
34 | b.drive()
35 | b.stop()
36 | b.headsup_display()
37 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/073 FindByIdName.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 |
7 | class FindByIdName():
8 |
9 | def test(self):
10 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
11 |
12 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 | driver.get(baseUrl)
16 | elementById = driver.find_element_by_id("name")
17 |
18 | if elementById is not None:
19 | print("We found an element by Id")
20 |
21 | elementByName = driver.find_element_by_name("show-hide")
22 |
23 | if elementByName is not None:
24 | print("We found an element by Name")
25 |
26 | ff = FindByIdName()
27 | ff.test()
28 |
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/interactingWithPage.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import os
6 | from selenium import webdriver
7 |
8 | chrome_driver_path = os.path.dirname(__file__) + "\chromedriver.exe"
9 |
10 | driver=webdriver.Chrome(chrome_driver_path)
11 |
12 | driver.get('http://codepad.org')
13 |
14 | text_area = driver.find_element_by_id('textarea')
15 | text_area.send_keys("This text is send using Python code.")
16 |
17 | text = driver.find_element_by_xpath("//*[@id='editor-form']/table/tbody/tr[1]/td/span").text
18 | print(text)
19 |
20 | print (driver.current_url)
21 |
22 | driver.close()
23 | #driver.forward()
24 | #driver.back()
25 | #driver.minimize_window()
26 | #driver.maximize_window()
27 | #driver.refresh()
28 | #driver.set_page_load_timeout(20)#seconds
29 | #driver.delete_all_cookies()
30 |
--------------------------------------------------------------------------------
/Python_basics/wait_types/implicit_wait_demo.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 24, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import os
8 |
9 | class ImplicitWaitDemo():
10 | def test(self):
11 | baseUrl = "https://letskodeit.teachable.com"
12 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 | driver.maximize_window()
16 | driver.get(baseUrl)
17 | driver.implicitly_wait(10)
18 |
19 | loginLink = driver.find_element(By.XPATH, "//div[@id='navbar']//a[@href='/sign_in']")
20 | loginLink.click()
21 |
22 | emailField = driver.find_element(By.ID, "user_email")
23 | emailField.send_keys("test")
24 |
25 | ff = ImplicitWaitDemo()
26 | ff.test()
27 |
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/SeleniumClickButton.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 21, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import os
7 | from selenium import webdriver
8 | import time
9 |
10 | chrome_driver_path = os.path.dirname(__file__) + "\chromedriver.exe"
11 |
12 | driver=webdriver.Chrome(chrome_driver_path)
13 | driver.get('http://codepad.org')
14 |
15 | # click radio button
16 | python_button = driver.find_elements_by_xpath("//input[@name='lang' and @value='Python']")[0]
17 | python_button.click()
18 |
19 | # type text
20 | text_area = driver.find_element_by_id('textarea')
21 | time.sleep(3)
22 |
23 | text_area.clear()
24 |
25 | text_area.send_keys("print('Hello World')")
26 |
27 | # click submit button
28 | submit_button = driver.find_element_by_css_selector(".g-recaptcha")
29 | submit_button.click()
30 |
31 | driver.close()
32 |
33 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/075 FindByXPathCSS.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 |
7 | class FindByXPathCSS():
8 |
9 | def test(self):
10 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
11 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
12 |
13 | driver=webdriver.Chrome(chrome_driver_path)
14 | driver.get(baseUrl)
15 | elementByXpath = driver.find_element_by_xpath("//input[@id='name']")
16 |
17 | if elementByXpath is not None:
18 | print("We found an element by XPATH")
19 |
20 | elementByCss = driver.find_element_by_css_selector("#displayed-text")
21 |
22 | if elementByCss is not None:
23 | print("We found an element by CSS")
24 |
25 | ff = FindByXPathCSS()
26 | ff.test()
27 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/UploadingFile.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 22, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | from selenium import webdriver
7 | from selenium.webdriver.common.by import By
8 | import time
9 | import os
10 |
11 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
12 |
13 | driver=webdriver.Chrome(chrome_driver_path)
14 | driver.maximize_window()
15 | driver.get("http://demo.guru99.com/test/upload/")
16 | driver.implicitly_wait(5)
17 | # enter the file path onto the file-selection input field
18 | uploadElement = driver.find_element(By.ID, "uploadfile_0")
19 | time.sleep(10)
20 | uploadElement.send_keys("D:\\webtable.JPG")
21 | time.sleep(2)
22 | driver.find_element(By.ID, "terms").click()
23 | # click the "UploadFile" button
24 | driver.find_element(By.NAME, "send").click()
25 |
26 | driver.quit()
27 |
--------------------------------------------------------------------------------
/Python_basics/ComparisonAndBooleanOperators/029 boolean-opertors.py:
--------------------------------------------------------------------------------
1 | """
2 | and
3 | **************************************
4 | True and True --> True
5 | True and False --> False
6 | False and False --> False
7 | **************************************
8 |
9 | or
10 | **************************************
11 | True or True --> True
12 | True or False --> True
13 | False or False --> False
14 | **************************************
15 |
16 | not
17 | **************************************
18 | Not True --> False
19 | Not False --> True
20 | """
21 |
22 | and_output1 = (10 == 10) and (10 > 9)
23 | and_output2 = (10 == 10) and (10 < 9)
24 | and_output3 = (10 > 10) and (10 < 9)
25 |
26 | or_output1 = (10 == 10) or (10 > 9)
27 | or_output2 = (10 == 10) or (10 < 9)
28 | or_output3 = (10 > 10) or (10 < 9)
29 |
30 | not_true = not (10 == 10)
31 | not_false = not (10 > 10)
32 |
33 | print(not_false)
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/126 window-size.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class WindowSize():
11 |
12 | def test(self):
13 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
14 |
15 | driver=webdriver.Chrome(chrome_driver_path)
16 | driver.maximize_window()
17 | driver.get("https://letskodeit.teachable.com/pages/practice")
18 | driver.implicitly_wait(3)
19 |
20 | height = driver.execute_script("return window.innerHeight;")
21 | width = driver.execute_script("return window.innerWidth;")
22 | print("Height: " + str(height))
23 | print("Width: " + str(width))
24 | driver.quit()
25 |
26 | ff = WindowSize()
27 | ff.test()
28 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_1/165 4-login-tests.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from pages.home.login_page import LoginPage
8 | import unittest
9 |
10 | class LoginTests(unittest.TestCase):
11 |
12 | def test_validLogin(self):
13 | baseURL = "https://letskodeit.teachable.com/"
14 | driver = webdriver.Firefox()
15 | driver.maximize_window()
16 | driver.implicitly_wait(3)
17 | driver.get(baseURL)
18 |
19 | lp = LoginPage(driver)
20 | lp.login("test@email.com", "abcabc")
21 |
22 | userIcon = driver.find_element(By.XPATH, ".//*[@id='navbar']//span[text()='User Settings']")
23 | if userIcon is not None:
24 | print("Login Successful")
25 | else:
26 | print("Login Failed")
27 |
--------------------------------------------------------------------------------
/Python_basics/utilities/driver_session.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | class DriverSession():
6 |
7 | driver = None
8 |
9 | @staticmethod
10 | def setDriver(driver):
11 | """
12 | Set the WebDriver object
13 |
14 | Required Parameters:
15 | driver: WebDriver object to set
16 |
17 | Optional Parameters:
18 | None
19 |
20 | Returns:
21 | None
22 | """
23 | DriverSession.driver = driver
24 |
25 | @staticmethod
26 | def getDriver():
27 | """
28 | Get the WebDriver object
29 |
30 | Required Parameters:
31 | None
32 |
33 | Optional Parameters:
34 | None
35 |
36 | Returns:
37 | 'WebDriver Object'
38 | """
39 | return DriverSession.driver
40 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/108 getAttribute.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class GetAttribute():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.implicitly_wait(10)
19 | driver.get(baseUrl)
20 |
21 | element = driver.find_element_by_id("name")
22 | result = element.get_attribute("type")
23 |
24 | print("Value of attribute is: " + result)
25 | time.sleep(1)
26 | driver.quit()
27 |
28 | ff = GetAttribute()
29 | ff.test()
30 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/Copypaste.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 24, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import sys
7 | import subprocess
8 | import pyperclip
9 | import clipboard
10 | import ctypes
11 |
12 | #pip install pyperclip
13 |
14 | '''
15 | pyperclip.copy('Hello world!')
16 | string = pyperclip.paste()
17 | print(string)
18 | '''
19 | # pip install clipboard
20 |
21 | '''
22 | clipboard.copy("abc") # now the clipboard content will be string "abc"
23 | text = clipboard.paste() # text will have the content of clipboard
24 | print(text)
25 | '''
26 | def winGetClipboard():
27 | ctypes.windll.user32.OpenClipboard(0)
28 | pcontents = ctypes.windll.user32.GetClipboardData(13) # CF_UNICODETEXT
29 | data = ctypes.c_wchar_p(pcontents).value
30 | ctypes.windll.user32.CloseClipboard()
31 | return data
32 |
33 | print (winGetClipboard())
34 |
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/test_class2.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import unittest
6 |
7 | class TestClass2(unittest.TestCase):
8 |
9 | @classmethod
10 | def setUpClass(cls):
11 | print("*#" * 30)
12 | print("Class 2 -> class level setUp")
13 | print("*#" * 30)
14 |
15 | def setUp(self):
16 | print("Class 2 -> setUp")
17 |
18 | def test_class2_methodA(self):
19 | print("Running class 2 -> method A")
20 |
21 | def test_class2_methodB(self):
22 | print("Running class 2 -> method B")
23 |
24 | def tearDown(self):
25 | print("Class 2 -> tearDown")
26 |
27 | @classmethod
28 | def tearDownClass(cls):
29 | print("*#" * 30)
30 | print("Class 2 -> class level tearDown")
31 | print("*#" * 30)
32 |
33 | if __name__ == '__main__':
34 | unittest.main(verbosity=2)
35 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/076 FindByLinkText.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 |
7 | class FindByLinkText():
8 |
9 | def test(self):
10 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
11 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
12 |
13 | driver=webdriver.Chrome(chrome_driver_path)
14 | driver.get(baseUrl)
15 |
16 | elementByLinkText = driver.find_element_by_link_text("Login")
17 |
18 | if elementByLinkText is not None:
19 | print("We found an element by Link Text")
20 |
21 | elementByPartialLinkText = driver.find_element_by_partial_link_text("Pract")
22 |
23 | if elementByPartialLinkText is not None:
24 | print("We found an element by Partial Link Text")
25 |
26 | ff = FindByLinkText()
27 | ff.test()
28 |
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/test_case_demo2.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import unittest
6 |
7 | class TestCaseDemo2(unittest.TestCase):
8 |
9 | @classmethod
10 | def setUpClass(cls):
11 | print("*#" * 30)
12 | print("I will run only once before all tests")
13 | print("*#" * 30)
14 |
15 | def setUp(self):
16 | print("I will run once before every testdemo")
17 |
18 | def test_methodA(self):
19 | print("Running method A")
20 |
21 | def test_methodB(self):
22 | print("Running method B")
23 |
24 | def tearDown(self):
25 | print("I will run after every testdemo")
26 |
27 | @classmethod
28 | def tearDownClass(cls):
29 | print("*#" * 30)
30 | print("I will run only once after all tests")
31 | print("*#" * 30)
32 |
33 | if __name__ == '__main__':
34 | unittest.main(verbosity=2)
35 |
--------------------------------------------------------------------------------
/Python_basics/MethodsWorkingWithReusableCode/041 built-in-functions.py:
--------------------------------------------------------------------------------
1 | """
2 | Some built-in functions
3 | max(): It takes any number of arguments and returns the largest one.
4 |
5 | min(): It takes any number of arguments and returns the smallest one.
6 |
7 | abs(): It returns the absolute value of the number, that number's distance from 0.
8 | It always returns a positive value and it only takes a single number.
9 |
10 | type(): It returns the type of the data it receives as an argument.
11 | """
12 |
13 | def largest_num(*args):
14 | print(max(args))
15 | return(max(args))
16 |
17 | largest_num(-20, -10, 0, 10, 100)
18 |
19 | def smallest_num(*args):
20 | print(min(args))
21 |
22 | smallest_num(-20, -10, 0, 10, 100)
23 |
24 | def abs_function(a):
25 | print(abs(a))
26 |
27 | abs_function(-20)
28 | abs_function(20)
29 |
30 | print("**********")
31 |
32 | print(type(99))
33 | print(type(99.9))
34 | print(type("99.9"))
35 | l = [1, 2, 3]
36 | print(type(l))
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/125 javascript-execution.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class JavaScriptExecution():
11 |
12 | def test(self):
13 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
14 |
15 | driver=webdriver.Chrome(chrome_driver_path)
16 | driver.maximize_window()
17 | # driver.get("https://letskodeit.teachable.com/pages/practice")
18 | driver.execute_script("window.location = 'https://letskodeit.teachable.com/pages/practice';")
19 | driver.implicitly_wait(3)
20 | time.sleep(6)
21 |
22 | # element = driver.find_element(By.ID, "name")
23 | element = driver.execute_script("return document.getElementById('name');")
24 | element.send_keys("Test")
25 |
26 | ff = JavaScriptExecution()
27 | ff.test()
28 |
--------------------------------------------------------------------------------
/Python_basics/utilities/using_wrappers_demo1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from utilities.handy_wrappers import HandyWrappers
8 | import time
9 | import os
10 |
11 | class UsingWrappers1():
12 |
13 | def test(self):
14 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | driver=webdriver.Chrome(chrome_driver_path)
18 | driver.maximize_window()
19 | driver.implicitly_wait(10)
20 | hw = HandyWrappers(driver)
21 | driver.get(baseUrl)
22 |
23 | textField1 = hw.getElement("name")
24 | textField1.send_keys("Test")
25 | time.sleep(2)
26 | textField2 = hw.getElement("//input[@id='name']", locatorType="xpath")
27 | textField2.clear()
28 |
29 | ff = UsingWrappers1()
30 | ff.test()
31 |
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/157 conftest.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 |
7 | @pytest.yield_fixture()
8 | def setUp():
9 | print("Running method level setUp")
10 | yield
11 | print("Running method level tearDown")
12 |
13 |
14 | @pytest.yield_fixture(scope="class")
15 | def oneTimeSetUp(browser):
16 | print("Running one time setUp")
17 | if browser == 'firefox':
18 | print("Running tests on FF")
19 | else:
20 | print("Running tests on chrome")
21 | yield
22 | print("Running one time tearDown")
23 |
24 | def pytest_addoption(parser):
25 | parser.addoption("--browser")
26 | parser.addoption("--osType", help="Type of operating system")
27 |
28 | @pytest.fixture(scope="session")
29 | def browser(request):
30 | return request.config.getoption("--browser")
31 |
32 | @pytest.fixture(scope="session")
33 | def osType(request):
34 | return request.config.getoption("--osType")
35 |
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/156 conftest.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 |
7 | @pytest.yield_fixture()
8 | def setUp():
9 | print("Running method level setUp")
10 | yield
11 | print("Running method level tearDown")
12 |
13 |
14 | @pytest.yield_fixture(scope="module")
15 | def oneTimeSetUp(browser, osType):
16 | print("Running one time setUp")
17 | if browser == 'firefox':
18 | print("Running tests on FF")
19 | else:
20 | print("Running tests on chrome")
21 | yield
22 | print("Running one time tearDown")
23 |
24 | def pytest_addoption(parser):
25 | parser.addoption("--browser")
26 | parser.addoption("--osType", help="Type of operating system")
27 |
28 | @pytest.fixture(scope="session")
29 | def browser(request):
30 | return request.config.getoption("--browser")
31 |
32 | @pytest.fixture(scope="session")
33 | def osType(request):
34 | return request.config.getoption("--osType")
35 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_2/171 3-login-tests.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from pages.home.login_page import LoginPage
7 | import unittest
8 | import pytest
9 |
10 | class LoginTests(unittest.TestCase):
11 | baseURL = "https://letskodeit.teachable.com/"
12 | driver = webdriver.Firefox()
13 | driver.maximize_window()
14 | driver.implicitly_wait(3)
15 | lp = LoginPage(driver)
16 |
17 | @pytest.mark.run(order=2)
18 | def test_validLogin(self):
19 | self.lp.clearLoginFields()
20 | self.lp.login("test@email.com", "abcabc")
21 | result = self.lp.verifyLoginSuccessful()
22 | assert result == True
23 | self.driver.quit()
24 |
25 | @pytest.mark.run(order=1)
26 | def test_invalidLogin(self):
27 | self.driver.get(self.baseURL)
28 | self.lp.login("test@email.com", "abcabcabc")
29 | result = self.lp.verifyLoginFailed()
30 | assert result == True
31 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/110 element-present-check.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from utilities.handy_wrappers import HandyWrappers
8 | import time
9 |
10 | class ElementPresentCheck():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.implicitly_wait(10)
19 | hw = HandyWrappers(driver)
20 | driver.get(baseUrl)
21 |
22 | elementResult1 = hw.isElementPresent("name", By.ID)
23 | print(str(elementResult1))
24 |
25 | elementResult2 = hw.elementPresenceCheck("//input[@id='name1']", By.XPATH)
26 | print(str(elementResult2))
27 |
28 | ff = ElementPresentCheck()
29 | ff.test()
30 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/077 FindByClassTag.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 |
7 | class FindByClassTag():
8 |
9 | def test(self):
10 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
11 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
12 |
13 | driver=webdriver.Chrome(chrome_driver_path)
14 | driver.get(baseUrl)
15 |
16 | elementByClassName = driver.find_element_by_class_name("displayed-class")
17 | elementByClassName.send_keys("Testing The Element")
18 |
19 | if elementByClassName is not None:
20 | print("We found an element by Class Name")
21 |
22 | elementByTagName = driver.find_element_by_tag_name("h1")
23 | text = elementByTagName.text
24 |
25 | if elementByTagName is not None:
26 | print("We found an element by Tag Name and the text on element is: " + text)
27 |
28 | ff = FindByClassTag()
29 | ff.test()
30 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/right_click.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from selenium import webdriver
3 | from selenium.webdriver.common.action_chains import ActionChains
4 | from selenium.webdriver.common.keys import Keys
5 |
6 |
7 | class RightClick(unittest.TestCase):
8 |
9 | def setUp(self):
10 | self.driver = webdriver.Firefox()
11 |
12 | def tearDown(self):
13 | self.driver.quit()
14 |
15 | def test_example_1(self):
16 | driver = self.driver
17 | driver.get('http://the-internet.herokuapp.com/context_menu')
18 | menu_area = driver.find_element_by_id('hot-spot')
19 | ActionChains(driver).context_click(
20 | menu_area).send_keys(
21 | Keys.ARROW_DOWN).send_keys(
22 | Keys.ARROW_DOWN).send_keys(
23 | Keys.ARROW_DOWN).send_keys(
24 | Keys.ENTER).perform()
25 | alert = driver.switch_to.alert
26 | assert alert.text == 'You selected a context menu'
27 |
28 | if __name__ == "__main__":
29 | unittest.main()
30 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_4/185 5-register-courses-tests.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from pages.courses.register_courses_page import RegisterCoursesPage
6 | from utilities.teststatus import TestStatus
7 | import unittest
8 | import pytest
9 |
10 | @pytest.mark.usefixtures("oneTimeSetUp", "setUp")
11 | class RegisterCoursesTests(unittest.TestCase):
12 |
13 | @pytest.fixture(autouse=True)
14 | def objectSetup(self, oneTimeSetUp):
15 | self.courses = RegisterCoursesPage(self.driver)
16 | self.ts = TestStatus(self.driver)
17 |
18 | @pytest.mark.run(order=1)
19 | def test_invalidEnrollment(self):
20 | self.courses.enterCourseName("JavaScript")
21 | self.courses.selectCourseToEnroll("JavaScript for beginners")
22 | self.courses.enrollCourse(num="10", exp="1220", cvv="10")
23 | result = self.courses.verifyEnrollFailed()
24 | self.ts.markFinal("test_invalidEnrollment", result,
25 | "Enrollment Failed Verification")
26 |
--------------------------------------------------------------------------------
/Python_basics/LaunchBrowsers/HeadlessBrowser.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 21, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import os
7 | from selenium import webdriver
8 | from selenium.webdriver.chrome.options import Options
9 |
10 | chrome_driver_path = os.path.dirname(__file__) + "\chromedriver.exe"
11 |
12 |
13 | chrome_options = Options()
14 | chrome_options.add_argument("--headless")
15 | chrome_options.add_argument("--window-size=1920x1080")
16 |
17 | # download the chrome driver from https://sites.google.com/a/chromium.org/chromedriver/downloads and put it in the
18 | # current directory
19 |
20 |
21 | # go to Google and click the I'm Feeling Lucky button
22 | driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chrome_driver_path)
23 | driver.get("https://www.google.com")
24 | lucky_button = driver.find_element_by_css_selector("[name=btnI]")
25 | lucky_button.click()
26 |
27 | # capture the screen
28 | driver.get_screenshot_as_file("capture.png")
29 |
30 | driver.close()
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/079 ListOfElements.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 |
8 | class ListOfElements():
9 |
10 | def test(self):
11 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
12 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 | driver.get(baseUrl)
16 |
17 | elementListByClassName = driver.find_elements_by_class_name("inputs")
18 | length1 = len(elementListByClassName)
19 |
20 | if elementListByClassName is not None:
21 | print("ClassName -> Size of the list is: " + str(length1))
22 |
23 | elementListByTagName = driver.find_elements(By.TAG_NAME, "td")
24 | length2 = len(elementListByTagName)
25 |
26 | if elementListByTagName is not None:
27 | print("TagName -> Size of the list is: " + str(length2))
28 |
29 | ff = ListOfElements()
30 | ff.test()
31 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/078 ByDemo.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 |
8 | class ByDemo():
9 |
10 | def test(self):
11 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
12 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 | driver.get(baseUrl)
16 |
17 | elementById = driver.find_element(By.ID, "name")
18 |
19 | if elementById is not None:
20 | print("We found an element by Id")
21 |
22 | elementByXpath = driver.find_element(By.XPATH, "//input[@id='displayed-text']")
23 |
24 | if elementByXpath is not None:
25 | print("We found an element by XPATH")
26 |
27 | elementByLinkText = driver.find_element(By.LINK_TEXT, "Login")
28 |
29 | if elementByLinkText is not None:
30 | print("We found an element by Link Text")
31 |
32 | ff = ByDemo()
33 | ff.test()
34 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/122 auto-complete.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class AutoComplete():
11 |
12 | def test(self):
13 | baseUrl = "http://www.southwest.com"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 | driver.implicitly_wait(3)
20 |
21 | # Send Partial Data
22 | cityField = driver.find_element_by_id("air-city-departure")
23 | cityField.send_keys("New York")
24 | time.sleep(3)
25 | # Find the item and click
26 | itemToSelect = driver.find_element_by_xpath("//ul[@id='air-city-departure-menu']//li[contains(text(),'NJ - EWR')]")
27 | itemToSelect.click()
28 |
29 | # time.sleep(3)
30 | # driver.quit()
31 |
32 | ff = AutoComplete()
33 | ff.test()
34 |
--------------------------------------------------------------------------------
/Python_basics/AdvancedLocators_CSS/074 FindByIdName.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 |
7 | class FindByIdName():
8 |
9 | def test(self):
10 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
11 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
12 |
13 | driver=webdriver.Chrome(chrome_driver_path)
14 | driver.get(baseUrl)
15 | elementById = driver.find_element_by_id("name")
16 |
17 | if elementById is not None:
18 | print("We found an element by Id")
19 |
20 | elementByName = driver.find_element_by_name("show-hide")
21 |
22 | if elementByName is not None:
23 | print("We found an element by Name")
24 |
25 | driver.get("https://www.yahoo.com/")
26 | # This one should fail because the Id is not static
27 | # Exception thrown: NoSuchElementException
28 | driver.find_element_by_id("yui_3_18_0_4_1463100170626_1148")
29 | driver.close()
30 |
31 | ff = FindByIdName()
32 | ff.test()
33 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_SwitchWindowAndIFrame/133 switch-to-alert.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class SwitchToFrame():
11 |
12 | def test1(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 |
20 | driver.find_element(By.ID, "name").send_keys("Anil")
21 | driver.find_element(By.ID, "alertbtn").click()
22 | time.sleep(2)
23 | alert1 = driver.switch_to.alert
24 | alert1.accept()
25 | time.sleep(2)
26 | driver.find_element(By.ID, "name").send_keys("Anil")
27 | driver.find_element(By.ID, "confirmbtn").click()
28 | time.sleep(2)
29 | alert2 = driver.switch_to.alert
30 | alert2.dismiss()
31 |
32 | ff = SwitchToFrame()
33 | ff.test1()
34 |
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/test_class1.py:
--------------------------------------------------------------------------------
1 | """
2 | Just follow this link to see how you can add PYTHONPATH to environment variable
3 |
4 | Windows:
5 | http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7
6 |
7 | Mac:
8 | http://stackoverflow.com/questions/3387695/add-to-python-path-mac-os-x
9 | """
10 | import unittest
11 |
12 | class TestClass1(unittest.TestCase):
13 |
14 | @classmethod
15 | def setUpClass(cls):
16 | print("*#" * 30)
17 | print("Class 1 -> class level setUp")
18 | print("*#" * 30)
19 |
20 | def setUp(self):
21 | print("Class 1 -> setUp")
22 |
23 | def test_class1_methodA(self):
24 | print("Running class 1 -> method A")
25 |
26 | def test_class1_methodB(self):
27 | print("Running class 1 -> method B")
28 |
29 | def tearDown(self):
30 | print("Class 1 -> tearDown")
31 |
32 | @classmethod
33 | def tearDownClass(cls):
34 | print("*#" * 30)
35 | print("Class 1 -> class level tearDown")
36 | print("*#" * 30)
37 |
38 | if __name__ == '__main__':
39 | unittest.main(verbosity=2)
--------------------------------------------------------------------------------
/Python_basics/MethodsWorkingWithReusableCode/042 methodexercise.py:
--------------------------------------------------------------------------------
1 | """
2 | Methods Exercise
3 | Create a method, which takes the state and gross income as the arguments and returns the net income after deducting tax based on the state.
4 |
5 | Assume Federal Tax: 10%
6 | Assume state tax on your wish.
7 |
8 | You don’t have to do for all the states, just take 3-4 to solve the purpose of the exercise.
9 | """
10 |
11 | def calculateNetIncome(gross, state):
12 | """
13 | Calculate the net income after federal and state tax
14 | :param gross: Gross Income
15 | :param state: State Name
16 | :return: Net Income
17 | """
18 | state_tax = {'CA': 10, 'NY': 9, 'TX': 0, 'NJ': 6}
19 |
20 | # Calculate net income after federal tax
21 | net = gross - (gross * .10)
22 |
23 | # Calculate net income after state tax
24 | if state in state_tax:
25 | net = net - (gross * state_tax[state] / 100)
26 | print("Your net income after all the heavy taxes is: " + str(net))
27 | return net
28 | else:
29 | print("State not in the list")
30 | return None
31 |
32 |
33 | calculateNetIncome(100000, 'CA')
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/158 conftest.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 |
7 | @pytest.yield_fixture()
8 | def setUp():
9 | print("Running method level setUp")
10 | yield
11 | print("Running method level tearDown")
12 |
13 |
14 | @pytest.yield_fixture(scope="class")
15 | def oneTimeSetUp(request, browser):
16 | print("Running one time setUp")
17 | if browser == 'firefox':
18 | value = 10
19 | print("Running tests on FF")
20 | else:
21 | value = 20
22 | print("Running tests on chrome")
23 |
24 | if request.cls is not None:
25 | request.cls.value = value
26 |
27 | yield value
28 | print("Running one time tearDown")
29 |
30 | def pytest_addoption(parser):
31 | parser.addoption("--browser")
32 | parser.addoption("--osType", help="Type of operating system")
33 |
34 | @pytest.fixture(scope="session")
35 | def browser(request):
36 | return request.config.getoption("--browser")
37 |
38 | @pytest.fixture(scope="session")
39 | def osType(request):
40 | return request.config.getoption("--osType")
41 |
--------------------------------------------------------------------------------
/Python_basics/Pytest_AdvancedTestingFramework/160 conftest.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import pytest
6 |
7 | @pytest.yield_fixture()
8 | def setUp():
9 | print("Running method level setUp")
10 | yield
11 | print("Running method level tearDown")
12 |
13 |
14 | @pytest.yield_fixture(scope="class")
15 | def oneTimeSetUp(request, browser):
16 | print("Running one time setUp")
17 | if browser == 'firefox':
18 | value = 10
19 | print("Running tests on FF")
20 | else:
21 | value = 20
22 | print("Running tests on chrome")
23 |
24 | if request.cls is not None:
25 | request.cls.value = value
26 |
27 | yield value
28 | print("Running one time tearDown")
29 |
30 | def pytest_addoption(parser):
31 | parser.addoption("--browser")
32 | parser.addoption("--osType", help="Type of operating system")
33 |
34 | @pytest.fixture(scope="session")
35 | def browser(request):
36 | return request.config.getoption("--browser")
37 |
38 | @pytest.fixture(scope="session")
39 | def osType(request):
40 | return request.config.getoption("--osType")
41 |
--------------------------------------------------------------------------------
/Python_basics/RunningCompleteTestSuite/191 2-login-tests.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from pages.home.login_page import LoginPage
6 | from utilities.teststatus import TestStatus
7 | import unittest
8 | import pytest
9 |
10 | @pytest.mark.usefixtures("oneTimeSetUp", "setUp")
11 | class LoginTests(unittest.TestCase):
12 |
13 | @pytest.fixture(autouse=True)
14 | def objectSetup(self, oneTimeSetUp):
15 | self.lp = LoginPage(self.driver)
16 | self.ts = TestStatus(self.driver)
17 |
18 | @pytest.mark.run(order=2)
19 | def test_validLogin(self):
20 | self.lp.login("test@email.com", "abcabc")
21 | result1 = self.lp.verifyLoginTitle()
22 | self.ts.mark(result1, "Title Verification")
23 | result2 = self.lp.verifyLoginSuccessful()
24 | self.ts.markFinal("test_validLogin", result2, "Login Verification")
25 |
26 | @pytest.mark.run(order=1)
27 | def test_invalidLogin(self):
28 | self.lp.logout()
29 | self.lp.login("test@email.com", "abcabcabc")
30 | result = self.lp.verifyLoginFailed()
31 | assert result == True
32 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_WorkingWithActionsClass/136 sliders.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from selenium.webdriver import ActionChains
8 | import time
9 | import os
10 |
11 | class Sliders():
12 |
13 | def test1(self):
14 | baseUrl = "https://jqueryui.com/slider/"
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | driver=webdriver.Chrome(chrome_driver_path)
18 | driver.maximize_window()
19 | driver.get(baseUrl)
20 | driver.implicitly_wait(3)
21 |
22 | driver.switch_to.frame(0)
23 |
24 | element = driver.find_element(By.XPATH, "//div[@id='slider']//span")
25 | time.sleep(2)
26 | try:
27 | actions = ActionChains(driver)
28 | actions.drag_and_drop_by_offset(element, 100, 0).perform()
29 | print("Sliding Element Successful")
30 | time.sleep(2)
31 | except:
32 | print("Sliding failed on element")
33 |
34 | ff = Sliders()
35 | ff.test1()
36 |
--------------------------------------------------------------------------------
/Python_basics/Logging_infrastructure/139 logger-demo-console.py:
--------------------------------------------------------------------------------
1 | """
2 | Logger Demo
3 | """
4 | import logging
5 |
6 | class LoggerDemoConsole():
7 |
8 | def testLog(self):
9 | # create logger
10 | logger = logging.getLogger(LoggerDemoConsole.__name__)
11 | logger.setLevel(logging.INFO)
12 |
13 | # create console handler and set level to info
14 | consoleHandler = logging.StreamHandler()
15 | consoleHandler.setLevel(logging.INFO)
16 |
17 | # create formatter
18 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s',
19 | datefmt='%m/%d/%Y %I:%M:%S %p')
20 |
21 | # add formatter to console handler
22 | consoleHandler.setFormatter(formatter)
23 |
24 | # add console handler to logger
25 | logger.addHandler(consoleHandler)
26 |
27 | # logging messages
28 | logger.debug('debug message')
29 | logger.info('info message')
30 | logger.warn('warn message')
31 | logger.error('error message')
32 | logger.critical('critical message')
33 |
34 | demo = LoggerDemoConsole()
35 | demo.testLog()
--------------------------------------------------------------------------------
/index.rst:
--------------------------------------------------------------------------------
1 | ********************
2 | Selenium with Python
3 | ********************
4 |
5 | :Author: `Baiju Muthukadan `_
6 | :License: This document is licensed under a
7 | `Creative Commons Attribution-ShareAlike 4.0 International License `_.
8 |
9 | .. note::
10 |
11 | This is not an official documentation. If you would like to
12 | contribute to this documentation, you can `fork this project in
13 | Github and send pull requests
14 | `_. You can also send
15 | your feedback to my email: baiju.m.mail AT gmail DOT com. So far
16 | 40+ community members have contributed to this project
17 | (See the closed pull requests). I encourage contributors to add
18 | more sections and make it a good documentation!
19 |
20 |
21 | .. toctree::
22 | :numbered:
23 |
24 | installation
25 | getting-started
26 | navigating
27 | locating-elements
28 | waits
29 | page-objects
30 | api
31 | faq
32 |
33 |
34 | Indices and tables
35 | ==================
36 |
37 | * :ref:`genindex`
38 | * :ref:`modindex`
39 | * :ref:`search`
40 |
--------------------------------------------------------------------------------
/Python_basics/Logging_infrastructure/141 logging-demo2.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import logging
6 | import loggingpackage.custom_logger as cl
7 |
8 | class LoggingDemo2():
9 |
10 | log = cl.customLogger(logging.DEBUG)
11 |
12 | def method1(self):
13 | self.log.debug('debug message')
14 | self.log.info('info message')
15 | self.log.warn('warn message')
16 | self.log.error('error message')
17 | self.log.critical('critical message')
18 |
19 | def method2(self):
20 | m2Log = cl.customLogger(logging.INFO)
21 | m2Log.debug('debug message')
22 | m2Log.info('info message')
23 | m2Log.warn('warn message')
24 | m2Log.error('error message')
25 | m2Log.critical('critical message')
26 |
27 | def method3(self):
28 | m3Log = cl.customLogger(logging.INFO)
29 | m3Log.debug('debug message')
30 | m3Log.info('info message')
31 | m3Log.warn('warn message')
32 | m3Log.error('error message')
33 | m3Log.critical('critical message')
34 |
35 | demo = LoggingDemo2()
36 | demo.method1()
37 | demo.method2()
38 | demo.method3()
39 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/099 WorkingWithElementsList.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class WorkingWithElementsList():
11 |
12 | def testListOfElements(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 | driver.implicitly_wait(10)
20 |
21 | radioButtonsList = driver.find_elements(
22 | By.XPATH, "//input[contains(@type,'radio') and contains(@name,'cars')]")
23 | size = len(radioButtonsList)
24 | print("Size of the list: " + str(size))
25 |
26 | for radioButton in radioButtonsList:
27 | isSelected = radioButton.is_selected()
28 |
29 | if not isSelected:
30 | radioButton.click()
31 | time.sleep(2)
32 |
33 | ff = WorkingWithElementsList()
34 | ff.testListOfElements()
35 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_1/163 3-login-tests.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 |
8 | class LoginTests():
9 |
10 | def test_validLogin(self):
11 | baseURL = "https://letskodeit.teachable.com/"
12 | driver = webdriver.Firefox()
13 | driver.maximize_window()
14 | driver.implicitly_wait(3)
15 | driver.get(baseURL)
16 |
17 | loginLink = driver.find_element(By.LINK_TEXT, "Login")
18 | loginLink.click()
19 |
20 | emailField = driver.find_element(By.ID, "user_email")
21 | emailField.send_keys("test@email.com")
22 |
23 | passwordField = driver.find_element(By.ID, "user_password")
24 | passwordField.send_keys("abcabc")
25 |
26 | loginButton = driver.find_element(By.NAME, "commit")
27 | loginButton.click()
28 |
29 | userIcon = driver.find_element(By.XPATH, ".//*[@id='navbar']//span[text()='User Settings']")
30 | if userIcon is not None:
31 | print("Login Successful")
32 | else:
33 | print("Login Failed")
34 |
35 | ff = LoginTests()
36 | ff.test_validLogin()
37 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/097 ElementState.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import os
7 |
8 | class ElementState():
9 |
10 | def isEnabled(self):
11 | baseUrl = "http://www.google.com"
12 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 | driver.maximize_window()
16 | driver.get(baseUrl)
17 | driver.implicitly_wait(3)
18 |
19 | e1 = driver.find_element_by_id("gs_htif0")
20 | e1State = e1.is_enabled() # True for enabled and False for disabled
21 | print("E1 is Enabled? -> " + str(e1State))
22 |
23 | e2 = driver.find_element_by_id("gs_taif0")
24 | e2State = e2.is_enabled() # True for enabled and False for disabled
25 | print("E2 is Enabled? -> " + str(e2State))
26 |
27 | e3 = driver.find_element_by_id("lst-ib")
28 | e3State = e3.is_enabled() # True for enabled and False for disabled
29 | print("E3 is Enabled? -> " + str(e3State))
30 |
31 | e3.send_keys("letskodeit")
32 |
33 | e = ElementState()
34 | e.isEnabled()
35 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/101 DropdownSelect.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import time
7 | from selenium.webdriver.support.select import Select
8 | import os
9 |
10 | class DropdownSelect():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 | driver.implicitly_wait(10)
20 |
21 | element = driver.find_element_by_id("carselect")
22 | sel = Select(element)
23 |
24 | sel.select_by_value("benz")
25 | print("Select Benz by value")
26 | time.sleep(2)
27 |
28 | sel.select_by_index("2")
29 | print("Select Honda by index")
30 | time.sleep(2)
31 |
32 | sel.select_by_visible_text("BMW")
33 | print("Select BMW by visible text")
34 | time.sleep(2)
35 |
36 | sel.select_by_index(2)
37 | print("Select Honda by index")
38 |
39 | ff = DropdownSelect()
40 | ff.test()
41 |
--------------------------------------------------------------------------------
/Python_basics/Data_Driven_Testing/187 2-register-courses-multiple-data-set.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from pages.courses.register_courses_page import RegisterCoursesPage
6 | from utilities.teststatus import TestStatus
7 | import unittest, pytest
8 | from ddt import ddt, data, unpack
9 |
10 | @pytest.mark.usefixtures("oneTimeSetUp", "setUp")
11 | @ddt
12 | class RegisterMultipleCoursesTests(unittest.TestCase):
13 |
14 | @pytest.fixture(autouse=True)
15 | def objectSetup(self, oneTimeSetUp):
16 | self.courses = RegisterCoursesPage(self.driver)
17 | self.ts = TestStatus(self.driver)
18 |
19 | @pytest.mark.run(order=1)
20 | @data(("JavaScript for beginners", "10", "1220", "10"), ("Learn Python 3 from scratch", "20", "1220", "20"))
21 | @unpack
22 | def test_invalidEnrollment(self, courseName, ccNum, ccExp, ccCVV):
23 | self.courses.enterCourseName(courseName)
24 | self.courses.selectCourseToEnroll(courseName)
25 | self.courses.enrollCourse(num=ccNum, exp=ccExp, cvv=ccCVV)
26 | result = self.courses.verifyEnrollFailed()
27 | self.ts.markFinal("test_invalidEnrollment", result,
28 | "Enrollment Failed Verification")
29 | self.driver.find_element_by_link_text("All Courses").click()
30 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/123 screenshots.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class Screenshots():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 | driver.implicitly_wait(3)
20 |
21 | driver.find_element(By.LINK_TEXT, "Login").click()
22 | driver.find_element(By.ID, "user_email").send_keys("abc@email.com")
23 | driver.find_element(By.ID, "user_password").send_keys("abc")
24 | driver.find_element(By.NAME, "commit").click()
25 | destinationFileName = "/Users/atomar/Desktop/test.png" # Mac
26 | # destinationFileName = "C:\\atomar\\Desktop" -> Windows
27 |
28 | try:
29 | driver.save_screenshot(destinationFileName)
30 | print("Screenshot saved to directory --> :: " + destinationFileName)
31 | except NotADirectoryError:
32 | print("Not a directory issue")
33 |
34 | ff = Screenshots()
35 | ff.test()
36 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_WorkingWithActionsClass/135 drag-and-drop.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from selenium.webdriver import ActionChains
8 | import time
9 | import os
10 |
11 | class DragAndDrop():
12 |
13 | def test1(self):
14 | baseUrl = "https://jqueryui.com/droppable/"
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | driver=webdriver.Chrome(chrome_driver_path)
18 | driver.maximize_window()
19 | driver.get(baseUrl)
20 | driver.implicitly_wait(3)
21 |
22 | driver.switch_to.frame(0)
23 |
24 | fromElement = driver.find_element(By.ID, "draggable")
25 | toElement = driver.find_element(By.ID, "droppable")
26 | time.sleep(2)
27 | try:
28 | actions = ActionChains(driver)
29 | actions.drag_and_drop(fromElement, toElement).perform()
30 | # actions.click_and_hold(fromElement).move_to_element(toElement).release().perform()
31 | print("Drag And Drop Element Successful")
32 | time.sleep(2)
33 | except:
34 | print("Drag And Drop failed on element")
35 |
36 | ff = DragAndDrop()
37 | ff.test1()
38 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_SwitchWindowAndIFrame/SwitchToNewTab.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 23, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import time
7 | import os
8 |
9 | # --- best example program for driver.close() and driver.quit()
10 |
11 | class SwitchToNewTab():
12 |
13 | def test1(self):
14 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | driver=webdriver.Chrome(chrome_driver_path)
18 | driver.maximize_window()
19 | driver.get(baseUrl)
20 |
21 | time.sleep(2)
22 | driver.execute_script("window.open('https://google.co.in','new window')")
23 | print("opened a new tab1")
24 | driver.switch_to.window(driver.window_handles[1])
25 | time.sleep(2)
26 | driver.execute_script("window.open('');")
27 | time.sleep(3)
28 | print("opened a new tab2")
29 | # Switch to the new window
30 | driver.switch_to.window(driver.window_handles[2])
31 | driver.get("http://stackoverflow.com")
32 | time.sleep(3)
33 | print("opened a new tab3")
34 | # close the active tab
35 | driver.close()
36 |
37 | ff = SwitchToNewTab()
38 | ff.test1()
39 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_1/166 5-login-page.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium.webdriver.common.by import By
6 |
7 | class LoginPage():
8 |
9 | def __init__(self, driver):
10 | self.driver = driver
11 |
12 | # Locators
13 | _login_link = "Login"
14 | _email_field = "user_email"
15 | _password_field = "user_password"
16 | _login_button = "commit"
17 |
18 | def getLoginLink(self):
19 | return self.driver.find_element(By.LINK_TEXT, self._login_link)
20 |
21 | def getEmailField(self):
22 | return self.driver.find_element(By.ID, self._email_field)
23 |
24 | def getPasswordField(self):
25 | return self.driver.find_element(By.ID, self._password_field)
26 |
27 | def getLoginButton(self):
28 | return self.driver.find_element(By.NAME, self._login_button)
29 |
30 | def clickLoginLink(self):
31 | self.getLoginLink().click()
32 |
33 | def enterEmail(self, email):
34 | self.getEmailField().send_keys(email)
35 |
36 | def enterPassword(self, password):
37 | self.getPasswordField().send_keys(password)
38 |
39 | def clickLoginButton(self):
40 | self.getLoginButton().click()
41 |
42 | def login(self, email, password):
43 | self.clickLoginLink()
44 | self.enterEmail(email)
45 | self.enterPassword(password)
46 | self.clickLoginButton()
47 |
--------------------------------------------------------------------------------
/Python_basics/wait_types/explicit_wait_demo2.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 24, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from wait_types.explicit_wait_type import ExplicitWaitType
8 | import time
9 | import os
10 | from selenium.webdriver.common.keys import Keys
11 |
12 | class ExplicitWaitDemo2():
13 |
14 | def test(self):
15 | baseUrl = "http://www.expedia.com"
16 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
17 |
18 | driver=webdriver.Chrome(chrome_driver_path)
19 | driver.implicitly_wait(.5)
20 | driver.maximize_window()
21 | wait = ExplicitWaitType(driver)
22 | driver.get(baseUrl)
23 | driver.find_element(By.ID, "tab-flight-tab").click()
24 | driver.find_element(By.ID, "flight-origin").send_keys("SFO")
25 | driver.find_element(By.ID, "flight-destination").send_keys("NYC")
26 | driver.find_element(By.ID, "flight-departing").send_keys("12/24/2016")
27 | returnDate = driver.find_element(By.ID, "flight-returning")
28 | returnDate.clear()
29 | returnDate.send_keys("12/26/2016")
30 | returnDate.send_keys(Keys.RETURN)
31 |
32 | element = wait.waitForElement("stopFilter_stops-0")
33 | element.click()
34 |
35 | time.sleep(2)
36 | driver.quit()
37 |
38 | ff = ExplicitWaitDemo2()
39 | ff.test()
40 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_SwitchWindowAndIFrame/132 switch-to-frame.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class SwitchToFrame():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 | driver.execute_script("window.scrollBy(0, 1000);")
20 |
21 | # Switch to frame using Id
22 | driver.switch_to.frame("courses-iframe")
23 |
24 | # Switch to frame using name
25 | # driver.switch_to.frame("iframe-name")
26 |
27 | # Switch to frame using numbers
28 | # driver.switch_to.frame(0)
29 |
30 | time.sleep(2)
31 | # Search course
32 | searchBox = driver.find_element(By.ID, "search-courses")
33 | searchBox.send_keys("python")
34 | time.sleep(2)
35 |
36 | # Switch back to the parent frame
37 | driver.switch_to.default_content()
38 | driver.execute_script("window.scrollBy(0, -1000);")
39 | time.sleep(2)
40 | driver.find_element(By.ID, "name").send_keys("Test Successful")
41 |
42 | ff = SwitchToFrame()
43 | ff.test()
44 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/127 scrolling-element.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class ScrollingElement():
11 |
12 | def test(self):
13 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
14 |
15 | driver=webdriver.Chrome(chrome_driver_path)
16 | driver.maximize_window()
17 | driver.get("https://letskodeit.teachable.com/pages/practice")
18 | driver.implicitly_wait(3)
19 |
20 | # Scroll Down
21 | driver.execute_script("window.scrollBy(0, 1000);")
22 | time.sleep(3)
23 |
24 | # Scroll Up
25 | driver.execute_script("window.scrollBy(0, -1000);")
26 | time.sleep(3)
27 |
28 | # Scroll Element Into View
29 | element = driver.find_element(By.ID, "mousehover")
30 | driver.execute_script("arguments[0].scrollIntoView(true);", element)
31 | time.sleep(2)
32 | driver.execute_script("window.scrollBy(0, -150);")
33 |
34 | # Native Way To Scroll Element Into View
35 | time.sleep(2)
36 | driver.execute_script("window.scrollBy(0, -1000);")
37 | location = element.location_once_scrolled_into_view
38 | print("Location: " + str(location))
39 | driver.execute_script("window.scrollBy(0, -150);")
40 |
41 | ff = ScrollingElement()
42 | ff.test()
43 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_WorkingWithActionsClass/134 mouse-hovering.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from selenium.webdriver import ActionChains
8 | import time
9 | import os
10 |
11 | class MouseHovering():
12 |
13 | def test1(self):
14 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | driver=webdriver.Chrome(chrome_driver_path)
18 | driver.maximize_window()
19 | driver.get(baseUrl)
20 | driver.implicitly_wait(3)
21 |
22 | driver.execute_script("window.scrollBy(0, 600);")
23 | time.sleep(2)
24 | element = driver.find_element(By.ID, "mousehover")
25 | itemToClickLocator = ".//div[@class='mouse-hover-content']//a[text()='Top']"
26 | try:
27 | actions = ActionChains(driver)
28 | actions.move_to_element(element).perform()
29 | # ActionChains(driver).move_to_element(element).perform()
30 | print("Mouse Hovered on element")
31 | time.sleep(2)
32 | topLink = driver.find_element(By.XPATH, itemToClickLocator)
33 | actions.move_to_element(topLink).click().perform()
34 | print("Item Clicked")
35 | except:
36 | print("Mouse Hover failed on element")
37 |
38 | ff = MouseHovering()
39 | ff.test1()
40 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/098 RadioButtonsAndCheckboxes.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import time
7 | import os
8 |
9 | class RadioButtonsAndCheckboxes():
10 |
11 | def test(self):
12 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
13 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
14 |
15 | driver=webdriver.Chrome(chrome_driver_path)
16 | driver.maximize_window()
17 | driver.get(baseUrl)
18 | driver.implicitly_wait(10)
19 |
20 | bmwRadioBtn = driver.find_element_by_id("bmwradio")
21 | bmwRadioBtn.click()
22 |
23 | time.sleep(2)
24 | benzRadioBtn = driver.find_element_by_id("benzradio")
25 | benzRadioBtn.click()
26 |
27 | time.sleep(2)
28 | bmwCheckbox = driver.find_element_by_id("bmwcheck")
29 | bmwCheckbox.click()
30 |
31 | time.sleep(2)
32 | benzCheckbox = driver.find_element_by_id("benzcheck")
33 | benzCheckbox.click()
34 |
35 | print("BMW Radio button is selected? " + str(bmwRadioBtn.is_selected())) # True if selected, False is not selected
36 | print("Benz Radio button is selected? " + str(benzRadioBtn.is_selected()))
37 | print("BMW Checkbox is selected? " + str(bmwCheckbox.is_selected()))
38 | print("Benz Checkbox is selected? " + str(benzCheckbox.is_selected()))
39 |
40 | ff = RadioButtonsAndCheckboxes()
41 | ff.test()
42 |
--------------------------------------------------------------------------------
/Python_basics/RunningCompleteTestSuite/190 1-register-courses-csv-data.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from pages.courses.register_courses_page import RegisterCoursesPage
6 | from pages.home.navigation_page import NavigationPage
7 | from utilities.teststatus import TestStatus
8 | import unittest, pytest
9 | from ddt import ddt, data, unpack
10 | from utilities.read_data import getCSVData
11 | import time
12 |
13 | @pytest.mark.usefixtures("oneTimeSetUp", "setUp")
14 | @ddt
15 | class RegisterCoursesCSVDataTests(unittest.TestCase):
16 |
17 | @pytest.fixture(autouse=True)
18 | def objectSetup(self, oneTimeSetUp):
19 | self.courses = RegisterCoursesPage(self.driver)
20 | self.ts = TestStatus(self.driver)
21 | self.nav = NavigationPage(self.driver)
22 |
23 | def setUp(self):
24 | self.nav.navigateToAllCourses()
25 |
26 | @pytest.mark.run(order=1)
27 | @data(*getCSVData("/Users/atomar/Documents/workspace_python/letskodeit/testdata.csv"))
28 | @unpack
29 | def test_invalidEnrollment(self, courseName, ccNum, ccExp, ccCVV):
30 | self.courses.enterCourseName(courseName)
31 | time.sleep(1)
32 | self.courses.selectCourseToEnroll(courseName)
33 | time.sleep(1)
34 | self.courses.enrollCourse(num=ccNum, exp=ccExp, cvv=ccCVV)
35 | time.sleep(1)
36 | result = self.courses.verifyEnrollFailed()
37 | self.ts.markFinal("test_invalidEnrollment", result,
38 | "Enrollment Failed Verification")
39 |
--------------------------------------------------------------------------------
/Python_basics/wait_types/explicit_wait_type.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 24, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from traceback import print_stack
6 | from utilities.handy_wrappers import HandyWrappers
7 | from selenium.webdriver.support.ui import WebDriverWait
8 | from selenium.webdriver.support import expected_conditions as EC
9 | from selenium.common.exceptions import *
10 |
11 | class ExplicitWaitType():
12 |
13 | def __init__(self, driver):
14 | self.driver = driver
15 | self.hw = HandyWrappers(driver)
16 |
17 | def waitForElement(self, locator, locatorType="xpath",
18 | timeout=10, pollFrequency=0.5):
19 | element = None
20 | try:
21 | byType = self.hw.getByType(locatorType)
22 | print("Waiting for maximum :: " + str(timeout) +
23 | " :: seconds for element to be clickable")
24 | wait = WebDriverWait(self.driver, 10, poll_frequency=1,
25 | ignored_exceptions=[NoSuchElementException,
26 | ElementNotVisibleException,
27 | ElementNotSelectableException])
28 | element = wait.until(EC.element_to_be_clickable((byType,
29 | "//select[@name='sort']")))
30 | print("Element appeared on the web page")
31 | except:
32 | print("Element not appeared on the web page")
33 | print_stack()
34 | return element
35 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/124 screenshots-generic.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class Screenshots():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 | driver.implicitly_wait(3)
20 |
21 | driver.find_element(By.LINK_TEXT, "Login").click()
22 | driver.find_element(By.ID, "user_email").send_keys("abc@email.com")
23 | driver.find_element(By.ID, "user_password").send_keys("abc")
24 | driver.find_element(By.NAME, "commit").click()
25 | self.takeScreenshot(driver)
26 |
27 | def takeScreenshot(self, driver):
28 | """
29 | Takes screenshot of the current open web page
30 | :param driver
31 | :return:
32 | """
33 | fileName = str(round(time.time() * 1000)) + ".png"
34 | screenshotDirectory = "/Users/atomar/desktop/"
35 | destinationFile = screenshotDirectory + fileName
36 |
37 | try:
38 | driver.save_screenshot(destinationFile)
39 | print("Screenshot saved to directory --> :: " + destinationFile)
40 | except NotADirectoryError:
41 | print("Not a directory issue")
42 |
43 | ff = Screenshots()
44 | ff.test()
45 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/download.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | import shutil
4 | import tempfile
5 | import unittest
6 | from selenium import webdriver
7 |
8 |
9 | class Download(unittest.TestCase):
10 |
11 | def setUp(self):
12 | self.download_dir = tempfile.mkdtemp()
13 |
14 | profile = webdriver.FirefoxProfile()
15 | profile.set_preference("browser.download.dir", self.download_dir)
16 | profile.set_preference("browser.download.folderList", 2)
17 | profile.set_preference(
18 | "browser.helperApps.neverAsk.saveToDisk",
19 | "images/jpeg, application/pdf, application/octet-stream")
20 | profile.set_preference("pdfjs.disabled", True)
21 | self.driver = webdriver.Firefox(firefox_profile=profile)
22 |
23 | def tearDown(self):
24 | self.driver.quit()
25 | shutil.rmtree(self.download_dir)
26 |
27 | def test_example_1(self):
28 | driver = self.driver
29 | driver.get('http://the-internet.herokuapp.com/download')
30 | download_link = driver.find_element_by_css_selector('.example a')
31 | download_link.click()
32 |
33 | time.sleep(1.0) # necessary for slow download speeds
34 |
35 | files = os.listdir(self.download_dir)
36 | files = [os.path.join(self.download_dir, f)
37 | for f in files] # add directory to each filename
38 | assert len(files) > 0, "no files were downloaded"
39 | assert os.path.getsize(files[0]) > 0, "downloaded file was empty"
40 |
41 | if __name__ == "__main__":
42 | unittest.main()
43 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/DynamicWebTable1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 22, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import unittest
7 | import os
8 | from selenium import webdriver
9 | import time
10 |
11 | class DynamicWebTable1(unittest.TestCase):
12 |
13 | @classmethod
14 | def setUpClass(cls):
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | cls.driver=webdriver.Chrome(chrome_driver_path)
18 |
19 | cls.driver.implicitly_wait(30)
20 | cls.driver.maximize_window()
21 | # navigate to the application home page
22 | cls.driver.get("http://qavalidation.com/demo/")
23 |
24 | def test_get_table_data(self):
25 | time.sleep(5)
26 | columns = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr[1]/td"))
27 | rows = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr"))
28 | print("rows - ",rows) # rows - 3
29 | print("columns - ",columns) #columns - 4
30 |
31 | for row in range(1,rows):
32 | for col in range(2,columns):
33 | values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+str(row)+"]/td["+str(col)+"]").text
34 | print(" Dynamic web table index {0} ,{1} value is {2} ".format(row, col, values))
35 |
36 | @classmethod
37 | def tearDownClass(cls):
38 | # close the browser window
39 | cls.driver.quit()
40 |
41 | if __name__ == '__main__':
42 | unittest.main(verbosity=2)
43 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/add_cookies.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from selenium import webdriver
3 |
4 |
5 | class ABTestOptOut(unittest.TestCase):
6 |
7 | def setUp(self):
8 | self.driver = webdriver.Firefox()
9 |
10 | def tearDown(self):
11 | self.driver.quit()
12 |
13 | def test_forge_cookie_on_target_page(self):
14 | driver = self.driver
15 | driver.get('http://the-internet.herokuapp.com/abtest')
16 | heading_text = driver.find_element_by_tag_name('h3').text
17 | assert heading_text in ['A/B Test Variation 1', 'A/B Test Control']
18 | driver.add_cookie({'name' : 'optimizelyOptOut', 'value' : 'true'})
19 | driver.refresh()
20 | heading_text = driver.find_element_by_tag_name('h3').text
21 | assert heading_text == 'No A/B Test'
22 |
23 | def test_forge_cookie_on_homepage_then_navigate_to_target_page(self):
24 | driver = self.driver
25 | driver.get('http://the-internet.herokuapp.com')
26 | driver.add_cookie({'name' : 'optimizelyOptOut', 'value' : 'true'})
27 | driver.get('http://the-internet.herokuapp.com/abtest')
28 | heading_text = driver.find_element_by_tag_name('h3').text
29 | assert heading_text == 'No A/B Test'
30 |
31 | def test_url_parameter(self):
32 | driver = self.driver
33 | driver.get('http://the-internet.herokuapp.com/abtest?optimizely_opt_out=true')
34 | driver.switch_to.alert.dismiss()
35 | heading_text = driver.find_element_by_tag_name('h3').text
36 | assert heading_text == 'No A/B Test'
37 |
38 | if __name__ == "__main__":
39 | unittest.main()
40 |
--------------------------------------------------------------------------------
/Python_basics/unittestpackage/test.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import random, string
6 |
7 | class Test():
8 | def getAlphaNumeric(self, length, type='letters'):
9 | """
10 | Get random string of characters
11 |
12 | Required Parameters:
13 | length: Length of string, number of characters string should have
14 |
15 | Optional Parameters:
16 | type: Type of characters string should have. Default is letters
17 | Provide lower/upper/digits for different types
18 |
19 | Returns:
20 | None
21 | """
22 | alpha_num = ''
23 | if type == 'lower':
24 | case = string.ascii_lowercase
25 | elif type == 'upper':
26 | case = string.ascii_uppercase
27 | elif type == 'digits':
28 | case = string.digits
29 | elif type == 'mix':
30 | case = string.ascii_letters + string.digits
31 | else:
32 | case = string.ascii_letters
33 | return alpha_num.join(random.choice(case) for i in range(length))
34 |
35 |
36 | def getValidPort(self, count=4):
37 | """
38 | Get a valid port number
39 |
40 | Required Parameters:
41 | None
42 |
43 | Optional Parameters:
44 | count: Number of digits in a port. Default is 4.
45 |
46 | Returns:
47 | None
48 | """
49 | port = self.getAlphaNumeric(count, 'digits')
50 | if int(port) > 65535:
51 | print("65535")
52 | return self.getAlphaNumeric(count, 'digits')
53 |
54 | t = Test()
55 | t.getValidPort(count=6)
56 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/Pyautogui.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 24, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | # pip install PyAutoGUI
7 | import pyautogui
8 | from selenium import webdriver
9 | import time
10 | import os
11 |
12 | '''chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 | driver.maximize_window()
16 | driver.get("http://demo.guru99.com/test/upload/")
17 | driver.implicitly_wait(5)
18 | time.sleep(5)
19 | pyautogui.hotkey('ctrl', 'a')'''
20 |
21 | screenWidth, screenHeight = pyautogui.size()
22 | currentMouseX, currentMouseY = pyautogui.position()
23 | print("screenWidth - {0},screenHeight - {1}".format(screenWidth, screenHeight))
24 | print("currentMouseX - {0},currentMouseY - {1}".format(currentMouseX, currentMouseY))
25 |
26 | pyautogui.keyDown('win')
27 | pyautogui.keyDown('m')
28 |
29 | pyautogui.keyUp('m')
30 | pyautogui.keyUp('win')
31 |
32 | '''pyautogui.moveTo(100, 150)
33 | pyautogui.click()
34 | pyautogui.moveRel(None, 10) # move mouse 10 pixels down
35 | pyautogui.doubleClick()
36 | pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # use tweening/easing function to move mouse over 2 seconds.
37 | pyautogui.typewrite('Hello world!', interval=0.25) # type with quarter-second pause in between each key
38 | pyautogui.press('esc')
39 | pyautogui.keyDown('shift')
40 | pyautogui.press(['left', 'left', 'left', 'left', 'left', 'left'])
41 | pyautogui.keyUp('shift')
42 | '''
43 |
44 | # Mouse operation https://pyautogui.readthedocs.io/en/latest/mouse.html
45 | # keyboard operation https://pyautogui.readthedocs.io/en/latest/keyboard.html
46 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/111 dynamic-xpath-format.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from utilities.handy_wrappers import HandyWrappers
8 | import time
9 | import os
10 |
11 | class DynamicXPathFormat():
12 |
13 | def test(self):
14 | baseUrl = "https://letskodeit.teachable.com"
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | driver=webdriver.Chrome(chrome_driver_path)
18 | driver.maximize_window()
19 | driver.implicitly_wait(10)
20 | driver.get(baseUrl)
21 |
22 | # Login -> Lecture "How to click and type on a web element"
23 | driver.find_element(By.LINK_TEXT, "Login").click()
24 | email = driver.find_element(By.ID, "user_email")
25 | email.send_keys("test@email.com")
26 | password = driver.find_element(By.ID, "user_password")
27 | password.send_keys("abcabc")
28 | driver.find_element(By.NAME, "commit").click()
29 |
30 | # Search for courses -> You don't need to search the course
31 | # You can select it without searching also
32 | searchBox = driver.find_element(By.ID, "search-courses")
33 | searchBox.send_keys("JavaScript")
34 |
35 | # Select Course
36 | _course = "//div[contains(@class,'course-listing-title') and contains(text(),'{0}')]"
37 | _courseLocator = _course.format("JavaScript for beginners")
38 |
39 | courseElement = driver.find_element(By.XPATH, _courseLocator)
40 | courseElement.click()
41 |
42 | ff = DynamicXPathFormat()
43 | ff.test()
44 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_SwitchWindowAndIFrame/130 switch-to-window.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class SwitchToWindow():
11 |
12 | def test(self):
13 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 |
20 | # Find parent handle -> Main Window
21 | parentHandle = driver.current_window_handle
22 | print("Parent Handle: " + parentHandle)
23 |
24 | # Find open window button and click it
25 | driver.find_element(By.ID, "openwindow").click()
26 | time.sleep(2)
27 |
28 | # Find all handles, there should two handles after clicking open window button
29 | handles = driver.window_handles
30 |
31 | # Switch to window and search course
32 | for handle in handles:
33 | print("Handle: " + handle)
34 | if handle not in parentHandle:
35 | driver.switch_to.window(handle)
36 | print("Switched to window:: " + handle)
37 | searchBox = driver.find_element(By.ID, "search-courses")
38 | searchBox.send_keys("python")
39 | time.sleep(2)
40 | driver.close()
41 | break
42 |
43 | # Switch back to the parent handle
44 | driver.switch_to.window(parentHandle)
45 | driver.find_element(By.ID, "name").send_keys("Test Successful")
46 |
47 |
48 |
49 |
50 |
51 |
52 | ff = SwitchToWindow()
53 | ff.test()
54 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_4/183 3-register-courses-pages.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import utilities.custom_logger as cl
6 | import logging
7 | from base.basepage import BasePage
8 |
9 | class RegisterCoursesPage(BasePage):
10 |
11 | log = cl.customLogger(logging.DEBUG)
12 |
13 | def __init__(self, driver):
14 | super().__init__(driver)
15 | self.driver = driver
16 |
17 | ################
18 | ### Locators ###
19 | ################
20 | _search_box = "search-courses"
21 | _course = "//div[contains(@class,'course-listing-title') and contains(text(),'{0}')]"
22 | _all_courses = "course-listing-title"
23 | _enroll_button = "enroll-button-top"
24 | _cc_num = "cc_field"
25 | _cc_exp = "cc-exp"
26 | _cc_cvv = "cc_cvc"
27 | _submit_enroll = "//div[@id='new_card']//button[contains(text(),'Enroll in Course')]"
28 | _enroll_error_message = "//div[@id='new_card']//div[contains(text(),'The card number is not a valid credit card number.')]"
29 |
30 | ############################
31 | ### Element Interactions ###
32 | ############################
33 |
34 | def enterCourseName(self, name):
35 | print()
36 |
37 | def selectCourseToEnroll(self, fullCourseName):
38 | print()
39 |
40 | def clickOnEnrollButton(self):
41 | print()
42 |
43 | def enterCardNum(self, num):
44 | print()
45 |
46 | def enterCardExp(self, exp):
47 | print()
48 |
49 | def enterCardCVV(self, cvv):
50 | print()
51 |
52 | def clickEnrollSubmitButton(self):
53 | print()
54 |
55 | def enterCreditCardInformation(self, num, exp, cvv):
56 | print()
57 |
58 | def enrollCourse(self, num="", exp="", cvv=""):
59 | print()
60 |
61 | def verifyEnrollFailed(self):
62 | print()
63 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_2/173 5-webdriverfactory.py:
--------------------------------------------------------------------------------
1 | """
2 | @package base
3 |
4 | WebDriver Factory class implementation
5 | It creates a webdriver instance based on browser configurations
6 |
7 | Example:
8 | wdf = WebDriverFactory(browser)
9 | wdf.getWebDriverInstance()
10 | """
11 | import traceback
12 | from selenium import webdriver
13 |
14 | class WebDriverFactory():
15 |
16 | def __init__(self, browser):
17 | """
18 | Inits WebDriverFactory class
19 |
20 | Returns:
21 | None
22 | """
23 | self.browser = browser
24 | """
25 | Set chrome driver and iexplorer environment based on OS
26 |
27 | chromedriver = "C:/.../chromedriver.exe"
28 | os.environ["webdriver.chrome.driver"] = chromedriver
29 | self.driver = webdriver.Chrome(chromedriver)
30 |
31 | PREFERRED: Set the path on the machine where browser will be executed
32 | """
33 |
34 | def getWebDriverInstance(self):
35 | """
36 | Get WebDriver Instance based on the browser configuration
37 |
38 | Returns:
39 | 'WebDriver Instance'
40 | """
41 | baseURL = "https://letskodeit.teachable.com/"
42 | if self.browser == "iexplorer":
43 | # Set ie driver
44 | driver = webdriver.Ie()
45 | elif self.browser == "firefox":
46 | driver = webdriver.Firefox()
47 | elif self.browser == "chrome":
48 | # Set chrome driver
49 | driver = webdriver.Chrome()
50 | else:
51 | driver = webdriver.Firefox()
52 | # Setting Driver Implicit Time out for An Element
53 | driver.implicitly_wait(3)
54 | # Maximize the window
55 | driver.maximize_window()
56 | # Loading browser with App URL
57 | driver.get(baseURL)
58 | return driver
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/DatePicker.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 22, 2018
3 |
4 | @author: venkateshwara.d
5 | '''
6 | import time
7 | from selenium import webdriver
8 | from selenium.webdriver.support.select import Select
9 | import os
10 |
11 | baseUrl = "https://jqueryui.com/datepicker/#date-range"
12 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 | # Window Maximize
16 | driver.maximize_window()
17 | # Open the Url
18 | driver.get(baseUrl)
19 | time.sleep(3)
20 | #define frame
21 | frame=driver.find_element_by_tag_name('iframe')
22 | #switch to frame
23 | driver.switch_to_frame(frame)
24 | #Choose From Month Day Date
25 | datepicker_from=driver.find_element_by_xpath("//input[@id='from']")
26 | datepicker_from.click()
27 | time.sleep(2)
28 | month_from=driver.find_element_by_xpath("//div/select[@class='ui-datepicker-month']")
29 | month_from.click()
30 | time.sleep(3)
31 | select_from_month=Select(month_from)
32 | select_from_month.select_by_visible_text("Apr")
33 | time.sleep(2)
34 | day_from=driver.find_element_by_xpath("//table/tbody/tr/td/a[text()='30']")
35 | day_from.click()
36 | time.sleep(5)
37 | #Choose To Month Day Date
38 | datepicker_to=driver.find_element_by_xpath("//input[@id='to']")
39 | datepicker_to.click()
40 | time.sleep(2)
41 | month_to=driver.find_element_by_xpath("//div/select[@class='ui-datepicker-month']")
42 | month_from.click()
43 | time.sleep(3)
44 | select_to_month=Select(month_to)
45 | select_to_month.select_by_visible_text("Jun")
46 | time.sleep(2)
47 | day_to=driver.find_element_by_xpath("//table/tbody/tr/td/a[text()='1']")
48 | day_to.click()
49 | time.sleep(5)
50 | #Get the string in To input
51 | to_month_string=datepicker_to.get_attribute('value')
52 | print(to_month_string)
53 | # close the browser
54 | driver.close()
55 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_3/175 2-teststatus.py:
--------------------------------------------------------------------------------
1 | """
2 | @package utilities
3 |
4 | CheckPoint class implementation
5 | It provides functionality to assert the result
6 |
7 | Example:
8 | self.check_point.markFinal("Test Name", result, "Message")
9 | """
10 | import utilities.custom_logger as cl
11 | import logging
12 | from base.selenium_driver import SeleniumDriver
13 |
14 | class TestStatus(SeleniumDriver):
15 |
16 | log = cl.customLogger(logging.INFO)
17 |
18 | def __init__(self, driver):
19 | """
20 | Inits CheckPoint class
21 | """
22 | super(TestStatus, self).__init__(driver)
23 | self.resultList = []
24 |
25 | def setResult(self, result, resultMessage):
26 | try:
27 | if result is not None:
28 | if result:
29 | self.resultList.append("PASS")
30 | self.log.info("### VERIFICATION SUCCESSFUL :: + " + resultMessage)
31 | else:
32 | self.resultList.append("FAIL")
33 | self.log.info("### VERIFICATION FAILED :: + " + resultMessage)
34 | else:
35 | self.resultList.append("FAIL")
36 | self.log.info("### VERIFICATION FAILED :: + " + resultMessage)
37 | except:
38 | self.resultList.append("FAIL")
39 | self.log.info("### Exception Occurred !!!")
40 |
41 | def mark(self, result, resultMessage):
42 | """
43 | Mark the result of the verification point in a test case
44 | """
45 | self.setResult(result, resultMessage)
46 |
47 | def markFinal(self, testName, result, resultMessage):
48 | """
49 | Mark the final result of the verification point in a test case
50 | This needs to be called at least once in a test case
51 | This should be final test status of the test case
52 | """
53 | print()
--------------------------------------------------------------------------------
/Python_basics/wait_types/explicit_wait_demo1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 24, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 | from selenium.webdriver.support.ui import WebDriverWait
10 | from selenium.webdriver.support import expected_conditions as EC
11 | from selenium.common.exceptions import *
12 | from selenium.webdriver.common.keys import Keys
13 |
14 | class ExplicitWaitDemo1():
15 |
16 | def test(self):
17 | baseUrl = "http://www.expedia.com"
18 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
19 |
20 | driver=webdriver.Chrome(chrome_driver_path)
21 | driver.implicitly_wait(.5)
22 | driver.maximize_window()
23 | driver.get(baseUrl)
24 | driver.find_element(By.ID, "tab-flight-tab-hp").click()
25 | driver.find_element(By.ID, "flight-origin-hp-flight").send_keys("SFO")
26 | driver.find_element(By.XPATH, ".//*[@id='flight-destination-hp-flight']").send_keys("NYC")
27 | driver.find_element(By.ID, "flight-departing-hp-flight").send_keys("12/24/2018")
28 | returnDate = driver.find_element(By.XPATH, "//input[@id='flight-returning-hp-flight']")
29 | returnDate.clear()
30 | returnDate.send_keys("12/26/2018")
31 | returnDate.send_keys(Keys.RETURN)
32 |
33 | wait = WebDriverWait(driver, 10, poll_frequency=1,
34 | ignored_exceptions=[NoSuchElementException,
35 | ElementNotVisibleException,
36 | ElementNotSelectableException])
37 | element = wait.until(EC.element_to_be_clickable((By.XPATH,
38 | "//select[@name='sort']")))
39 | element.click()
40 |
41 | time.sleep(2)
42 | driver.quit()
43 |
44 | ff = ExplicitWaitDemo1()
45 | ff.test()
46 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/095 BrowserInteractions.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import os
7 |
8 | class BrowserInteractions():
9 |
10 | def test(self):
11 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
12 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
13 |
14 | driver=webdriver.Chrome(chrome_driver_path)
15 |
16 | # Window Maximize
17 | driver.maximize_window()
18 | # Open the Url
19 | driver.get(baseUrl)
20 | # Get Title
21 | title = driver.title
22 | print("Title of the web page is: " + title)
23 | # Get Current Url
24 | currentUrl = driver.current_url
25 | print("Current Url of the web page is: " + currentUrl)
26 | # Browser Refresh
27 | driver.refresh()
28 | print("Browser Refreshed 1st time")
29 | driver.get(driver.current_url)
30 | print("Browser Refreshed 2nd time")
31 | # Open another Url
32 | driver.get("https://sso.teachable.com/secure/42299/users/sign_in?reset_purchase_session=1")
33 | currentUrl = driver.current_url
34 | print("Current Url of the web page is: " + currentUrl)
35 | # Browser Back
36 | driver.back()
37 | print("Go one step back in browser history")
38 | currentUrl = driver.current_url
39 | print("Current Url of the web page is: " + currentUrl)
40 | # Browser Forward
41 | driver.forward()
42 | print("Go one step forward in browser history")
43 | currentUrl = driver.current_url
44 | print("Current Url of the web page is: " + currentUrl)
45 | # Get Page Source
46 | pageSource = driver.page_source
47 | print(pageSource.encode("utf-8"))
48 | # Browser Close / Quit
49 | # driver.close()
50 | driver.quit()
51 |
52 | ff = BrowserInteractions()
53 | ff.test()
54 |
--------------------------------------------------------------------------------
/Python_basics/RunningCompleteTestSuite/193 4-webdriverfactory.py:
--------------------------------------------------------------------------------
1 | """
2 | @package base
3 |
4 | WebDriver Factory class implementation
5 | It creates a webdriver instance based on browser configurations
6 |
7 | Example:
8 | wdf = WebDriverFactory(browser)
9 | wdf.getWebDriverInstance()
10 | """
11 | import traceback
12 | from selenium import webdriver
13 | import os
14 |
15 | class WebDriverFactory():
16 |
17 | def __init__(self, browser):
18 | """
19 | Inits WebDriverFactory class
20 |
21 | Returns:
22 | None
23 | """
24 | self.browser = browser
25 | """
26 | Set chrome driver and iexplorer environment based on OS
27 |
28 | chromedriver = "C:/.../chromedriver.exe"
29 | os.environ["webdriver.chrome.driver"] = chromedriver
30 | self.driver = webdriver.Chrome(chromedriver)
31 |
32 | PREFERRED: Set the path on the machine where browser will be executed
33 | """
34 |
35 | def getWebDriverInstance(self):
36 | """
37 | Get WebDriver Instance based on the browser configuration
38 |
39 | Returns:
40 | 'WebDriver Instance'
41 | """
42 | baseURL = "https://letskodeit.teachable.com/"
43 | if self.browser == "iexplorer":
44 | # Set ie driver
45 | driver = webdriver.Ie()
46 | elif self.browser == "firefox":
47 | driver = webdriver.Firefox()
48 | elif self.browser == "chrome":
49 | # Set chrome driver
50 | chromedriver = "/Users/atomar/Documents/workspace_personal/selenium/chromedriver"
51 | os.environ["webdriver.chrome.driver"] = chromedriver
52 | driver = webdriver.Chrome(chromedriver)
53 | driver.set_window_size(1440, 900)
54 | else:
55 | driver = webdriver.Firefox()
56 | # Setting Driver Implicit Time out for An Element
57 | driver.implicitly_wait(3)
58 | # Maximize the window
59 | driver.maximize_window()
60 | # Loading browser with App URL
61 | driver.get(baseURL)
62 | return driver
--------------------------------------------------------------------------------
/Python_basics/utilities/handy_wrappers.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium.webdriver.common.by import By
6 |
7 | class HandyWrappers():
8 |
9 | def __init__(self, driver):
10 | self.driver = driver
11 |
12 | def getByType(self, locatorType):
13 | locatorType = locatorType.lower()
14 | if locatorType == "id":
15 | return By.ID
16 | elif locatorType == "name":
17 | return By.NAME
18 | elif locatorType == "xpath":
19 | return By.XPATH
20 | elif locatorType == "css":
21 | return By.CSS_SELECTOR
22 | elif locatorType == "classname":
23 | return By.CLASS_NAME
24 | elif locatorType == "linktext":
25 | return By.LINK_TEXT
26 | else:
27 | print("Locator type " + locatorType + " not correct/supported")
28 | return False
29 |
30 | def getElement(self, locator, locatorType="id"):
31 | element = None
32 | try:
33 | locatorType = locatorType.lower()
34 | byType = self.getByType(locatorType)
35 | element = self.driver.find_element(byType, locator)
36 | print("Element Found")
37 | except:
38 | print("Element not found")
39 | return element
40 |
41 | def isElementPresent(self, locator, byType):
42 | try:
43 | element = self.driver.find_element(byType, locator)
44 | if element is not None:
45 | print("Element Found")
46 | return True
47 | else:
48 | print("Element not found")
49 | return False
50 | except:
51 | print("Element not found")
52 | return False
53 |
54 | def elementPresenceCheck(self, locator, byType):
55 | try:
56 | elementList = self.driver.find_elements(byType, locator)
57 | if len(elementList) > 0:
58 | print("Element Found")
59 | return True
60 | else:
61 | print("Element not found")
62 | return False
63 | except:
64 | print("Element not found")
65 | return False
66 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_3/176 3-teststatus.py:
--------------------------------------------------------------------------------
1 | """
2 | @package utilities
3 |
4 | CheckPoint class implementation
5 | It provides functionality to assert the result
6 |
7 | Example:
8 | self.check_point.markFinal("Test Name", result, "Message")
9 | """
10 | import utilities.custom_logger as cl
11 | import logging
12 | from base.selenium_driver import SeleniumDriver
13 |
14 | class TestStatus(SeleniumDriver):
15 |
16 | log = cl.customLogger(logging.INFO)
17 |
18 | def __init__(self, driver):
19 | """
20 | Inits CheckPoint class
21 | """
22 | super(TestStatus, self).__init__(driver)
23 | self.resultList = []
24 |
25 | def setResult(self, result, resultMessage):
26 | try:
27 | if result is not None:
28 | if result:
29 | self.resultList.append("PASS")
30 | self.log.info("### VERIFICATION SUCCESSFUL :: + " + resultMessage)
31 | else:
32 | self.resultList.append("FAIL")
33 | self.log.error("### VERIFICATION FAILED :: + " + resultMessage)
34 | else:
35 | self.resultList.append("FAIL")
36 | self.log.error("### VERIFICATION FAILED :: + " + resultMessage)
37 | except:
38 | self.resultList.append("FAIL")
39 | self.log.error("### Exception Occurred !!!")
40 |
41 | def mark(self, result, resultMessage):
42 | """
43 | Mark the result of the verification point in a test case
44 | """
45 | self.setResult(result, resultMessage)
46 |
47 | def markFinal(self, testName, result, resultMessage):
48 | """
49 | Mark the final result of the verification point in a test case
50 | This needs to be called at least once in a test case
51 | This should be final test status of the test case
52 | """
53 | self.setResult(result, resultMessage)
54 |
55 | if "FAIL" in self.resultList:
56 | self.log.error(testName + " ### TEST FAILED")
57 | self.resultList.clear()
58 | assert True == False
59 | else:
60 | self.log.info(testName + " ### TEST SUCCESSFUL")
61 | self.resultList.clear()
62 | assert True == True
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriver_Advanced/120 calendar-selection.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 |
10 | class CalendarSelection():
11 |
12 | def test1(self):
13 | baseUrl = "http://www.expedia.com"
14 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
15 |
16 | driver=webdriver.Chrome(chrome_driver_path)
17 | driver.maximize_window()
18 | driver.get(baseUrl)
19 | driver.implicitly_wait(3)
20 |
21 | # Click flights tab
22 | driver.find_element_by_id("tab-flight-tab-hp").click()
23 | # Find departing field
24 | departingField = driver.find_element_by_id("flight-departing-hp-flight")
25 | # Click departing field
26 | departingField.click()
27 | # Find the date to be selected
28 | # Expedia website has changed the DOM after the lecture was made
29 | # Updated new xpath
30 | dateToSelect = driver.find_element(By.XPATH,
31 | "(//div[@class='datepicker-cal-month'])[1]//button[text()='30']")
32 | # Click the date
33 | dateToSelect.click()
34 |
35 | time.sleep(3)
36 | driver.quit()
37 |
38 | def test2(self):
39 | baseUrl = "http://www.expedia.com"
40 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
41 |
42 | driver=webdriver.Chrome(chrome_driver_path)
43 | driver.maximize_window()
44 | driver.get(baseUrl)
45 | driver.implicitly_wait(3)
46 |
47 | # Click flights tab
48 | driver.find_element_by_id("tab-flight-tab-hp").click()
49 | # Click departing field
50 | driver.find_element_by_id("flight-departing-hp-flight").click()
51 | # Expedia website has changed the DOM after the lecture was made
52 | # Updated new xpath
53 | calMonth = driver.find_element(By.XPATH, "(//div[@class='datepicker-cal-month'])[1]")
54 | allValidDates = calMonth.find_elements(By.TAG_NAME, "button")
55 | time.sleep(2)
56 |
57 | for date in allValidDates:
58 | if date.text == "30":
59 | date.click()
60 | break
61 |
62 | ff = CalendarSelection()
63 | ff.test1()
64 | ff.test2()
65 |
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_3/178 5-teststatus.py:
--------------------------------------------------------------------------------
1 | """
2 | @package utilities
3 |
4 | CheckPoint class implementation
5 | It provides functionality to assert the result
6 |
7 | Example:
8 | self.check_point.markFinal("Test Name", result, "Message")
9 | """
10 | import utilities.custom_logger as cl
11 | import logging
12 | from base.selenium_driver import SeleniumDriver
13 | from traceback import print_stack
14 |
15 | class TestStatus(SeleniumDriver):
16 |
17 | log = cl.customLogger(logging.INFO)
18 |
19 | def __init__(self, driver):
20 | """
21 | Inits CheckPoint class
22 | """
23 | super(TestStatus, self).__init__(driver)
24 | self.resultList = []
25 |
26 | def setResult(self, result, resultMessage):
27 | try:
28 | if result is not None:
29 | if result:
30 | self.resultList.append("PASS")
31 | self.log.info("### VERIFICATION SUCCESSFUL :: + " + resultMessage)
32 | else:
33 | self.resultList.append("FAIL")
34 | self.log.error("### VERIFICATION FAILED :: + " + resultMessage)
35 | self.screenShot(resultMessage)
36 | else:
37 | self.resultList.append("FAIL")
38 | self.log.error("### VERIFICATION FAILED :: + " + resultMessage)
39 | self.screenShot(resultMessage)
40 | except:
41 | self.resultList.append("FAIL")
42 | self.log.error("### Exception Occurred !!!")
43 | self.screenShot(resultMessage)
44 | print_stack()
45 |
46 | def mark(self, result, resultMessage):
47 | """
48 | Mark the result of the verification point in a test case
49 | """
50 | self.setResult(result, resultMessage)
51 |
52 | def markFinal(self, testName, result, resultMessage):
53 | """
54 | Mark the final result of the verification point in a test case
55 | This needs to be called at least once in a test case
56 | This should be final test status of the test case
57 | """
58 | self.setResult(result, resultMessage)
59 |
60 | if "FAIL" in self.resultList:
61 | self.log.error(testName + " ### TEST FAILED")
62 | self.resultList.clear()
63 | assert True == False
64 | else:
65 | self.log.info(testName + " ### TEST SUCCESSFUL")
66 | self.resultList.clear()
67 | assert True == True
--------------------------------------------------------------------------------
/Python_basics/AutomationFramework_Part_4/184 4-register-courses-pages.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | import utilities.custom_logger as cl
6 | import logging
7 | from base.basepage import BasePage
8 |
9 | class RegisterCoursesPage(BasePage):
10 |
11 | log = cl.customLogger(logging.DEBUG)
12 |
13 | def __init__(self, driver):
14 | super().__init__(driver)
15 | self.driver = driver
16 |
17 | ################
18 | ### Locators ###
19 | ################
20 | _search_box = "search-courses"
21 | _course = "//div[contains(@class,'course-listing-title') and contains(text(),'{0}')]"
22 | _all_courses = "course-listing-title"
23 | _enroll_button = "enroll-button-top"
24 | _cc_num = "cc_field"
25 | _cc_exp = "cc-exp"
26 | _cc_cvv = "cc_cvc"
27 | _submit_enroll = "//div[@id='new_card']//button[contains(text(),'Enroll in Course')]"
28 | _enroll_error_message = "//div[@id='new_card']//div[contains(text(),'The card number is not a valid credit card number.')]"
29 |
30 | ############################
31 | ### Element Interactions ###
32 | ############################
33 |
34 | def enterCourseName(self, name):
35 | self.sendKeys(name, locator=self._search_box)
36 |
37 | def selectCourseToEnroll(self, fullCourseName):
38 | self.elementClick(locator=self._course.format(fullCourseName), locatorType="xpath")
39 |
40 | def clickOnEnrollButton(self):
41 | self.elementClick(locator=self._enroll_button)
42 |
43 | def enterCardNum(self, num):
44 | self.sendKeys(num, locator=self._cc_num)
45 |
46 | def enterCardExp(self, exp):
47 | self.sendKeys(exp, locator=self._cc_exp)
48 |
49 | def enterCardCVV(self, cvv):
50 | self.sendKeys(cvv, locator=self._cc_cvv)
51 |
52 | def clickEnrollSubmitButton(self):
53 | self.sendKeys(self._submit_enroll, locator="xpath")
54 |
55 | def enterCreditCardInformation(self, num, exp, cvv):
56 | self.enterCardNum(num)
57 | self.enterCardExp(exp)
58 | self.enterCardCVV(cvv)
59 |
60 | def enrollCourse(self, num="", exp="", cvv=""):
61 | self.clickOnEnrollButton()
62 | self.webScroll(direction="down")
63 | self.enterCreditCardInformation(num, exp, cvv)
64 | self.clickEnrollSubmitButton()
65 |
66 | def verifyEnrollFailed(self):
67 | messageElement = self.waitForElement(self._enroll_error_message, locatorType="xpath")
68 | result = self.isElementDisplayed(element=messageElement)
69 | return result
70 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverWorkingWithWebElements/103 HiddenElements.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | import time
7 | import os
8 |
9 | class HiddenElements():
10 |
11 | def testLetsKodeIt(self):
12 | baseUrl = "https://letskodeit.teachable.com/pages/practice"
13 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
14 |
15 | driver=webdriver.Chrome(chrome_driver_path)
16 | driver.maximize_window()
17 | driver.get(baseUrl)
18 | driver.implicitly_wait(2)
19 |
20 |
21 | # Find the state of the text box
22 | textBoxElement = driver.find_element_by_id("displayed-text")
23 | textBoxState = textBoxElement.is_displayed() # True if visible, False if hidden
24 | # Exception if not present in the DOM
25 | print("Text is visible? " + str(textBoxState))
26 | time.sleep(2)
27 |
28 | # Click the Hide button
29 | driver.find_element_by_id("hide-textbox").click()
30 | # Find the state of the text box
31 | textBoxState = textBoxElement.is_displayed()
32 | print("Text is visible? " + str(textBoxState))
33 | time.sleep(2)
34 |
35 | # Added code to scroll up because the element was hiding behind the top navigation menu
36 | # You will learn about scrolling in future lecture
37 | driver.execute_script("window.scrollBy(0, -150);")
38 | # Click the Show button
39 | driver.find_element_by_id("show-textbox").click()
40 | # Find the state of the text box
41 | textBoxState = textBoxElement.is_displayed()
42 | print("Text is visible? " + str(textBoxState))
43 | time.sleep(2)
44 | # Browser Close
45 | driver.quit()
46 |
47 | def testExpedia(self):
48 | baseUrl = "http://www.expedia.com"
49 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
50 |
51 | driver=webdriver.Chrome(chrome_driver_path)
52 | driver.maximize_window()
53 | driver.get(baseUrl)
54 | driver.implicitly_wait(3)
55 | #selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"tab-flight-tab"}
56 | driver.find_element_by_id("tab-flight-tab").click()
57 |
58 | drpdwnElement = driver.find_element_by_id("flight-age-select-1")
59 | print("Element visible? " + str(drpdwnElement.is_displayed()))
60 |
61 |
62 | ff = HiddenElements()
63 | ff.testLetsKodeIt()
64 | ff.testExpedia()
65 |
--------------------------------------------------------------------------------
/Python_basics/base/configreader.py:
--------------------------------------------------------------------------------
1 | """
2 | @package base
3 |
4 | ConfigReader class implementation
5 |
6 | It reads the configuration files needed for the framework
7 |
8 | All the methods to read different configuration file should be implemented in Util class
9 |
10 | Example:
11 | self.cfg = ConfigReader(fileName=fileName)
12 | self.cfg.configRead()
13 | value = self.cfg.getConfiguration(section, option)
14 | """
15 | from configparser import ConfigParser
16 | import os
17 |
18 | class ConfigReader(object):
19 |
20 | def __init__(self, fileName="messages.ini"):
21 | self.parser = ConfigParser()
22 | scriptDirectory = os.path.dirname(__file__)
23 | relativePath = "../configfiles/" + fileName
24 | absFilePath = os.path.join(scriptDirectory, relativePath)
25 | self.file = absFilePath
26 | # self.file = ['/auto/home.nas03/atomar/hg/ntests/cases/gui/configfiles/testenvironment.ini']
27 |
28 | def configRead (self):
29 | self.parser.read(self.file)
30 |
31 | def configSectionMap(self, section):
32 | """
33 | Returns a dictionary of 'Option and Value' under a section
34 |
35 | Required Parameters:
36 | section: Section in the file under which options exist
37 | Look at messages.ini to understand the format of a configuration file
38 |
39 | Optional Parameters:
40 | None
41 |
42 | Returns:
43 | Dictionary of 'Option and Value'
44 | """
45 | config = {}
46 | options = self.parser.options(section)
47 | for option in options:
48 | try:
49 | config[option] = self.parser.get(section, option)
50 | if config[option] == -1:
51 | print("skip: %s" % option)
52 | except:
53 | print("exception on %s!" % option)
54 | config[option] = None
55 | return config
56 |
57 | def getConfiguration(self, section, option):
58 | """
59 | Get value of the provided option and section
60 |
61 | Required Parameters:
62 | section: Section in the file under which options exist
63 | option: Option whose corresponding value is needed
64 |
65 | Optional Parameters:
66 | None
67 |
68 | Returns:
69 | Value of the provided option
70 | """
71 | config_map = self.configSectionMap(section)
72 | option_value = config_map[option]
73 | return option_value
74 |
75 |
76 | def testMethod(self):
77 | value = ConfigReader.getConfiguration(self,'Grid', 'remote')
78 | print(value)
79 |
--------------------------------------------------------------------------------
/Python_basics/SeleniumWebDriverUsefulMethodsAndProperties/106 2-airbnb-exercise1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on May 30, 2018
3 | @author: venkateshwara.d
4 | '''
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | import time
8 | import os
9 | from selenium.webdriver.support.select import Select
10 |
11 | class AirbnbExercise1():
12 |
13 | def test(self):
14 | baseUrl = "https://www.airbnb.com/"
15 | chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe"
16 |
17 | driver=webdriver.Chrome(chrome_driver_path)
18 | #driver = webdriver.Chrome()
19 | driver.maximize_window()
20 | driver.get(baseUrl)
21 | driver.implicitly_wait(10)
22 |
23 | # Elements and design has changed on Airbnb website after the lecture was made
24 | searchBox = driver.find_element(By.NAME, "location")
25 | searchBox.send_keys("Hawaii")
26 |
27 | when = driver.find_element(By.XPATH,
28 | "(//button//span[text()='Anytime'])[2]")
29 | when.click()
30 | time.sleep(2)
31 |
32 | checkin = driver.find_element(By.XPATH,
33 | "(//div[contains(@class,'CalendarMonth') and @data-visible='true']//div[text()='30']//parent::button)[1]")
34 | checkin.click()
35 |
36 | checkout = driver.find_element(By.XPATH,
37 | "(//div[contains(@class,'CalendarMonth') and @data-visible='true']//div[text()='30']//parent::button)[2]")
38 | checkout.click()
39 |
40 | showInstant = driver.find_elements(By.XPATH, "//span[text()='Show Instant Book Listings']")
41 | if len(showInstant) > 0:
42 | showInstant[0].click()
43 |
44 | dropdownElement = driver.find_element(By.XPATH,
45 | "(//span[text()='1 guest'])[2]")
46 | #sel = Select(dropdownElement)
47 | #sel.select_by_visible_text("2 Guests")
48 | # It is updated to