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.

Monday, November 30, 2026

Unit-II

Python: Iteration to Exceptions - Lecture 7 | Control, Abstraction, and Robustness
Lecture 7 • Python Course • Assistant Professor

Python: Iteration to Exceptions

Control, Abstraction, and Robustness. Iterate with intention, package behaviour in functions, generate lazily, wrap carefully, know where your names live, and let errors speak in the language of your problem.

1. Iterate with for

A for loop in Python is not a counter. It is an iterator protocol. It asks an object: "Give me your next item," until there is none left.

fruits = ["apple", "mango", "banana"]
for fruit in fruits:
    print(fruit)

Internally: iter(fruits) → repeatedly next(iterator) → StopIteration ends the loop.

marks = {"Anitha": 92, "Kumar": 78, "Priya": 85}
for name, mark in marks.items():
    print(f"{name} scored {mark}")

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
Professor's Note: If you write for i in range(len(list)), stop. Use for item in list or for i, item in enumerate(list).

2. Comprehensions

A comprehension is a for loop compressed into an expression that builds a new collection.

numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
even_squares = [n * n for n in numbers if n % 2 == 0]
name_lengths = {fruit: len(fruit) for fruit in fruits}
first_letters = {fruit[0] for fruit in fruits}

Structure: [expression for variable in iterable if condition]

Do NOT use comprehensions only for side effects: [print(x) for x in numbers] is bad style. Use a normal loop for actions, comprehension for building values.

3. Functions

def greet(name, greeting="Vanakkam"):
    """Return a greeting message."""
    return f"{greeting}, {name}!"

print(greet("Anitha"))
print(greet("Kumar", greeting="Hello"))

def total(*numbers):
    return sum(numbers)

def show_profile(**details):
    for key, value in details.items():
        print(key, ":", value)

def min_max(data):
    return min(data), max(data)

low, high = min_max([10, 20, 5, 30])

Parameters are in the definition. Arguments are in the call. Never use a mutable default like def f(x=[]).

4. Generators

A normal function computes everything at once. A generator computes one item at a time with yield. It is lazy.

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

squares_gen = (x*x for x in range(10000000))
print(next(squares_gen))  # 0
Classic Exam Question: Fibonacci Generator
def fibonacci(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

for num in fibonacci(20):
    print(num, end=" ")

Note: (x*x for x in ...) is a generator expression. [x*x for x in ...] is a list comprehension.

5. Decorators

A decorator takes a function and returns a new, enhanced function. @timer is shorthand for func = timer(func).

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.4f} seconds")
        return result
    return wrapper

@timer
def slow_work():
    time.sleep(1)
    return "Done"

print(slow_work())

6. Namespaces and Scope

Python follows LEGB: Local → Enclosing → Global → Built-in.

x = 100  # Global
def outer():
    x = 50  # Enclosing
    def inner():
        x = 10  # Local
        print(x)  # 10
    inner()
    print(x)  # 50
outer()
print(x)  # 100
count = 0
def increment():
    global count
    count += 1

def counter():
    count = 0
    def inc():
        nonlocal count
        count += 1
        return count
    return inc

c = counter()
print(c())  # 1
print(c())  # 2

7. Handle Errors with try and except

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print("Result:", result)
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("No error occurred.")
finally:
    print("This always runs, for cleanup.")

Catch specific exceptions, not bare except:. A bare except hides bugs.

8. User Exceptions

Define your own by inheriting from Exception when your domain has a specific error.

class InvalidMarksError(Exception):
    """Raised when marks are outside 0 to 100."""
    pass

def set_marks(marks):
    if not 0 <= marks <= 100:
        raise InvalidMarksError(f"Marks {marks} are invalid. Must be 0 to 100.")
    return f"Marks accepted: {marks}"

try:
    print(set_marks(120))
except InvalidMarksError as e:
    print("Error:", e)
class InsufficientBalanceError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Need {amount}, but balance is only {balance}")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalanceError(balance, amount)
    return balance - amount

9. Putting It All Together

class InvalidAgeError(Exception):
    pass

def get_eligible_students(students):
    def check_age(student):
        name, age = student
        if age < 0:
            raise InvalidAgeError(f"Age cannot be negative for {name}")
        return age >= 18

    for student in students:
        try:
            if check_age(student):
                yield student[0]
        except InvalidAgeError as e:
            print("Skipping:", e)

students = [("Anitha", 20), ("Kumar", 17), ("Priya", -5), ("Ravi", 19)]
print(list(get_eligible_students(students)))

Assignment for Next Class

Write a decorator @validate_marks that checks if a function's argument is between 0 and 100, and raises InvalidMarksError if not.

@validate_marks
def record_score(name, mark):
    return f"{name}: {mark}"

print(record_score("Anitha", 92))  # Anitha: 92
# record_score("Kumar", 140)  # should raise InvalidMarksError
Python: Iteration to Exceptions • Lecture 7 • Control, Abstraction, and Robustness

Decision Tree

Decision Tree - Working and Building
MACHINE LEARNING | STUDY NOTES

Decision Tree

Working of Decision Tree & Building a Decision Tree

Simple Concepts • Real-World Examples • Easy Learning

1. Introduction to Decision Tree

A Decision Tree is a supervised machine learning algorithm used for classification and prediction. It represents decisions in the form of a tree-like structure.

Simple Definition:
A Decision Tree is a flowchart-like model that makes decisions by checking conditions step by step until it reaches a final result.

Real-World Example

A college wants to predict whether a student will pass or fail based on attendance and internal marks.

  • Check student attendance.
  • Check internal examination marks.
  • Predict the final result.

2. Working of a Decision Tree

A Decision Tree starts with the complete dataset and divides it into smaller groups based on selected conditions. It continues this process until a final prediction is obtained.

Steps Involved in Working

1
Start with Dataset

Collect training data containing input attributes and output labels.

2
Select the Best Attribute

Identify the most useful attribute for dividing the dataset.

3
Split the Dataset

Divide the records into smaller groups based on a condition.

4
Repeat the Process

Continue splitting the groups until a suitable final decision is reached.

5
Generate Prediction

Reach a leaf node to obtain the final output.

3. Components of Decision Tree

🌳

Root Node

The starting point containing the complete dataset.

🔷

Decision Node

Represents a condition or attribute test.

➡️

Branch

Represents the outcome of a condition.

🍃

Leaf Node

Represents the final prediction or result.

4. Building a Decision Tree

Building a Decision Tree means creating a tree structure using training data to make predictions for new data.

1
Collect Training Dataset

Gather the required data with input attributes and target values.

2
Identify Attributes

Separate input features and the target variable.

3
Select Root Node

Choose the best attribute using Information Gain, Entropy or Gini Index.

4
Divide the Dataset

Split records into groups according to the selected condition.

5
Create Child Nodes

Create additional decision nodes for groups that need further splitting.

6
Repeat Splitting

Continue until a stopping condition is satisfied.

7
Create Leaf Nodes

Assign the final class or predicted value.

8
Pruning

Remove unnecessary branches to reduce complexity and overfitting.

5. Methods for Selecting Attributes

1. Entropy

Entropy measures the impurity or uncertainty in a dataset. Lower entropy indicates more homogeneous data.

Entropy(S) = - Σ p(i) log₂ p(i)

2. Information Gain

Information Gain measures how much uncertainty is reduced after splitting a dataset using an attribute.

Information Gain = Parent Entropy − Weighted Child Entropy
Remember: The attribute with the highest Information Gain is generally selected for splitting.

3. Gini Index

Gini Index measures the impurity of a dataset. A lower Gini value indicates a purer group.

Gini(S) = 1 − Σ p(i)²

4. Gain Ratio

Gain Ratio adjusts Information Gain using Split Information. It helps reduce the bias towards attributes having many values.

Gain Ratio = Information Gain / Split Information

6. Example: Student Pass or Fail Prediction

Consider a college predicting student results using attendance and internal marks.

Student Attendance Internal Mark Result
A90%80Pass
B60%30Fail
C85%70Pass
D50%25Fail
E80%45Pass

Decision Tree Diagram

Attendance ≥ 75%?
YES
↓
PASS
NO
↓
Internal Mark ≥ 40?
YES
↓
PASS
NO
↓
FAIL
Note: This is a simplified teaching example. Actual examination eligibility and pass rules depend on institutional regulations.

7. Advantages of Decision Tree

  • Easy to understand and interpret.
  • Simple to construct and visualize.
  • Handles numerical and categorical data.
  • Useful for classification and prediction.
  • Requires less data preparation.

8. Disadvantages of Decision Tree

  • Large trees can become difficult to understand.
  • Small changes in data may create a different tree.
  • Overfitting may occur.
  • Pruning may be required.

9. Applications

🎓

Education

Student performance prediction

🏦

Banking

Loan approval prediction

🏥

Healthcare

Disease classification

🛒

Marketing

Customer behaviour analysis

10. Quick Revision

TermMeaning
Decision TreeTree-based prediction algorithm
Root NodeStarting point
Decision NodePerforms a condition test
BranchOutcome of a condition
Leaf NodeFinal prediction
EntropyMeasures impurity
Information GainReduction in uncertainty
PruningRemoval of unnecessary branches

11. Test Your Knowledge

Choose the correct answer for each question.

Q1. What is the starting point of a Decision Tree?

Q2. Which method measures impurity?

Q3. What is the purpose of pruning?

12. Conclusion

A Decision Tree is a simple and powerful machine learning algorithm. It works by selecting the best attributes, splitting the dataset into smaller groups and generating final predictions through leaf nodes.

Classroom Activity:
Construct a Decision Tree for the question: "Should a person carry an umbrella?" Use weather conditions such as Sunny, Rainy and Cloudy.

Learning Machine Learning

Understand Concepts • Practice Examples • Build Knowledge

Educational Notes | Decision Tree

Sunday, November 29, 2026

Python programming (1-5 program)

React Artifact

Python Programming -Unit III

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