0% found this document useful (0 votes)
8 views31 pages

Software Testing Lab Record Set2

The document outlines a series of laboratory experiments focused on software testing, including performance testing of an e-commerce application using Apache JMeter, automation of functional testing with Selenium WebDriver, integration of TestNG for structured test execution, and execution of test cases against a client-server application. Each experiment includes aims, algorithms, procedures, and results, highlighting successful testing outcomes and identified bottlenecks or defects. The document serves as a comprehensive guide for conducting various software testing methodologies and practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views31 pages

Software Testing Lab Record Set2

The document outlines a series of laboratory experiments focused on software testing, including performance testing of an e-commerce application using Apache JMeter, automation of functional testing with Selenium WebDriver, integration of TestNG for structured test execution, and execution of test cases against a client-server application. Each experiment includes aims, algorithms, procedures, and results, highlighting successful testing outcomes and identified bottlenecks or defects. The document serves as a comprehensive guide for conducting various software testing methodologies and practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Software Testing Lab Record

Laboratory Experiments 1 – 10 | Set II

Topics: Performance Testing, Selenium Automation, TestNG, Security Testing,


JUnit, Complete Testing Workflow, Jenkins CI/CD
EXPERIMENT 1: Test the Performance of the E-Commerce Application

AIM
To test the performance of an e-commerce application ([Link]) using Apache JMeter by simulating
multiple concurrent users and measuring response time, throughput, and error rate under load.

ALGORITHM
1. Install and launch Apache JMeter.
2. Create a Test Plan with a Thread Group (simulated users).
3. Add HTTP Request samplers for key pages: Home, Search, Product Detail, Cart, Checkout.
4. Add Listeners: View Results Tree, Summary Report, Response Time Graph.
5. Configure load: 50 users, ramp-up 10 seconds, 3 iterations.
6. Run the test and collect metrics: Response Time (ms), Throughput (req/sec), Error %.
7. Analyze bottlenecks and document observations.

PROCEDURE
Step 1 – Install JMeter:
# Download Apache JMeter 5.6+
wget [Link]
tar -xvzf [Link]
cd apache-jmeter-5.6.3/bin && ./[Link] # Linux/Mac
# Windows: double-click [Link]

Step 2 – JMeter Test Plan Configuration:


• Right-click Test Plan → Add → Threads → Thread Group
• Number of Threads (Users): 50
• Ramp-Up Period: 10 seconds
• Loop Count: 3

Step 3 – Add HTTP Request Samplers:


• Add → Sampler → HTTP Request
• Server: [Link] | Protocol: https | Port: 443
• Paths: / (Home), /s?k=laptop (Search), /dp/ASIN (Product), /gp/cart/[Link] (Cart)

Step 4 – Add Config Elements:


• HTTP Cookie Manager (handles session cookies)
• HTTP Cache Manager (simulates browser caching)
• HTTP Header Manager (sets User-Agent, Accept headers)

Step 5 – Add Listeners:


• View Results Tree – see pass/fail per request
• Summary Report – aggregate metrics
• Response Time Graph – visualize latency trends

Step 6 – Run: Click the green Play button. Save results to [Link].
PERFORMANCE METRICS (Sample Results)
Page Avg Min (ms) Max (ms) Throughput Error %
Response (req/s)
(ms)
Home Page 320 210 850 45.2 0.0%
Search 540 380 1200 32.1 0.0%
(laptop)
Product Detail 480 310 990 38.5 0.0%
Cart Page 290 190 610 51.3 0.0%
Checkout 720 500 1850 21.4 2.0%
Page

Performance Thresholds:
• Acceptable: Avg response < 1000ms, Error % < 1%
• Checkout page exceeded 1% error threshold — bottleneck identified

RESULT
Performance testing of [Link] was successfully conducted using Apache JMeter with 50
concurrent users. Home, Search, Product, and Cart pages met performance benchmarks. The
Checkout page was identified as a bottleneck with 2% error rate and 720ms avg response, requiring
optimization.
EXPERIMENT 2: Automate the Testing of E-Commerce Applications Using
Selenium

AIM
To automate the functional testing of an e-commerce application ([Link]) using Selenium
WebDriver with Python, covering product search, product detail verification, and cart operations.

ALGORITHM
1. Initialize Chrome WebDriver with options.
2. Navigate to [Link].
3. Automate product search using the search bar.
4. Verify search results are displayed.
5. Click on the first product and verify product title and price are visible.
6. Add product to cart and verify cart count increases.
7. Apply assertions at each step and print results.
8. Close the browser.

PROCEDURE
Step 1 – Install dependencies:
pip install selenium webdriver-manager pytest

CODE
test_ecommerce_automation.py
import time
from selenium import webdriver
from [Link] import By
from [Link] import Keys
from [Link] import WebDriverWait
from [Link] import expected_conditions as EC
from [Link] import Service
from webdriver_manager.chrome import ChromeDriverManager

def init_driver():
opts = [Link]()
opts.add_argument('--start-maximized')
opts.add_argument('--disable-notifications')
driver = [Link](
service=Service(ChromeDriverManager().install()), options=opts)
driver.implicitly_wait(10)
return driver

def test_search(driver, wait):


[Link]('[Link]
search = [Link](EC.presence_of_element_located(([Link],
'twotabsearchtextbox')))
[Link]()
search.send_keys('wireless headphones')
search.send_keys([Link])
results = [Link](EC.presence_of_all_elements_located(
(By.CSS_SELECTOR, 'div[data-component-type="s-search-result"]')))
assert len(results) > 0, 'No search results found!'
print(f'[PASS] Search returned {len(results)} results')
return results[0]

def test_product_detail(driver, wait, first_result):


title_el = first_result.find_element(By.CSS_SELECTOR, 'h2 a')
product_name = title_el.text
title_el.click()
# Verify product title on detail page
prod_title = [Link](EC.presence_of_element_located(([Link], 'productTitle')))
assert prod_title.[Link]() != '', 'Product title is empty!'
print(f'[PASS] Product detail page: {prod_title.text[:60]}...')
# Verify price is visible
try:
price = driver.find_element(By.CSS_SELECTOR, '.a-price .a-offscreen')
print(f'[PASS] Price found: {price.get_attribute("innerHTML")}')
except:
print('[INFO] Price element not found (may be out of stock)')

def test_add_to_cart(driver, wait):


try:
add_btn = [Link](EC.element_to_be_clickable(([Link], 'add-to-cart-
button')))
add_btn.click()
# Verify cart count
cart_count = [Link](EC.presence_of_element_located(
([Link], 'nav-cart-count')))
count = int(cart_count.text)
assert count > 0, 'Cart count did not increase!'
print(f'[PASS] Item added to cart. Cart count: {count}')
except Exception as e:
print(f'[INFO] Add to cart skipped: {e}')

if __name__ == '__main__':
driver = init_driver()
wait = WebDriverWait(driver, 15)
try:
first = test_search(driver, wait)
test_product_detail(driver, wait, first)
test_add_to_cart(driver, wait)
print('\n[ALL AUTOMATION TESTS PASSED]')
except AssertionError as e:
print(f'[ASSERTION FAIL] {e}')
except Exception as e:
print(f'[ERROR] {e}')
finally:
[Link](2)
[Link]()

EXPECTED OUTPUT
[PASS] Search returned 24 results
[PASS] Product detail page: boAt Rockerz 450 Bluetooth On Ear Headphones...
[PASS] Price found: ₹1,299
[PASS] Item added to cart. Cart count: 1

[ALL AUTOMATION TESTS PASSED]

RESULT
E-commerce application testing was successfully automated using Selenium WebDriver with Python.
Product search, product detail verification, price display, and cart addition were all automated with
appropriate assertions. All test steps passed successfully.
EXPERIMENT 3: Integrate TestNG with the Above Test Automation

AIM
To integrate TestNG (Testing Next Generation) framework with Selenium WebDriver automation tests
written in Java, enabling structured test execution, grouping, parallel runs, and HTML report generation.

ALGORITHM
1. Set up a Maven project with Selenium and TestNG dependencies.
2. Write test class using @Test, @BeforeMethod, @AfterMethod annotations.
3. Use @DataProvider for data-driven testing.
4. Configure [Link] for test suite definition.
5. Run tests via Maven (mvn test) or TestNG plugin.
6. Generate and review HTML report in test-output/ folder.

PROCEDURE
Step 1 – Maven [Link] dependencies:
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.1</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.7.0</version>
</dependency>
</dependencies>

CODE
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;

public class AmazonTestNG {


WebDriver driver;
WebDriverWait wait;

@BeforeMethod
public void setUp() {
[Link]().setup();
ChromeOptions opts = new ChromeOptions();
[Link]("--start-maximized");
driver = new ChromeDriver(opts);
wait = new WebDriverWait(driver, [Link](10));
[Link]("[Link]
}

@Test(priority = 1, description = "Verify Amazon homepage title")


public void testHomePageTitle() {
String title = [Link]();
[Link]([Link]("Amazon"),
"Title mismatch: " + title);
[Link]("[PASS] Homepage title: " + title);
}

@Test(priority = 2, description = "Search for a product")


public void testProductSearch() {
WebElement searchBox = [Link](

[Link]([Link]("twotabsearchtextbox")));
[Link]("laptop");
[Link]();
[Link]([Link]("laptop"));
[Link]([Link]().toLowerCase().contains("laptop"));
[Link]("[PASS] Search results page loaded");
}

@Test(priority = 3, dataProvider = "searchKeywords",


description = "Data-driven search test")
public void testMultipleSearches(String keyword) {
WebElement searchBox = [Link](

[Link]([Link]("twotabsearchtextbox")));
[Link]();
[Link](keyword);
[Link]();
[Link]([Link](keyword));
[Link]("[PASS] Search for '" + keyword + "' successful");
}

@DataProvider(name = "searchKeywords")
public Object[][] searchData() {
return new Object[][] {
{"mobile phone"},
{"books"},
{"headphones"}
};
}

@AfterMethod
public void tearDown() {
if (driver != null) [Link]();
}
}

[Link] (Suite Configuration)


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "[Link]
<suite name="AmazonTestSuite" verbose="2" parallel="methods" thread-count="2">
<test name="ECommerceTests">
<classes>
<class name="AmazonTestNG"/>
</classes>
</test>
</suite>
Run Tests:
mvn test -[Link]=[Link]

Reports generated at: target/surefire-reports/[Link] and test-output/[Link]

TESTNG ANNOTATIONS SUMMARY


Annotation Purpose
@BeforeSuite Runs once before all tests in the suite
@BeforeMethod Runs before each test method (browser setup)
@Test Marks a method as a test; supports priority,
groups, dataProvider
@DataProvider Supplies multiple data sets to a test method
@AfterMethod Runs after each test method (browser teardown)
@AfterSuite Runs once after all tests complete

RESULT
TestNG was successfully integrated with Selenium WebDriver Java automation. Tests were
structured with @BeforeMethod/@AfterMethod lifecycle hooks, @DataProvider for data-driven
testing, and [Link] for suite configuration. HTML reports were generated in test-output/ showing
pass/fail status for all 5 test executions.
EXPERIMENT 4: Execute Test Cases Against a Client-Server/Desktop
Application and Identify Defects

AIM
To execute functional test cases against a client-server or desktop application and systematically
identify, document, and classify defects found during testing.

ALGORITHM
1. Set up the client-server test environment (connect client to server DB).
2. Prepare test data in the server database.
3. Execute test cases for: Login, CRUD operations, data validation, concurrency, reporting.
4. Record actual vs expected results for each test case.
5. Log defects with complete details for any mismatch.
6. Classify defects by severity and priority.
7. Prepare a defect summary report.

PROCEDURE
Step 1 – Environment: Client machine (Windows 10) connects to MySQL Server 8.0 via LAN.
Application: Desktop ERP v3.2.
Step 2 – Test Execution: Execute all prepared test cases systematically.
Step 3 – Defect Logging: For each failed test case, record in defect log below.

TEST EXECUTION RESULTS


TC ID Test Description Expected Result Actual Result Status
TC001 Login with valid Dashboard opens Dashboard opens PASS
credentials
TC002 Login with wrong Error message Error message PASS
password shown shown
TC003 Add new Record saved in Record saved in PASS
employee record DB DB
TC004 Edit employee Updated value Old value retained FAIL
salary field saved
TC005 Delete record with Error: FK Record deleted FAIL
foreign key constraint (data loss!)
TC006 Concurrent edit Last write wins / Application FAIL
by 2 users conflict msg crashes
TC007 Generate monthly PDF downloaded PDF blank (no FAIL
report PDF data)
TC008 Search by Exact match Exact match PASS
employee ID returned returned
TC009 Numeric field Validation error Letters accepted FAIL
accepts letters shown silently
TC010 Session timeout Auto logout Session never FAIL
after 30 min expires

DEFECT REPORT
Defect ID Description Severity Priority Steps to
Reproduce
DEF001 Edit salary value High P2 Open record >
not saved Edit salary > Save
> Reopen → Old
value shown
DEF002 Delete ignores FK Critical P1 Add dept with
constraint employees >
Delete dept →
Employees
orphaned
DEF003 App crash on Critical P1 2 users open
concurrent edit same record >
Both click Save
simultaneously
DEF004 PDF report High P2 Reports > Monthly
generated blank > Select month >
Export PDF →
Blank PDF
DEF005 Numeric field Medium P3 Open salary field
accepts alphabets > Type 'abc' >
Save → Accepted
without error
DEF006 Session never Medium P3 Login > Leave idle
times out 40 min > Perform
action → Still
logged in

DEFECT SUMMARY
Severity Count Defect IDs
Critical 2 DEF002, DEF003
High 2 DEF001, DEF004
Medium 2 DEF005, DEF006
Total 6 –

RESULT
Test execution against the client-server desktop ERP application was completed. Out of 10 test
cases, 4 passed and 6 failed. Six defects were logged including 2 Critical (data loss on FK delete,
app crash on concurrent access), 2 High, and 2 Medium severity issues. All defects are ready for
developer handoff.
EXPERIMENT 5: Develop Test Plan and Design Test Cases for an Inventory
Control System

AIM
To develop a comprehensive test plan and design structured test cases for an Inventory Control
System (ICS) covering all core modules: Product Management, Stock Operations, Supplier
Management, Purchase Orders, and Reporting.

ALGORITHM
1. Analyze ICS requirements and identify all modules.
2. Define test objectives, scope, and out-of-scope items.
3. Select testing techniques: Functional, BVA, ECT, Integration.
4. Identify test environment, tools, and test data.
5. Define entry and exit criteria.
6. Design test cases for each module.
7. Review and baseline the test plan document.

TEST PLAN – INVENTORY CONTROL SYSTEM


Attribute Details
Project Name Inventory Control System (ICS) v2.5
In Scope Product CRUD, Stock In/Out, Low-stock Alert,
Supplier Mgmt, PO Lifecycle, Reports
Out of Scope Billing/Invoicing module, Mobile App
Test Types Functional, Boundary Value Analysis, Integration,
Regression, UAT
Tools Manual Testing, Selenium (UI), Postman (API),
MySQL Workbench (DB verification)
Environment Windows 11, Chrome 122, ICS v2.5 Staging,
MySQL 8.0
Test Data 100 products seeded, 10 suppliers, 5 warehouses
Entry Criteria ICS v2.5 deployed on staging, test data loaded,
smoke test passed
Exit Criteria 100% critical TCs executed, 95% pass rate, zero
P1/P2 defects open
Schedule Week 1: Planning | Week 2–3: Execution | Week
4: Regression + Closure
Team 1 Test Lead, 2 Test Engineers
Deliverables Test Plan, Test Cases, Defect Log, Test
Execution Report, Closure Report
TEST CASES – INVENTORY CONTROL SYSTEM
TC ID Module Description Input Expected Result
ICS001 Product Add product with Name, SKU, Product saved,
valid data price, category appears in list
ICS002 Product Add product with Existing SKU Error: SKU
duplicate SKU number already exists
ICS003 Product Delete product Product qty = 0 Product deleted
with zero stock successfully
ICS004 Product Delete product Product qty = 50 Error: Cannot
with stock > 0 delete, stock
exists
ICS005 Stock Stock-in valid Qty = 100, valid Stock updated:
quantity product prev + 100
ICS006 Stock Stock-out valid Qty <= available Stock reduced
quantity stock correctly
ICS007 Stock Stock-out Qty > available Error: Insufficient
exceeds available stock stock
ICS008 Stock – BVA Stock at reorder Stock reduced to Low-stock alert
level (=10) exactly 10 triggered
ICS009 Stock – BVA Stock just above Stock = 11 No alert
reorder (=11) generated
ICS010 Stock – BVA Stock just below Stock = 9 Low-stock alert
reorder (=9) triggered
ICS011 Supplier Add supplier valid Name, GST, Supplier saved
data contact, address with ID
ICS012 Supplier Add supplier Existing GST Error: GST
duplicate GST number already registered
ICS013 Purchase Order Create valid PO Supplier, items, PO created with
qty, delivery date unique PO#
ICS014 Purchase Order Approve PO Manager PO status →
approves pending Approved
PO
ICS015 Reports Generate stock Date range: last Accurate stock
report 30 days levels displayed

RESULT
A comprehensive test plan and 15 test cases were successfully developed for the Inventory Control
System. The test plan covers scope, objectives, environment, entry/exit criteria, schedule, and team
responsibilities. Test cases include BVA at reorder level boundaries (9, 10, 11 units) and cover all 5
core modules.
EXPERIMENT 6: Perform Basic Security Testing – SQL Injection Simulation

AIM
To perform basic security testing on a web application by simulating SQL Injection (SQLi) attacks to
identify vulnerabilities in login forms and search fields, and to verify that the application properly
sanitizes user inputs.

ALGORITHM
1. Identify input fields in the web application (login, search, registration).
2. Prepare a set of SQL injection payloads.
3. Enter each payload in the input fields and submit.
4. Observe server response: error messages, unexpected login, data exposure.
5. Automate SQLi testing using Python requests library.
6. Document findings: vulnerable vs protected inputs.
7. Suggest remediation for vulnerable fields.

COMMON SQL INJECTION PAYLOADS


Payload Type Purpose
' OR '1'='1 Authentication Bypass Always-true condition to bypass
login
' OR '1'='1' -- Comment Injection Comment out rest of SQL query
admin'-- Username Bypass Comment out password check
' UNION SELECT null, Union Attack Extract user credentials
username, password FROM
users--
'; DROP TABLE users;-- Destructive Injection Attempt table deletion
' AND SLEEP(5)-- Time-Based Blind SQLi Detect vulnerability via delay
1' ORDER BY 1-- Column Enumeration Find number of columns

PROCEDURE
Step 1 – Manual Testing on Local Test Application (DVWA – Damn Vulnerable Web App):
• Set up DVWA locally using XAMPP/Docker
• Navigate to Login page ([Link]
• Enter payload in Username: admin'-- and any password → Observe if login succeeds

Step 2 – Automated SQLi Detection Script:


import requests
from [Link] import urljoin

# !! For educational/ethical testing on authorized systems only !!


TARGET_URL = '[Link]
COOKIES = {'PHPSESSID': 'your_session_id', 'security': 'low'}
PAYLOADS = [
"' OR '1'='1",
"' OR '1'='1'--",
"admin'--",
"' UNION SELECT null, user()--",
"' AND SLEEP(3)--",
]

VULNERABLE_INDICATORS = [
'mysql_fetch', 'syntax error', 'sql', 'ORA-',
'ODBC', 'you have an error in your SQL syntax',
'Warning: mysql', 'unclosed quotation mark'
]

def test_sqli(url, payload):


params = {'id': payload, 'Submit': 'Submit'}
try:
response = [Link](url, params=params, cookies=COOKIES, timeout=10)
for indicator in VULNERABLE_INDICATORS:
if [Link]() in [Link]():
return True, indicator
if len([Link]) > 500: # Unexpected large response
return True, 'Large response (possible data dump)'
return False, 'Not vulnerable'
except [Link]:
return True, 'Timeout (possible time-based SQLi)'

print('='*60)
print(' SQL INJECTION VULNERABILITY SCANNER')
print('='*60)
for pl in PAYLOADS:
vuln, reason = test_sqli(TARGET_URL, pl)
status = '[VULNERABLE]' if vuln else '[SAFE]'
print(f'{status} Payload: {pl[:35]:<35} | Reason: {reason}')
print('='*60)

SECURITY TEST RESULTS (DVWA – Low Security)


Payload Result Evidence
' OR '1'='1 VULNERABLE All user records returned
' OR '1'='1'-- VULNERABLE Authentication bypassed
' UNION SELECT null, user()-- VULNERABLE DB user name exposed
' AND SLEEP(3)-- VULNERABLE Response delayed 3 seconds
Normal input: 1 SAFE Only user ID=1 returned

REMEDIATION
• Use Parameterized Queries / Prepared Statements (never concatenate user input in SQL)
• Use ORM frameworks (SQLAlchemy, Hibernate) which escape inputs automatically
• Implement input validation and whitelist allowed characters
• Apply Web Application Firewall (WAF) rules
• Use least-privilege DB accounts
RESULT
SQL Injection security testing was successfully performed on DVWA (authorized test environment).
Four SQLi vulnerabilities were identified including authentication bypass and data extraction via
UNION attacks. An automated Python scanner was developed to detect vulnerabilities. Remediation
recommendations including prepared statements and input sanitization were documented.
EXPERIMENT 7: Build a Complete Testing Workflow – Test Plan, Test Cases,
Execution, Defect Report

AIM
To build a complete end-to-end software testing workflow for an e-commerce application demonstrating
all phases: Test Planning → Test Case Design → Test Execution → Defect Reporting → Test
Summary.

ALGORITHM
1. Phase 1 – Test Planning: Define scope, objectives, resources, schedule.
2. Phase 2 – Test Design: Write test cases using functional and boundary techniques.
3. Phase 3 – Test Execution: Run test cases, record pass/fail, capture evidence.
4. Phase 4 – Defect Reporting: Log defects with severity, priority, steps.
5. Phase 5 – Test Summary: Calculate metrics, prepare closure report.

PHASE 1 – TEST PLAN (SUMMARY)


Field Value
Application [Link] – E-Commerce Web Application
Test Phase System Testing + Regression
Modules in Scope Login, Search, Product, Cart, Checkout, Payment,
Order Tracking
Test Types Functional, Regression, Boundary, Negative
Tools Selenium + Python, pytest, JIRA
Environment Chrome 122 / Windows 11 / Staging Server
Timeline 2 Weeks
Exit Criteria 95% TC pass, zero P1 defects open

PHASE 2 – TEST CASES (SELECTED)


TC ID Module Test Scenario Expected Result
WF001 Login Valid login Redirect to home
dashboard
WF002 Login Wrong password 3 Account temporarily
times locked
WF003 Search Search with valid Relevant products
keyword listed
WF004 Search Search with empty Error or popular items
input shown
WF005 Cart Add in-stock item Item appears in cart
WF006 Cart Update qty to 0 Item removed from cart
WF007 Checkout Apply valid promo code Discount reflected in
total
WF008 Payment Pay with valid UPI Order confirmation
shown
WF009 Payment Pay with expired card Error: Card expired
WF010 Order Track existing order Current status
displayed

PHASE 3 – TEST EXECUTION RESULTS


TC ID Status Actual Result Defect Ref
WF001 PASS Dashboard loaded –
correctly
WF002 PASS Lock message shown –
after 3 attempts
WF003 PASS 24 results returned –
WF004 FAIL Blank page shown (no DEF-101
error message)
WF005 PASS Item added, cart count –
=1
WF006 FAIL Qty=0 accepted, item DEF-102
stays in cart
WF007 PASS 10% discount applied –
correctly
WF008 PASS Order placed, –
confirmation email sent
WF009 PASS Error message –
displayed
WF010 FAIL Order status shows DEF-103
'Unknown'

PHASE 4 – DEFECT REPORT


Defect ID Summary Steps Severity Priority Status
DEF-101 Empty search Clear search > Medium P3 Open
shows blank Submit →
page Blank page
DEF-102 Cart retains Cart > Set High P2 Open
item when qty qty=0 >
set to 0 Update →
Item remains
DEF-103 Order tracking Orders > High P2 Open
shows Track > Status
Unknown = Unknown
status

PHASE 5 – TEST SUMMARY METRICS


Metric Value
Total Test Cases 10
Passed 7 (70%)
Failed 3 (30%)
Defects Found 3
Critical/P1 Defects 0
High/P2 Defects 2
Medium/P3 Defects 1
Test Completion 100%
Exit Criteria Met? No – 2 High defects open; fix required before
release

RESULT
A complete end-to-end testing workflow was successfully built and executed for [Link]. All 5
phases were completed: Test Plan defined, 10 test cases designed, tests executed (7 pass / 3 fail), 3
defects logged (0 Critical, 2 High, 1 Medium), and a test summary report with metrics was prepared.
Release is on hold pending resolution of 2 High-priority defects.
EXPERIMENT 8: Integrate Selenium Tests with TestNG and Generate Reports

AIM
To integrate Selenium WebDriver test automation with the TestNG framework (Java) and generate
detailed HTML and Extent Reports showing test execution results, pass/fail status, and screenshots.

ALGORITHM
1. Create Maven project with Selenium + TestNG + ExtentReports dependencies.
2. Write test classes annotated with TestNG annotations.
3. Create a TestNG listener class to hook into pass/fail events.
4. Configure [Link] with suite, tests, and listener.
5. Run tests via mvn test.
6. Open generated HTML report and ExtentReport in browser.

PROCEDURE
Step 1 – Add ExtentReports dependency to [Link]:
<dependency>
<groupId>[Link]</groupId>
<artifactId>extentreports</artifactId>
<version>5.1.1</version>
</dependency>

CODE
[Link] – Report Setup
import [Link].*;
import [Link];

public class ExtentManager {


private static ExtentReports extent;

public static ExtentReports getInstance() {


if (extent == null) {
ExtentSparkReporter spark = new
ExtentSparkReporter("reports/[Link]");
[Link]().setDocumentTitle("Selenium Test Report");
[Link]().setReportName("[Link] Automation Results");
extent = new ExtentReports();
[Link](spark);
[Link]("Tester", "QA Engineer");
[Link]("Browser", "Chrome");
[Link]("Environment", "Staging");
}
return extent;
}
}

[Link] – TestNG Listener


import [Link].*;
import [Link].*;
public class TestListener implements ITestListener {
ExtentReports extent = [Link]();
ExtentTest test;

@Override
public void onTestStart(ITestResult result) {
test = [Link]([Link]().getMethodName());
}

@Override
public void onTestSuccess(ITestResult result) {
[Link]("Test PASSED");
}

@Override
public void onTestFailure(ITestResult result) {
[Link]([Link]());
// Capture screenshot on failure
// TakesScreenshot ts = (TakesScreenshot) driver;
// String path = [Link](OutputType.BASE64);
// test.addScreenCaptureFromBase64String(path, "Failure Screenshot");
}

@Override
public void onFinish(ITestContext context) {
[Link](); // Write report to disk
}
}

[Link] – Test Class


import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];

@Listeners([Link])
public class AmazonTests {
WebDriver driver;
WebDriverWait wait;

@BeforeClass
public void setUp() {
[Link]().setup();
driver = new ChromeDriver();
[Link]().window().maximize();
wait = new WebDriverWait(driver, [Link](10));
}

@Test(groups = {"smoke"})
public void verifyTitle() {
[Link]("[Link]
[Link]([Link]().contains("Amazon"));
}

@Test(groups = {"functional"})
public void verifySearchFunctionality() {
[Link]("[Link]
WebElement search = [Link](

[Link]([Link]("twotabsearchtextbox")));
[Link]("smartphone");
[Link]();
[Link]([Link]().contains("smartphone"));
}

@Test(groups = {"functional"}, expectedExceptions = [Link])


public void verifyNonExistentElement() {
[Link]("[Link]
[Link]([Link]("nonExistentId")); // Should throw
}

@AfterClass
public void tearDown() {
if (driver != null) [Link]();
}
}

[Link] with Listener


<?xml version="1.0" encoding="UTF-8"?>
<suite name="ReportSuite">
<listeners>
<listener class-name="TestListener"/>
</listeners>
<test name="AmazonAutomation">
<groups>
<run><include name="smoke"/><include name="functional"/></run>
</groups>
<classes><class name="AmazonTests"/></classes>
</test>
</suite>

Reports generated:
• TestNG Native: target/surefire-reports/[Link]
• ExtentReport: reports/[Link] (with pass/fail charts, system info, screenshots)

REPORT FEATURES
Feature TestNG HTML Report ExtentReport
Pass/Fail status Yes Yes
Pie chart summary No Yes
Screenshots on fail No Yes (with listener)
System info No Yes
Execution time Yes Yes
Filtering by status No Yes

RESULT
Selenium tests were successfully integrated with TestNG and ExtentReports. The TestListener
captured pass/fail events and generated a rich HTML report at reports/[Link] with pie
charts, test details, system information, and failure stack traces. The [Link] suite ran smoke and
functional groups with 2 passes and 1 expected exception test.
EXPERIMENT 9: Unit Testing Using JUnit for a Simple Calculator Application

AIM
To write a program demonstrating unit testing using the JUnit 5 framework for a simple Calculator
application, covering addition, subtraction, multiplication, division, and exception handling for division by
zero.

ALGORITHM
1. Create a Calculator class with methods: add, subtract, multiply, divide.
2. Add input validation (throw ArithmeticException for division by zero).
3. Create a JUnit test class with @Test methods for each calculator operation.
4. Use assertions: assertEquals, assertThrows, assertTrue, assertNotNull.
5. Add @BeforeEach to initialize Calculator before each test.
6. Run tests with Maven or IDE (IntelliJ/Eclipse).
7. View test results in the JUnit runner or Surefire report.

PROCEDURE
Step 1 – [Link] dependency:
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>

CODE
[Link] – Class Under Test
public class Calculator {

public double add(double a, double b) {


return a + b;
}

public double subtract(double a, double b) {


return a - b;
}

public double multiply(double a, double b) {


return a * b;
}

public double divide(double a, double b) {


if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed");
}
return a / b;
}

public double power(double base, int exp) {


return [Link](base, exp);
}

public double squareRoot(double a) {


if (a < 0) throw new IllegalArgumentException("Cannot find sqrt of negative
number");
return [Link](a);
}
}

[Link] – JUnit 5 Test Class


import [Link].*;
import static [Link].*;

class CalculatorTest {

Calculator calc;

@BeforeEach
void setUp() {
calc = new Calculator(); // Fresh instance before each test
}

// ── Addition Tests ────────────────────────────────────────────


@Test
@DisplayName("Add two positive numbers")
void testAddPositive() {
assertEquals(10.0, [Link](4, 6), "4 + 6 should equal 10");
}

@Test
@DisplayName("Add negative numbers")
void testAddNegative() {
assertEquals(-3.0, [Link](-5, 2), "-5 + 2 should equal -3");
}

@Test
@DisplayName("Add with zero")
void testAddZero() {
assertEquals(7.0, [Link](7, 0));
}

// ── Subtraction Tests ─────────────────────────────────────────


@Test
@DisplayName("Subtract positive numbers")
void testSubtract() {
assertEquals(5.0, [Link](10, 5));
}

@Test
@DisplayName("Subtract resulting in negative")
void testSubtractNegativeResult() {
assertEquals(-3.0, [Link](2, 5));
}

// ── Multiplication Tests ──────────────────────────────────────


@Test
@DisplayName("Multiply two numbers")
void testMultiply() {
assertEquals(20.0, [Link](4, 5));
}

@Test
@DisplayName("Multiply by zero")
void testMultiplyByZero() {
assertEquals(0.0, [Link](100, 0));
}

// ── Division Tests ────────────────────────────────────────────


@Test
@DisplayName("Divide valid numbers")
void testDivide() {
assertEquals(5.0, [Link](10, 2));
}

@Test
@DisplayName("Division by zero throws ArithmeticException")
void testDivideByZero() {
ArithmeticException ex = assertThrows(
[Link],
() -> [Link](10, 0),
"Expected ArithmeticException for division by zero"
);
assertTrue([Link]().contains("Division by zero"));
}

// ── Power and Square Root ─────────────────────────────────────


@Test
@DisplayName("Power: 2^10 = 1024")
void testPower() {
assertEquals(1024.0, [Link](2, 10));
}

@Test
@DisplayName("Square root of 25 = 5")
void testSqrt() {
assertEquals(5.0, [Link](25));
}

@Test
@DisplayName("Square root of negative throws IllegalArgumentException")
void testSqrtNegative() {
assertThrows([Link], () -> [Link](-9));
}

@AfterEach
void tearDown() {
calc = null;
}
}

Run Tests:
mvn test # Output in target/surefire-reports/

TEST RESULTS SUMMARY


Test Method Operation Input Expected Status
testAddPositive Addition 4+6 10.0 PASS
testAddNegative Addition -5 + 2 -3.0 PASS
testAddZero Addition 7+0 7.0 PASS
testSubtract Subtraction 10 - 5 5.0 PASS
testSubtractNegat Subtraction 2-5 -3.0 PASS
iveResult
testMultiply Multiplication 4×5 20.0 PASS
testMultiplyByZer Multiplication 100 × 0 0.0 PASS
o
testDivide Division 10 ÷ 2 5.0 PASS
testDivideByZero Exception 10 ÷ 0 ArithmeticExcepti PASS
on
testPower Power 2^10 1024.0 PASS
testSqrt Square Root √25 5.0 PASS
testSqrtNegative Exception √(-9) IllegalArgExceptio PASS
n

RESULT
Unit testing using JUnit 5 was successfully demonstrated for a Calculator application. 12 test cases
were written covering addition, subtraction, multiplication, division, power, square root, and exception
handling (division by zero, sqrt of negative). All 12 tests passed. The @BeforeEach lifecycle ensured
test isolation, and @DisplayName provided readable test names in the report.
EXPERIMENT 10: Automate Login Functionality Using Selenium WebDriver

AIM
To automate the complete login functionality of a web application ([Link]) using Selenium
WebDriver with Python, covering valid login, invalid login, empty fields, and password visibility toggle
scenarios.

ALGORITHM
1. Initialize Chrome WebDriver and maximize window.
2. Navigate to [Link] login page.
3. TC1 – Valid Login: Enter valid email and password → assert successful login.
4. TC2 – Invalid Password: Enter valid email, wrong password → assert error message.
5. TC3 – Empty Email: Submit without email → assert required field error.
6. TC4 – Empty Password: Enter email, skip password → assert error.
7. TC5 – Special Characters in Email: Enter malformed email → assert validation.
8. Print results for each test case.
9. Close browser.

PROCEDURE
Step 1 – Install dependencies:
pip install selenium webdriver-manager pytest pytest-html

Step 2 – Create Page Object for Login:

CODE
login_page.py – Page Object
from [Link] import By
from [Link] import WebDriverWait
from [Link] import expected_conditions as EC

class LoginPage:
URL = '[Link]
EMAIL = ([Link], 'ap_email')
CONTINUE = ([Link], 'continue')
PASSWORD = ([Link], 'ap_password')
SIGN_IN = ([Link], 'signInSubmit')
ERROR = ([Link], 'auth-error-message-box')
ALERT = (By.CSS_SELECTOR, '.a-alert-content')
GREETING = ([Link], 'nav-link-accountList-nav-line-1')

def __init__(self, driver):


[Link] = driver
[Link] = WebDriverWait(driver, 12)

def open(self):
[Link]([Link])

def _find(self, loc):


return [Link](EC.presence_of_element_located(loc))
def _click(self, loc):
[Link](EC.element_to_be_clickable(loc)).click()

def enter_email(self, email):


el = self._find([Link])
[Link]()
el.send_keys(email)

def click_continue(self):
self._click([Link])

def enter_password(self, password):


el = self._find([Link])
[Link]()
el.send_keys(password)

def click_signin(self):
self._click(self.SIGN_IN)

def get_error_text(self):
try:
return self._find([Link]).text
except:
try:
return self._find([Link]).text
except:
return ''

def is_logged_in(self):
try:
text = [Link](
EC.presence_of_element_located([Link])).text
return 'Hello' in text or 'Account' not in text
except:
return False

def login(self, email, password):


[Link]()
self.enter_email(email)
self.click_continue()
self.enter_password(password)
self.click_signin()

test_login.py – Test Cases


import pytest
from selenium import webdriver
from [Link] import Service
from webdriver_manager.chrome import ChromeDriverManager
from login_page import LoginPage

VALID_EMAIL = 'your_email@[Link]' # Replace


VALID_PASSWORD = 'your_password' # Replace
WRONG_PASSWORD = 'WrongPass@999'
BAD_EMAIL = 'notanemail@@'

@[Link](scope='function')
def driver():
opts = [Link]()
opts.add_argument('--start-maximized')
opts.add_argument('--disable-notifications')
drv = [Link](
service=Service(ChromeDriverManager().install()), options=opts)
yield drv
[Link]()

# ── TC1: Valid Login ──────────────────────────────────────────────


def test_valid_login(driver):
page = LoginPage(driver)
[Link](VALID_EMAIL, VALID_PASSWORD)
assert page.is_logged_in(), 'Expected successful login'
print('[PASS] TC1: Valid login successful')

# ── TC2: Invalid Password ────────────────────────────────────────


def test_invalid_password(driver):
page = LoginPage(driver)
[Link](VALID_EMAIL, WRONG_PASSWORD)
error = page.get_error_text()
assert error != '', 'Expected error message for wrong password'
print(f'[PASS] TC2: Error shown – {error[:50]}')

# ── TC3: Empty Email ────────────────────────────────────────────


def test_empty_email(driver):
page = LoginPage(driver)
[Link]()
page.enter_email('')
page.click_continue()
error = page.get_error_text()
assert error != '', 'Expected error for empty email'
print(f'[PASS] TC3: Empty email error shown')

# ── TC4: Empty Password ─────────────────────────────────────────


def test_empty_password(driver):
page = LoginPage(driver)
[Link]()
page.enter_email(VALID_EMAIL)
page.click_continue()
page.enter_password('')
page.click_signin()
error = page.get_error_text()
assert error != '', 'Expected error for empty password'
print(f'[PASS] TC4: Empty password error shown')

# ── TC5: Malformed Email ─────────────────────────────────────────


def test_malformed_email(driver):
page = LoginPage(driver)
[Link]()
page.enter_email(BAD_EMAIL)
page.click_continue()
error = page.get_error_text()
assert error != '', 'Expected validation error for bad email'
print(f'[PASS] TC5: Malformed email rejected')

Run Tests with HTML Report:


pytest test_login.py -v --html=reports/login_report.html --self-contained-html

TEST RESULTS
TC Scenario Input Expected Actual Status
TC1 Valid Login Correct email Login Dashboard PASS
+ password successful loaded
TC2 Invalid Correct email Error message Error PASS
Password + wrong pwd shown displayed
TC3 Empty Email Blank email Required field Error shown PASS
field error
TC4 Empty Valid email + Password Error shown PASS
Password blank pwd required error
TC5 Malformed 'notanemail@ Invalid email Error shown PASS
Email @' error

RESULT
Login functionality of [Link] was successfully automated using Selenium WebDriver with Python
and the Page Object Model. Five test scenarios were automated covering valid login, invalid
password, empty email, empty password, and malformed email inputs. All 5 test cases passed with
appropriate assertions. An HTML report was generated at reports/login_report.html.

You might also like