0% found this document useful (0 votes)
2 views22 pages

Python Unit7 Unit8 Advanced Examples

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Python Unit7 Unit8 Advanced Examples

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Unit-VII & Unit-VIII: Advanced

Examples & Code Snippets

PART 1: ADVANCED sys MODULE EXAMPLES

1. Building a Command-Line Argument Parser

import sys

class SimpleArgParser:
"""Simple command-line argument parser"""

def __init__(self):
[Link] = [Link][1:] # Skip script name
[Link] = {}

def parse(self):
"""Parse command-line arguments"""
i = 0
while i < len([Link]):
arg = [Link][i]

if [Link]('-'):
if '=' in arg:
# Format: --key=value
key, value = [Link]('=')
[Link][[Link]('-')] = value
else:
# Format: --key value
key = [Link]('-')
if i + 1 < len([Link]) and not [Link][i + 1].startswi
value = [Link][i + 1]
[Link][key] = value

Page 1 of 22
i += 1
else:
[Link][key] = True
i += 1

return [Link]

# Usage:
# python [Link] --name John --age 30 --city="New York"

parser = SimpleArgParser()
args = [Link]()
print(f"Arguments: {args}")

# Output:
# Arguments: {'name': 'John', 'age': '30', 'city': 'New York'}

2. Logging System Using sys Streams

import sys
from datetime import datetime

class Logger:
"""Custom logging system using sys streams"""

def __init__(self, logfile=None):


[Link] = logfile
self.original_stdout = [Link]
self.original_stderr = [Link]

def log(self, message, level="INFO"):


"""Log a message with timestamp"""
timestamp = [Link]().strftime("%Y-%m-%d %H:%M:%S")
formatted_message = f"[{timestamp}] [{level}] {message}"

# Write to stdout
self.original_stdout.write(formatted_message + "\n")

Page 2 of 22
# Also write to file if specified
if [Link]:
with open([Link], 'a') as f:
[Link](formatted_message + "\n")

def log_error(self, message):


"""Log error message to stderr"""
timestamp = [Link]().strftime("%Y-%m-%d %H:%M:%S")
formatted_message = f"[{timestamp}] [ERROR] {message}"
self.original_stderr.write(formatted_message + "\n")

def info(self, message):


"""Log info level message"""
[Link](message, "INFO")

def warning(self, message):


"""Log warning level message"""
[Link](message, "WARNING")

def error(self, message):


"""Log error level message"""
self.log_error(message)

# Usage:
logger = Logger("[Link]")
[Link]("Application started")
[Link]("This is a warning")
[Link]("An error occurred!")

# Output to console:
# [2024-01-15 10:30:45] [INFO] Application started
# [2024-01-15 10:30:45] [WARNING] This is a warning
# [2024-01-15 10:30:45] [ERROR] An error occurred!

# [Link] content:

Page 3 of 22
# [2024-01-15 10:30:45] [INFO] Application started
# [2024-01-15 10:30:45] [WARNING] This is a warning

3. Interactive Menu System

import sys

def create_menu():
"""Create interactive command-line menu"""

options = {
'1': 'Add item',
'2': 'Delete item',
'3': 'View items',
'4': 'Exit'
}

items = []

while True:
# Display menu
[Link]("\n=== Main Menu ===\n")
for key, value in [Link]():
[Link](f"{key}. {value}\n")

# Get user choice


[Link]("Enter your choice: ")
[Link]()
choice = [Link]().strip()

if choice == '1':
[Link]("Enter item name: ")
[Link]()
item = [Link]().strip()
[Link](item)
[Link](f"Item '{item}' added!\n")

Page 4 of 22
elif choice == '2':
if items:
[Link](f"Items: {', '.join(items)}\n")
[Link]("Enter item to delete: ")
[Link]()
item = [Link]().strip()
if item in items:
[Link](item)
[Link](f"Item '{item}' deleted!\n")
else:
[Link](f"Item '{item}' not found!\n")
else:
[Link]("No items to delete!\n")

elif choice == '3':


if items:
[Link](f"Items: {', '.join(items)}\n")
else:
[Link]("No items in list.\n")

elif choice == '4':


[Link]("Exiting...\n")
[Link](0)

else:
[Link]("Invalid choice! Try again.\n")

# Uncomment to run:
# create_menu()

4. Performance Monitoring

import sys
import time

class PerformanceMonitor:
"""Monitor Python runtime performance"""

Page 5 of 22
def __init__(self):
[Link] = {}

def get_memory_info(self):
"""Get memory information"""
return {
'refcount': [Link],
'max_recursion': [Link]()
}

def get_platform_info(self):
"""Get platform information"""
return {
'platform': [Link],
'version': [Link],
'version_info': sys.version_info,
'executable': [Link],
'prefix': [Link]
}

def benchmark_function(self, func, *args, **kwargs):


"""Benchmark a function's execution time"""
start_time = [Link]()
result = func(*args, **kwargs)
end_time = [Link]()

execution_time = end_time - start_time


[Link](f"Function: {func.__name__}\n")
[Link](f"Execution time: {execution_time:.6f} seconds\n")

return result, execution_time

# Usage:
monitor = PerformanceMonitor()

# Display system info

Page 6 of 22
print("Platform Info:", monitor.get_platform_info())

# Benchmark a function
def slow_function(n):
total = 0
for i in range(n):
total += i
return total

result, time_taken = monitor.benchmark_function(slow_function, 1000000)


print(f"Result: {result}, Time: {time_taken:.6f}s")

# Output:
# Platform Info: {'platform': 'win32', 'version': '3.8.5 ...', ...}
# Function: slow_function
# Execution time: 0.050000 seconds

PART 2: ADVANCED TESTING EXAMPLES

1. Testing with Edge Cases and Boundaries

import unittest
import math

def calculate_bmi(weight, height):


"""Calculate BMI - weight in kg, height in meters"""
if height <= 0 or weight <= 0:
raise ValueError("Weight and height must be positive")
return weight / (height ** 2)

class TestBMICalculation([Link]):
"""Comprehensive BMI calculation tests"""

# Normal cases
def test_normal_bmi(self):

Page 7 of 22
"""Test normal BMI calculation"""
bmi = calculate_bmi(70, 1.75)
[Link](bmi, 22.86, places=2)

# Boundary cases
def test_zero_height(self):
"""Test with zero height (boundary)"""
with [Link](ValueError):
calculate_bmi(70, 0)

def test_zero_weight(self):
"""Test with zero weight (boundary)"""
with [Link](ValueError):
calculate_bmi(0, 1.75)

# Negative values
def test_negative_height(self):
"""Test with negative height"""
with [Link](ValueError):
calculate_bmi(70, -1.75)

def test_negative_weight(self):
"""Test with negative weight"""
with [Link](ValueError):
calculate_bmi(-70, 1.75)

# Edge cases
def test_very_small_values(self):
"""Test with very small values"""
bmi = calculate_bmi(0.001, 0.001)
[Link](bmi, 0)

def test_very_large_values(self):
"""Test with very large values"""
bmi = calculate_bmi(1000, 2.5)
[Link](bmi, 0)

Page 8 of 22
# Float precision
def test_float_precision(self):
"""Test float calculation precision"""
bmi = calculate_bmi(70.5, 1.754)
[Link](bmi, 22.88, places=1)

if __name__ == '__main__':
[Link](verbosity=2)

# Output:
# test_float_precision ... ok
# test_negative_height ... ok
# test_negative_weight ... ok
# test_normal_bmi ... ok
# test_very_large_values ... ok
# test_very_small_values ... ok
# test_zero_height ... ok
# test_zero_weight ... ok
#
# Ran 8 tests in 0.002s
# OK

2. Testing Database Operations

import unittest
from [Link] import Mock, patch

class UserDatabase:
"""Simulated database class"""

def __init__(self):
[Link] = {}
self.id_counter = 0

def add_user(self, name, email):


"""Add user to database"""
if not name or not email:

Page 9 of 22
raise ValueError("Name and email required")

self.id_counter += 1
[Link][self.id_counter] = {'name': name, 'email': email}
return self.id_counter

def get_user(self, user_id):


"""Get user by ID"""
if user_id not in [Link]:
raise KeyError(f"User {user_id} not found")
return [Link][user_id]

def update_user(self, user_id, name=None, email=None):


"""Update user information"""
if user_id not in [Link]:
raise KeyError(f"User {user_id} not found")

if name:
[Link][user_id]['name'] = name
if email:
[Link][user_id]['email'] = email

def delete_user(self, user_id):


"""Delete user"""
if user_id not in [Link]:
raise KeyError(f"User {user_id} not found")
del [Link][user_id]

class TestUserDatabase([Link]):
"""Test database operations"""

def setUp(self):
"""Set up test database"""
[Link] = UserDatabase()

def test_add_user(self):
"""Test adding a user"""

Page 10 of 22
user_id = [Link].add_user("John", "john@[Link]")
[Link](user_id, 1)
[Link]([Link][1]['name'], "John")

def test_add_user_invalid(self):
"""Test adding user with invalid data"""
with [Link](ValueError):
[Link].add_user("", "email@[Link]")

def test_get_user(self):
"""Test retrieving a user"""
user_id = [Link].add_user("Alice", "alice@[Link]")
user = [Link].get_user(user_id)
[Link](user['name'], "Alice")

def test_get_nonexistent_user(self):
"""Test getting non-existent user"""
with [Link](KeyError):
[Link].get_user(999)

def test_update_user(self):
"""Test updating user"""
user_id = [Link].add_user("Bob", "bob@[Link]")
[Link].update_user(user_id, name="Robert")
user = [Link].get_user(user_id)
[Link](user['name'], "Robert")

def test_delete_user(self):
"""Test deleting user"""
user_id = [Link].add_user("Charlie", "charlie@[Link]")
[Link].delete_user(user_id)
with [Link](KeyError):
[Link].get_user(user_id)

if __name__ == '__main__':
[Link](verbosity=2)

Page 11 of 22
# Output:
# test_add_user ... ok
# test_add_user_invalid ... ok
# test_delete_user ... ok
# test_get_nonexistent_user ... ok
# test_get_user ... ok
# test_update_user ... ok
#
# Ran 6 tests in 0.001s
# OK

3. Testing with Setup and Teardown

import unittest
import tempfile
import os

class FileOperations:
"""File handling operations"""

def __init__(self, filename):


[Link] = filename

def write_data(self, data):


"""Write data to file"""
with open([Link], 'w') as f:
[Link](data)

def read_data(self):
"""Read data from file"""
with open([Link], 'r') as f:
return [Link]()

def append_data(self, data):


"""Append data to file"""
with open([Link], 'a') as f:
[Link](data)

Page 12 of 22
class TestFileOperations([Link]):
"""Test file operations"""

def setUp(self):
"""Create temporary file for testing"""
self.temp_file = [Link](delete=False, mode='w')
self.temp_filename = self.temp_file.name
self.temp_file.close()
self.file_ops = FileOperations(self.temp_filename)

def tearDown(self):
"""Clean up temporary file"""
if [Link](self.temp_filename):
[Link](self.temp_filename)

def test_write_and_read(self):
"""Test writing and reading data"""
test_data = "Hello, World!"
self.file_ops.write_data(test_data)
read_data = self.file_ops.read_data()
[Link](read_data, test_data)

def test_append_data(self):
"""Test appending data"""
self.file_ops.write_data("Hello")
self.file_ops.append_data(" World")
[Link](self.file_ops.read_data(), "Hello World")

def test_empty_file(self):
"""Test reading empty file"""
self.file_ops.write_data("")
[Link](self.file_ops.read_data(), "")

def test_multiline_data(self):
"""Test with multiline data"""
data = "Line 1\nLine 2\nLine 3"

Page 13 of 22
self.file_ops.write_data(data)
[Link](self.file_ops.read_data(), data)

if __name__ == '__main__':
[Link](verbosity=2)

# Output:
# test_append_data ... ok
# test_empty_file ... ok
# test_multiline_data ... ok
# test_write_and_read ... ok
#
# Ran 4 tests in 0.002s
# OK

4. Testing with Exception Handling

import unittest

def process_data(data):
"""Process data with validation"""
if not data:
raise ValueError("Data cannot be empty")

if not isinstance(data, list):


raise TypeError("Data must be a list")

if len(data) == 0:
raise ValueError("Data list cannot be empty")

result = []
for item in data:
if not isinstance(item, (int, float)):
raise TypeError(f"Invalid item type: {type(item)}")

if item < 0:
raise ValueError(f"Negative number not allowed: {item}")

Page 14 of 22
[Link](item * 2)

return result

class TestExceptionHandling([Link]):
"""Test exception handling"""

def test_valid_data(self):
"""Test with valid data"""
result = process_data([1, 2, 3])
[Link](result, [2, 4, 6])

def test_none_data(self):
"""Test with None"""
with [Link](ValueError) as context:
process_data(None)
[Link]("empty", str([Link]))

def test_not_a_list(self):
"""Test with non-list input"""
with [Link](TypeError) as context:
process_data("not a list")
[Link]("must be a list", str([Link]))

def test_empty_list(self):
"""Test with empty list"""
with [Link](ValueError):
process_data([])

def test_invalid_item_type(self):
"""Test with invalid item type"""
with [Link](TypeError):
process_data([1, "two", 3])

def test_negative_number(self):
"""Test with negative number"""

Page 15 of 22
with [Link](ValueError) as context:
process_data([1, -2, 3])
[Link]("Negative", str([Link]))

def test_float_data(self):
"""Test with float data"""
result = process_data([1.5, 2.5, 3.5])
[Link](result, [3.0, 5.0, 7.0])

if __name__ == '__main__':
[Link](verbosity=2)

# Output:
# test_empty_list ... ok
# test_float_data ... ok
# test_invalid_item_type ... ok
# test_negative_number ... ok
# test_none_data ... ok
# test_not_a_list ... ok
# test_valid_data ... ok
#
# Ran 7 tests in 0.001s
# OK

5. Test-Driven Development (TDD) Example

import unittest

# Step 1: Write tests first


class TestCalculator([Link]):
"""Calculator tests (written before implementation)"""

def test_add(self):
"""Test addition"""
[Link](add(2, 3), 5)

def test_subtract(self):

Page 16 of 22
"""Test subtraction"""
[Link](subtract(5, 3), 2)

def test_multiply(self):
"""Test multiplication"""
[Link](multiply(4, 5), 20)

def test_divide(self):
"""Test division"""
[Link](divide(10, 2), 5)

def test_divide_by_zero(self):
"""Test division by zero"""
with [Link](ValueError):
divide(10, 0)

def test_power(self):
"""Test power operation"""
[Link](power(2, 3), 8)

# Step 2: Implement code to pass tests


def add(a, b):
"""Add two numbers"""
return a + b

def subtract(a, b):


"""Subtract two numbers"""
return a - b

def multiply(a, b):


"""Multiply two numbers"""
return a * b

def divide(a, b):


"""Divide two numbers"""
if b == 0:
raise ValueError("Cannot divide by zero")

Page 17 of 22
return a / b

def power(a, b):


"""Raise a to power b"""
return a ** b

# Step 3: Run tests


if __name__ == '__main__':
[Link](verbosity=2)

# Output:
# test_add ... ok
# test_divide ... ok
# test_divide_by_zero ... ok
# test_multiply ... ok
# test_power ... ok
# test_subtract ... ok
#
# Ran 6 tests in 0.001s
# OK

PART 3: BEST PRACTICES AND TIPS

1. Test Naming Conventions

import unittest

# Good naming practices


class TestUserAuthentication([Link]):

# Method names clearly describe what they test


def test_user_login_with_valid_credentials(self):
"""Test successful login"""
pass

Page 18 of 22
def test_user_login_with_invalid_password(self):
"""Test login failure with wrong password"""
pass

def test_user_login_with_nonexistent_user(self):
"""Test login with non-existent username"""
pass

def test_user_registration_creates_new_account(self):
"""Test account creation"""
pass

2. Organizing Tests

# Structure: tests/ directory


# project/
# ├── [Link]
# ├── [Link]
# └── tests/
# ├── __init__.py
# ├── test_main.py
# ├── test_utils.py
# └── test_integration.py

# test_main.py
import unittest
from main import main_function

class TestMainFunctions([Link]):
"""Tests for [Link]"""
pass

# test_utils.py
import unittest
from utils import utility_function

class TestUtilityFunctions([Link]):

Page 19 of 22
"""Tests for [Link]"""
pass

# Run all tests


# python -m unittest discover tests/ -v

3. Common Testing Patterns

import unittest

# Pattern 1: Arrange-Act-Assert
class TestArrangeActAssert([Link]):

def test_example(self):
# Arrange - setup test data
input_value = 5
expected_output = 10

# Act - perform action


actual_output = input_value * 2

# Assert - verify result


[Link](actual_output, expected_output)

# Pattern 2: Given-When-Then (BDD style)


class TestGivenWhenThen([Link]):

def test_user_login(self):
# Given - initial state
username = "admin"
password = "password123"

# When - perform action


login_result = login(username, password)

# Then - verify outcome


[Link](login_result)

Page 20 of 22
# Pattern 3: Test Parametrization
class TestParametrized([Link]):

def test_multiple_cases(self):
"""Test multiple input/output combinations"""
test_cases = [
(2, 3, 5), # add(2,3) = 5
(10, 5, 15), # add(10,5) = 15
(0, 0, 0), # add(0,0) = 0
(-1, 1, 0), # add(-1,1) = 0
]

for a, b, expected in test_cases:


with [Link](a=a, b=b):
[Link](add(a, b), expected)

def add(a, b):


return a + b

def login(username, password):


return username == "admin" and password == "password123"

SUMMARY TABLE: sys Module vs Testing

Task sys Module Testing

Input/Output stdin, stdout, stderr Mock/Patch

Parameterized
Arguments [Link]
tests

Not typically
System Info [Link], [Link]
tested

Exit Control [Link]() assertRaises

Page 21 of 22
Task sys Module Testing

Module
[Link] Setup/Teardown
Search

[Link](),
Performance Benchmark tests
[Link]()

This comprehensive guide covers practical implementations, best


practices, and advanced patterns for both system-level interaction and
testing in Python.

Page 22 of 22

You might also like