Wednesday, December 2, 2026

Python Programming -Unit III

24MCST21 Python Programming - Unit III
SUBJECT CODE: 24MCST21

PYTHON PROGRAMMING

School of Computer Science

UNIT – III

Modules, Packages and Classes

1. Modules in Python

Definition: A module is a Python file containing functions, variables and classes that can be reused in another Python program. A Python module has the .py extension.

Advantages of Modules

  • Code reusability.
  • Reduces code repetition.
  • Organizes large programs.
  • Easy maintenance and debugging.

Example: Creating a Module

Step 1: Create a file named calculator.py.

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

Step 2: Create another file named main.py.

import calculator

print(calculator.add(10, 20))
print(calculator.sub(20, 5))
Output:
30 15

2. Packages in Python

Definition: A package is a collection of related Python modules organized inside a directory. It helps organize large applications into smaller components.

Package Structure

MyProject/
│
├── main.py
│
└── college/
    ├── __init__.py
    ├── student.py
    └── teacher.py

student.py

def student_details():
    print("Student Name: Arun")

teacher.py

def teacher_details():
    print("Teacher Name: Kumar")

main.py

from college import student, teacher

student.student_details()
teacher.teacher_details()
Student Name: Arun Teacher Name: Kumar

Difference Between Module and Package

ModulePackage
A single Python file.A directory containing related modules.
Has .py extension.Usually contains __init__.py.
Organizes individual code.Organizes multiple modules.
Example: calculator.pyExample: college package

3. Standalone Programs

Definition: A standalone program is a Python program that can execute independently without being imported by another program.

Example

print("Welcome to Python Programming")

a = 10
b = 20

total = a + b

print("Total:", total)
Welcome to Python Programming Total: 30

This program can run directly using the Python interpreter.

4. Command Line Arguments

Definition: Command line arguments are values passed to a Python program during execution through the command prompt or terminal.

Python provides the sys.argv list to access command line arguments.

Example

import sys

print("Program Name:", sys.argv[0])
print("First Argument:", sys.argv[1])
print("Second Argument:", sys.argv[2])

Execution in Terminal

python main.py Arun 25
Program Name: main.py First Argument: Arun Second Argument: 25

Important Points

  • sys.argv[0] represents the program name.
  • sys.argv[1] represents the first argument.
  • sys.argv[2] represents the second argument.
  • Command line arguments are received as strings.

5. Modules and the Import Statement

The import statement is used to access functions, variables and classes from another module.

1. Import Complete Module

import math

print(math.sqrt(25))
5.0

2. Import Specific Function

from math import sqrt

print(sqrt(36))
6.0

3. Import with Alias

import math as m

print(m.factorial(5))
120

4. Import Multiple Functions

from math import sqrt, pow

print(sqrt(49))
print(pow(2, 3))
7.0 8.0

6. Python Standard Library

Definition: The Python Standard Library is a collection of ready-made modules that provide functions for performing different programming tasks.
ModulePurpose
mathMathematical operations
randomGenerate random numbers
datetimeWork with dates and time
osInteract with operating system
sysAccess system information
calendarDisplay calendar
statisticsStatistical calculations
jsonWork with JSON data

Example 1: Math Module

import math

print(math.sqrt(64))
print(math.factorial(5))
8.0 120

Example 2: Random Module

import random

number = random.randint(1, 10)

print("Random Number:", number)
Output changes each time the program runs.

Example 3: DateTime Module

import datetime

today = datetime.date.today()

print("Today's Date:", today)

7. Objects and Classes

What is a Class?

A class is a blueprint or template used to create objects. It defines the attributes and methods of an object.

What is an Object?

An object is an instance of a class. It represents a real-world entity with data and behaviour.

Real-World Example: Student

ConceptExample
ClassStudent
ObjectsArun, Priya, Kumar
AttributesName, Age, Department
MethodsDisplay Details, Calculate Marks

Define a Class with class

class Student:

    def display(self):
        print("Welcome to Python")

s1 = Student()

s1.display()
Welcome to Python

Explanation

  • class Student creates a class.
  • display() is a method.
  • self refers to the current object.
  • s1 = Student() creates an object.
  • s1.display() calls the method.

8. Inheritance

Definition: Inheritance is an object-oriented programming concept in which one class acquires the properties and methods of another class.
  • Parent Class: The class that provides properties.
  • Child Class: The class that receives properties.

Example

class Parent:

    def display(self):
        print("This is Parent Class")

class Child(Parent):
    pass

obj = Child()

obj.display()
This is Parent Class

Types of Inheritance

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

9. Override a Method

Method overriding occurs when a child class defines a method with the same name as a method in its parent class. The child class provides its own implementation.

Example

class Parent:

    def display(self):
        print("Parent Method")

class Child(Parent):

    def display(self):
        print("Child Method")

obj = Child()

obj.display()
Child Method

The child class overrides the display() method of the parent class.

10. Add a Method

A child class can have additional methods that are not available in its parent class.

Example

class Student:

    def display(self):
        print("Student Details")

class Result(Student):

    def calculate(self):
        print("Result Calculated")

obj = Result()

obj.display()
obj.calculate()
Student Details Result Calculated

11. Get Help from Parent with super()

The super() function is used to access methods and constructors of the parent class from the child class.

Example

class Parent:

    def display(self):
        print("Parent Class Method")

class Child(Parent):

    def display(self):
        super().display()
        print("Child Class Method")

obj = Child()

obj.display()
Parent Class Method Child Class Method

Explanation

  • super() accesses the parent class implementation.
  • super().display() calls the parent method.
  • The child class also executes its own method.

12. In Self Defense – Understanding self

self represents the current object of a class. It allows each object to access its own attributes and methods.

Example

class Student:

    def set_details(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print("Name:", self.name)
        print("Age:", self.age)

s1 = Student()

s1.set_details("Arun", 20)
s1.display()
Name: Arun Age: 20

Important Points

  • self refers to the current object.
  • It accesses instance variables.
  • It is written as the first parameter of instance methods.
  • Python automatically passes the object when an instance method is called.

13. Get and Set Attribute Values with Properties

Properties are used to access and modify object attributes in a controlled manner. Python provides the @property decorator to create getter and setter methods.
  • Getter: Retrieves an attribute value.
  • Setter: Changes an attribute value.

Example

class Student:

    def __init__(self):
        self._name = ""

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

s1 = Student()

s1.name = "Arun"

print(s1.name)
Arun

14. Name Mangling for Privacy

Name mangling is a technique used in Python to make direct access to certain class attributes more difficult. It is performed by adding two underscores before an attribute name.

Example

class Student:

    def __init__(self):
        self.__marks = 90

    def display(self):
        print("Marks:", self.__marks)

s1 = Student()

s1.display()
Marks: 90
Important: Name mangling does not provide complete security or true private access. It mainly helps avoid accidental access and naming conflicts. Internally, __marks is stored using a name similar to _Student__marks.

15. Method Types

Python classes support three major method types.

1. Instance Method

An instance method works with individual object data and uses self.

class Student:

    def display(self):
        print("Instance Method")

s = Student()
s.display()
Instance Method

2. Class Method

A class method works with class-level data and uses cls. It is defined using @classmethod.

class Student:

    college = "NSCAS"

    @classmethod
    def display(cls):
        print(cls.college)

Student.display()
NSCAS

3. Static Method

A static method does not require self or cls. It is defined using @staticmethod.

class Calculator:

    @staticmethod
    def add(a, b):
        print(a + b)

Calculator.add(10, 20)
30

Comparison of Method Types

Instance MethodClass MethodStatic Method
Uses selfUses clsNo self or cls
Works with object dataWorks with class dataGeneral utility
No decorator required@classmethod@staticmethod

16. Duck Typing

Duck typing is a programming concept in which the type or class of an object is less important than the methods or behaviour it supports.

Principle: If it behaves like a duck, it can be treated like a duck.

Example

class Dog:

    def sound(self):
        print("Dog Barks")

class Cat:

    def sound(self):
        print("Cat Meows")

def make_sound(animal):
    animal.sound()

d = Dog()
c = Cat()

make_sound(d)
make_sound(c)
Dog Barks Cat Meows

The make_sound() function works with both Dog and Cat objects because both provide the sound() method.

17. Special Methods

Special methods are predefined methods in Python that begin and end with double underscores. They are also called Magic Methods or Dunder Methods.

Important Special Methods

MethodPurpose
__init__()Initializes an object
__str__()Returns a readable string
__len__()Returns object length
__add__()Defines addition
__eq__()Defines equality comparison
__del__()Called when an object is finalized

Example: __init__() and __str__()

class Student:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

s1 = Student("Arun")

print(s1)
Arun
  • __init__() initializes the object.
  • __str__() defines the readable string representation.
  • print(s1) automatically calls __str__().

18. Composition

Composition is an object-oriented programming concept in which one class contains an object of another class. It represents a "Has-A" relationship.

Real-World Examples

  • A coll

SOFTWARE TESTING AND AUTOMATION LAB

Software Testing and Automation Lab - Practical Manual

SOFTWARE TESTING AND AUTOMATION LAB

Practical Laboratory Manual

Manual Testing | Selenium WebDriver | JUnit

15 Lab Exercises

LAB EXERCISES

  1. Identify Testing Types for a Sample Application
  2. Write Test Cases for a Login Page
  3. Design Test Scenarios for a Web Form
  4. Perform Manual Testing and Record Defects
  5. Install Selenium and Configure Environment
  6. Launch Browser Using Selenium WebDriver
  7. Locate Web Elements Using Different Locators
  8. Perform Actions (Click, Send Keys, Submit)
  9. Automate Form Filling Using Selenium
  10. Handle Alerts and Pop-ups
  11. Implement Wait Conditions in Selenium
  12. Write JUnit Test Cases
  13. Use Assertions in JUnit
  14. Execute Test Suite Using JUnit
  15. Integrate Selenium with JUnit and Run Automation Tests

STEP 1: SOFTWARE INSTALLATION AND ENVIRONMENT SETUP

Before performing the laboratory exercises, install and configure the required software. Visual Studio Code (VS Code) will be used to write and execute Java programs with Selenium WebDriver and JUnit.

1. Install Java Development Kit (JDK)

Step 1: Open the official Java website.

Download Java JDK

Step 2: Select the Windows installer according to your computer (64-bit installer for most modern Windows systems). Step 3: Download the installer and open it. Step 4: Follow the installation instructions and complete the setup. Step 5: Open Command Prompt. Step 6: Type the following commands:
java -version
javac -version
Step 7: Verify that Java version information is displayed.
Expected Result: Java JDK is successfully installed and configured.

2. Install Visual Studio Code

Step 1: Visit the official Visual Studio Code website.

Download Visual Studio Code

Step 2: Click Download for Windows. Step 3: Open the downloaded installer. Step 4: Accept the license agreement. Step 5: Select the following options if available:
  • Add to PATH
  • Add Open with Code action
  • Create a desktop icon
  • Register Code as an editor
Step 6: Click Install. Step 7: After installation, open Visual Studio Code.

3. Install Java Extensions in VS Code

Step 1: Open Visual Studio Code. Step 2: Click the Extensions icon on the left sidebar. Step 3: Search for:
Extension Pack for Java
Step 4: Select the Microsoft Extension Pack for Java. Step 5: Click Install. Step 6: Search for Maven for Java and install it. Step 7: Restart VS Code if required.

Important Extensions:

ExtensionPurpose
Extension Pack for JavaJava development and execution
Maven for JavaProject and dependency management
Debugger for JavaDebug Java programs
Test Runner for JavaRun JUnit test cases

4. Install Apache Maven

Maven is used to download and manage Selenium and JUnit libraries automatically.

Step 1: Open the official website.

Download Apache Maven

Step 2: Download the Binary zip archive. Step 3: Extract the downloaded ZIP file to a folder, for example:
C:\apache-maven
Step 4: Configure the system environment variables.
  • Create MAVEN_HOME pointing to the extracted Maven folder.
  • Add %MAVEN_HOME%\bin to the system PATH.
Step 5: Open a new Command Prompt. Step 6: Enter:
mvn -version
Step 7: Verify the Maven version information.
If Maven is already available through VS Code or another installation, verify it using mvn -version before installing it again.

5. Install Google Chrome

Step 1: Open the official Chrome website.

Download Google Chrome

Step 2: Download and install Google Chrome. Step 3: Open the browser and verify that it works.
Note: Selenium 4 includes Selenium Manager. It can automatically manage compatible browser drivers in normal supported configurations. Manual ChromeDriver installation is generally not required.

6. Create a Selenium Maven Project in VS Code

Step 1: Open VS Code. Step 2: Press Ctrl + Shift + P. Step 3: Search for:
Java: Create Java Project
Step 4: Select Maven. Step 5: Select Maven Archetype Quickstart or an available Maven project template. Step 6: Enter the project name:
SoftwareTestingLab
Step 7: Select a folder to save the project. Step 8: Wait until Maven finishes creating the project. Step 9: Open the project folder in VS Code.

7. Configure Selenium and JUnit Dependencies

Open the pom.xml file in the project folder. Add the following dependencies inside the dependencies section.

<dependencies>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.27.0</version>
    </dependency>

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.11.4</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-suite</artifactId>
        <version>1.11.4</version>
        <scope>test</scope>
    </dependency>

</dependencies>

<build>
    <plugins>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.5.2</version>
        </plugin>

    </plugins>
</build>

Also ensure the project uses Java 17 or a compatible newer JDK. If necessary, add the following inside the pom.xml project element:

<properties>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Step 1: Save pom.xml. Step 2: Wait for VS Code to download the required libraries. Step 3: If required, open the terminal using:
Terminal → New Terminal
Step 4: Enter:
mvn clean install
Step 5: Wait until the BUILD SUCCESS message appears.

8. How to Write and Run Java Programs in VS Code

Step 1: Open the project folder. Step 2: Locate:
src/main/java
Step 3: Right-click and create a new Java file. Step 4: Give the file a name, for example:
BrowserLaunch.java
Step 5: Type the Java program. Step 6: Save using Ctrl + S. Step 7: Click the Run button above the main method. Step 8: Observe the output in the VS Code terminal.

9. How to Run JUnit Test Cases in VS Code

Step 1: Save the test file under:
src/test/java
Step 2: Use the @Test annotation. Step 3: Save the file. Step 4: Click Run Test displayed above the test method, if available. Step 5: Alternatively, execute the following command in the terminal:
mvn test
Step 6: Check the test results in the terminal or Testing panel.
Successful Installation: The environment is ready when Java, Maven, Selenium and JUnit are configured and a simple browser automation program executes successfully.

STEP 2: LABORATORY EXERCISES

LAB EXERCISE 1: Identify Testing Types for a Sample Application

Aim

To identify different types of software testing using a sample application.

Requirements

  • Computer system
  • Internet browser
  • Sample online shopping application

Procedure

  1. Select an online shopping application.
  2. Identify its major functionalities.
  3. Study different software testing types.
  4. Match each testing type with the appropriate application functionality.
  5. Record the testing types and their purposes.

Testing Types

Testing TypeDescriptionExample
Unit TestingTests individual components.Testing login function.
Integration TestingTests combined modules.Payment gateway integration.
System TestingTests the complete application.Complete shopping process.
Acceptance TestingChecks user requirements.Customer order completion.
Functional TestingChecks application functionality.Add to Cart button.
Performance TestingChecks application speed.Multiple users accessing website.
Security TestingChecks security vulnerabilities.Password protection.
Usability TestingChecks user-friendliness.Easy website navigation.

Expected Output

A list of software testing types with suitable examples for the selected application.

Result: Different software testing types were identified successfully.
LAB EXERCISE 2: Write Test Cases for a Login Page

Aim

To prepare and execute test cases for validating a login page.

Procedure

  1. Open a sample login page.
  2. Identify the username and password fields.
  3. Prepare positive and negative test cases.
  4. Enter different input values.
  5. Compare expected and actual results.
  6. Record the results.

Test Cases

IDTest ScenarioInputExpected Result
TC01Valid loginCorrect username and passwordLogin successful
TC02Invalid passwordCorrect username, wrong passwordError message
TC03Invalid usernameWrong usernameError message
TC04Empty fieldsNo inputValidation message
TC05Password maskingEnter passwordPassword hidden
TC06Forgot passwordClick forgot passwordPassword reset page

Expected Output

Login test cases with expected results.

Result: Test cases for the login page were prepared successfully.
LAB EXERCISE 3: Design Test Scenarios for a Web Form

Aim

To design test scenarios for validating a registration form.

Procedure

  1. Open a registration form.
  2. Identify the input fields.
  3. Prepare different test scenarios.
  4. Check mandatory field validation.
  5. Verify the email and mobile number formats.
  6. Check form submission.

Sample Test Scenarios

IDTest ScenarioExpected Result
TS01Enter valid nameName accepted
TS02Enter invalid emailValidation error
TS03Enter valid mobile numberNumber accepted
TS04Leave mandatory fields emptyError displayed
TS05Enter weak passwordPassword validation message
TS06Submit valid informationRegistration successful

Expected Output

Test scenarios for a registration form.

Result: Test scenarios were designed successfully.
LAB EXERCISE 4: Perform Manual Testing and Record Defects

Aim

To perform manual testing and identify defects in a sample web application.

Procedure

  1. Select a sample web application.
  2. Prepare test cases.
  3. Execute each test case manually.
  4. Compare actual results with expected results.
  5. Identify application defects.
  6. Prepare a defect report.

Sample Defect Report

Defect IDDescriptionSeverityStatus
BUG01Login accepts empty passwordHighOpen
BUG02Submit button not respondingMediumOpen
BUG03Error message not displayedLowOpen

Expected Output

Manual testing report containing identified defects.

Result: Manual testing was performed and defects were recorded successfully.
LAB EXERCISE 5: Install Selenium and Configure Environment

Aim

To install Selenium WebDriver and configure the automation testing environment using VS Code.

Requirements

  • Java JDK
  • Visual Studio Code
  • Google Chrome
  • Apache Maven
  • Selenium WebDriver
  • JUnit 5

Procedure

  1. Install Java JDK.
  2. Verify Java using java -version.
  3. Install Visual Studio Code.
  4. Install the Extension Pack for Java.
  5. Install Maven for Java.
  6. Install Apache Maven and configure PATH.
  7. Create a Maven project.
  8. Add Selenium and JUnit dependencies in pom.xml.
  9. Execute mvn clean install.
  10. Verify successful dependency installation.

Maven Dependency

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.27.0</version>
</dependency>

Verification Command

java -version
mvn -version
mvn clean install

Expected Output

Java, Maven and Selenium environment configured successfully.

Result: Selenium WebDriver environment was installed and configured successfully.
LAB EXERCISE 6: Launch Browser Using Selenium WebDriver

Aim

To launch a web browser using Selenium WebDriver.

Procedure

  1. Open VS Code.
  2. Open the Maven project.
  3. Create BrowserLaunch.java inside src/main/java.
  4. Import Selenium packages.
  5. Create a ChromeDriver object.
  6. Open Google using get().
  7. Display the page title.
  8. Close the browser.

Program

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserLaunch {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.google.com");

        System.out.println(
            "Title: " + driver.getTitle()
        );

        driver.quit();
    }
}

Execution

Save the file and click Run above the main method.

Expected Output

Title: Google

Chrome browser opens successfully.
Result: Browser was launched successfully using Selenium WebDriver.
LAB EXERCISE 7: Locate Web Elements Using Different Locators

Aim

To locate web elements using different Selenium WebDriver locators.

Types of Locators

LocatorPurposeExample
IDFind using element IDBy.id("username")
NameFind using nameBy.name("q")
Class NameFind using CSS classBy.className("search")
Tag NameFind using HTML tagBy.tagName("input")
Link TextFind complete link textBy.linkText("Login")
Partial Link TextFind partial link textBy.partialLinkText("Log")
CSS SelectorFind using CSS selectorBy.cssSelector("#username")
XPathFind using XPathBy.xpath("//input[@id='username']")

Program

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class LocatorsDemo {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.google.com");

        WebElement search =
            driver.findElement(By.name("q"));

        search.sendKeys("Software Testing");

        search.submit();

        driver.quit();
    }
}

Expected Output

Google search results for Software Testing are displayed.

Result: Web elements were located successfully using Selenium locators.
LAB EXERCISE 8: Perform Actions (Click, Send Keys, Submit)

Aim

To perform basic web element actions using Selenium WebDriver.

Important Methods

MethodPurpose
click()Clicks an element.
sendKeys()Enters text into a field.
submit()Submits a form.
clear()Clears an input field.

Program

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class ActionsDemo {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.google.com");

        WebElement search =
            driver.findElement(By.name("q"));

        search.sendKeys("Selenium Automation");

        search.submit();

        System.out.println(driver.getTitle());

        driver.quit();
    }
}

Expected Output

The browser searches for Selenium Automation and displays the search results.

Result: Click, sendKeys and submit actions were performed successfully.
LAB EXERCISE 9: Automate Form Filling Using Selenium

Aim

To automate filling and submitting a registration form using Selenium WebDriver.

Procedure

  1. Create a sample HTML registration form.
  2. Identify the form fields using ID attributes.
  3. Open the form using Selenium.
  4. Enter name, email and password.
  5. Click the Register button.
  6. Verify the successful submission message.

HTML Form

<!DOCTYPE html>
<html>
<body>

<h2>Registration Form</h2>

<form id="registerForm">

Name:
<input type="text" id="name" required>
<br><br>

Email:
<input type="email" id="email" required>
<br><br>

Password:
<input type="password"
id="password" required>
<br><br>

<button type="submit">Register</button>

</form>

<p id="message"></p>

<script>
document.getElementById("registerForm")
.addEventListener("submit", function(e) {
    e.preventDefault();
    document.getElementById("message")
    .innerText = "Registration Successful";
});
</script>

</body>
</html>

Save the File

Save the above code as:

form.html

Place it inside:

src/test/resources/form.html

Selenium Program

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.nio.file.Paths;

public class FormAutomation {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {

            String filePath = Paths.get(
                "src/test/resources/form.html"
            ).toAbsolutePath().toUri().toString();

            driver.get(filePath);

            driver.findElement(By.id("name"))
                  .sendKeys("Student");

            driver.findElement(By.id("email"))
                  .sendKeys("test@gmail.com");

            driver.findElement(By.id("password"))
                  .sendKeys("Test123");

            driver.findElement(
                By.cssSelector("button[type='submit']")
            ).click();

            String message = driver.findElement(
                By.id("message")
            ).getText();

            System.out.println(message);

        } finally {
            driver.quit();
        }
    }
}

Expected Output

Registration Successful
Result: Registration form fields were automatically filled and submitted successfully.
LAB EXERCISE 10: Handle Alerts and Pop-ups

Aim

To handle JavaScript alerts using Selenium WebDriver.

Types of Alerts

  • Simple Alert
  • Confirmation Alert
  • Prompt Alert

Alert Methods

MethodPurpose
accept()Clicks OK.
dismiss()Clicks Cancel.
getText()Reads the alert message.
sendKeys()Enters text in a prompt.

HTML Alert Page

<html>
<body>

<button id="alertBtn"
onclick="alert('Welcome to Selenium Testing')">
Show Alert
</button>

</body>
</html>

Save as alert.html inside src/test/resources.

Java Program

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.nio.file.Paths;

public class AlertDemo {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {

            String path = Paths.get(
                "src/test/resources/alert.html"
            ).toAbsolutePath().toUri().toString();

            driver.get(path);

            driver.findElement(By.id("alertBtn")).click();

            Alert alert = driver.switchTo().alert();

            System.out.println(alert.getText());

            alert.accept();

        } finally {
            driver.quit();
        }
    }
}

Expected Output

Welcome to Selenium Testing
Result: JavaScript alerts were handled successfully.
LAB EXERCISE 11: Implement Wait Conditions in Selenium

Aim

To implement different wait conditions for handling dynamic web elements.

Types of Waits

Wait TypeDescription
Implicit WaitWaits for elements while searching for them.
Explicit WaitWaits for a specific condition.
Fluent WaitWaits with configurable polling intervals and ignored exceptions.

Program – Explicit Wait

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;

import java.time.Duration;

public class WaitDemo {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {

            driver.get("https://www.google.com");

            WebDriverWait wait =
                new WebDriverWait(
                    driver,
                    Duration.ofSeconds(10)
                );

            WebElement search = wait.until(
                ExpectedConditions
                .visibilityOfElementLocated(
                    By.name("q")
                )
            );

            search.sendKeys("Software Testing");

            search.submit();

            System.out.println("Search Completed");

        } finally {
            driver.quit();
        }
    }
}

Expected Output

Search Completed
Result: Explicit wait was implemented successfully.
LAB EXERCISE 12: Write JUnit Test Cases

Aim

To create and execute test cases using the JUnit 5 framework.

Important JUnit Annotation

AnnotationPurpose
@TestIdentifies a test method.
@BeforeEachExecutes before each test.
@AfterEachExecutes after each test.
@BeforeAllExecutes once before all tests.
@AfterAllExecutes once after all tests.

Program

Save this file inside src/test/java.

import org.junit.jupiter.api.Test;

public class SampleTest {

    @Test
    public void testLogin() {

        System.out.println(
            "Testing Login Function"
        );

    }

    @Test
    public void testRegistration() {

        System.out.println(
            "Testing Registration Function"
        );

    }
}

Execution

mvn test

Expected Output

JUnit executes both test methods successfully.

Result: JUnit test cases were created and executed successfully.
LAB EXERCISE 13: Use Assertions in JUnit

Aim

To validate actual results against expected results using JUnit assertions.

Types of Assertions

AssertionPurpose
assertEquals()Compares two values.
assertNotEquals()Checks unequal values.
assertTrue()Checks whether a condition is true.
assertFalse()Checks whether a condition is false.
assertNull()Checks for null.
assertNotNull()Checks for non-null.

Program

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class AssertionDemo {

    @Test
    public void testAddition() {

        int a = 10;
        int b = 20;

        int result = a + b;

        assertEquals(30, result);

    }

    @Test
    public void testCondition() {

        assertTrue(10 > 5);

    }

    @Test
    public void testString() {

        String name = "Selenium";

        assertNotNull(name);

    }
}

Expected Output

All three test methods pass when their conditions are satisfied.

Result: JUnit assertions were implemented successfully.
LAB EXERCISE 14: Execute Test Suite Using JUnit

Aim

To execute multiple test classes using a JUnit test suite.

Procedure

  1. Create separate JUnit test files.
  2. Write test methods in each file.
  3. Create a test suite file.
  4. Use @Suite annotation.
  5. Use @SelectClasses to select the test files.
  6. Run the test suite using Maven.

First Test File – LoginTest.java

import org.junit.jupiter.api.Test;

public class LoginTest {

    @Test
    public void testLogin() {

        System.out.println("Login Test Passed");

    }
}

Second Test File – RegistrationTest.java

import org.junit.jupiter.api.Test;

public class RegistrationTest {

    @Test
    public void testRegistration() {

        System.out.println(
            "Registration Test Passed"
        );

    }
}

Test Suite – TestSuiteDemo.java

import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

@Suite
@SelectClasses({
    LoginTest.class,
    RegistrationTest.class
})
public class TestSuiteDemo {
}

Execution

mvn test
Place all three files inside src/test/java. The Maven Surefire plugin discovers the suite using its standard test naming patterns. Alternatively, run the suite directly using VS Code's Run Test option.

Expected Output

Login Test Passed
Registration Test Passed

Tests run: 2
Failures: 0
Result: Multiple JUnit test cases were executed through a single test suite successfully.
LAB EXERCISE 15: Integrate Selenium with JUnit and Run Automation Tests

Aim

To integrate Selenium WebDriver with JUnit and execute automated browser testing.

Procedure

  1. Create a Maven project.
  2. Configure Selenium and JUnit dependencies.
  3. Create a JUnit test file inside src/test/java.
  4. Initialize the browser before each test.
  5. Write test methods using @Test.
  6. Use assertions to verify expected results.
  7. Close the browser after each test.
  8. Execute tests using Maven.

Program

import org.junit.jupiter.api.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import static org.junit.jupiter.api.Assertions.*;

public class SeleniumJUnitTest {

    WebDriver driver;

    @BeforeEach
    public void setUp() {

        driver = new ChromeDriver();

        driver.get("https://www.google.com");
    }

    @Test
    public void testPageTitle() {

        String title = driver.getTitle();

        assertTrue(title.contains("Google"));

    }

    @Test
    public void testSearch() {

        WebElement search =
            driver.findElement(By.name("q"));

        search.sendKeys("Selenium");

        search.submit();

        assertTrue(
            driver.getTitle().contains("Selenium")
        );

    }

    @AfterEach
    public void tearDown() {

        if (driver != null) {
            driver.quit();
        }

    }
}

Execution

Save the file as SeleniumJUnitTest.java inside src/test/java.

Open the VS Code terminal and execute:

mvn test

Expected Output

Tests run: 2
Failures: 0
Errors: 0

BUILD SUCCESS
Result: Selenium WebDriver was integrated with JUnit and automated browser test cases were executed successfully.

STEP 3: IMPORTANT PROJECT STRUCTURE

The following is the recommended Maven project folder structure for completing all the practical exercises.

SoftwareTestingLab/
│
├── pom.xml
│
└── src/
    │
    ├── main/
    │   └── java/
    │       ├── BrowserLaunch.java
    │       ├── LocatorsDemo.java
    │       ├── ActionsDemo.java
    │       ├── FormAutomation.java
    │       ├── AlertDemo.java
    │       └── WaitDemo.java
    │
    └── test/
        │
        ├── java/
        │   ├── SampleTest.java
        │   ├── AssertionDemo.java
        │   ├── LoginTest.java
        │   ├── RegistrationTest.java
        │   ├── TestSuiteDemo.java
        │   └── SeleniumJUnitTest.java
        │
        └── resources/
            ├── form.html
            └── alert.html

STEP 4: COMMON EXECUTION COMMANDS

CommandPurpose
java -versionCheck Java installation
javac -versionCheck Java compiler
mvn -versionCheck Maven installation
mvn cleanClean previous build files
mvn compileCompile main source files
mvn testExecute JUnit tests
mvn clean installBuild the complete project

STEP 5: TROUBLESHOOTING

ProblemSolution
Java not recognizedCheck JDK installation and PATH.
Maven not recognizedConfigure MAVEN_HOME and PATH.
Package not foundCheck pom.xml dependencies and reload Maven.
ChromeDriver errorCheck Chrome installation and Selenium Manager access.
JUnit test not runningCheck JUnit dependency and test file location.
Element not foundVerify the locator and use suitable wait conditions.
Browser closes immediatelyCheck program execution and browser quit statements.

CONCLUSION

Through these 15 laboratory exercises, students gain practical knowledge of software testing techniques, test case preparation, manual testing, defect identification, Selenium WebDriver automation, web element interaction, wait conditions, JUnit testing, assertions and automated test suite execution.

Python Programming -Unit III

24MCST21 Python Programming - Unit III SUBJECT CODE: 24MCST21 PYTHON PROGRAMMING School of Computer Science ...