Python Unit7 Unit8 Advanced Examples
Python Unit7 Unit8 Advanced Examples
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'}
import sys
from datetime import datetime
class Logger:
"""Custom logging system using sys streams"""
# 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")
# 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
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")
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")
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]
}
# Usage:
monitor = PerformanceMonitor()
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
# Output:
# Platform Info: {'platform': 'win32', 'version': '3.8.5 ...', ...}
# Function: slow_function
# Execution time: 0.050000 seconds
import unittest
import math
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
import unittest
from [Link] import Mock, patch
class UserDatabase:
"""Simulated database class"""
def __init__(self):
[Link] = {}
self.id_counter = 0
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
if name:
[Link][user_id]['name'] = name
if email:
[Link][user_id]['email'] = email
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
import unittest
import tempfile
import os
class FileOperations:
"""File handling operations"""
def read_data(self):
"""Read data from file"""
with open([Link], 'r') as f:
return [Link]()
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
import unittest
def process_data(data):
"""Process data with validation"""
if not data:
raise ValueError("Data cannot be empty")
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
import unittest
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)
Page 17 of 22
return a / b
# 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
import unittest
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
# 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
import unittest
# Pattern 1: Arrange-Act-Assert
class TestArrangeActAssert([Link]):
def test_example(self):
# Arrange - setup test data
input_value = 5
expected_output = 10
def test_user_login(self):
# Given - initial state
username = "admin"
password = "password123"
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
]
Parameterized
Arguments [Link]
tests
Not typically
System Info [Link], [Link]
tested
Page 21 of 22
Task sys Module Testing
Module
[Link] Setup/Teardown
Search
[Link](),
Performance Benchmark tests
[Link]()
Page 22 of 22