9.3 שגיאות וטסטים פתרון
טיפול נכון בשגיאות¶
from pathlib import Path
def divide(a: float, b: float) -> float:
if b == 0:
raise ZeroDivisionError("לא ניתן לחלק באפס")
return a / b
def read_config(path: str) -> str:
return Path(path).read_text()
def process(a: float, b: float, config_path: str) -> None:
try:
result = divide(a, b)
config = read_config(config_path)
print(f"result={result}, config={config}")
except ZeroDivisionError as e:
print(f"שגיאת חישוב: {e}")
except FileNotFoundError:
print(f"קובץ הגדרות לא נמצא: {config_path}")
TDD - כתיבת טסטים לפני הקוד¶
שלב 1 - הטסטים:
import unittest
class TestValidatePassword(unittest.TestCase):
def test_valid_password(self):
self.assertTrue(validate_password("Secure1!"))
def test_too_short(self):
self.assertFalse(validate_password("Ab1"))
def test_no_uppercase(self):
self.assertFalse(validate_password("secure123"))
def test_no_digit(self):
self.assertFalse(validate_password("SecurePass"))
def test_exactly_8_chars_valid(self):
self.assertTrue(validate_password("Validpa1"))
def test_empty_string(self):
self.assertFalse(validate_password(""))
def test_only_digits(self):
self.assertFalse(validate_password("12345678"))
if __name__ == "__main__":
unittest.main()
שלב 2 - המימוש:
def validate_password(password: str) -> bool:
"""
בודקת אם סיסמה תקינה.
:param password: הסיסמה לבדיקה
:return: True אם תקינה, False אחרת
"""
if len(password) < 8:
return False
if not any(c.isupper() for c in password):
return False
if not any(c.isdigit() for c in password):
return False
return True
תיעוד ו-type hints¶
דוגמה לפונקציה מפרק קודם עם תיעוד מלא: