נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
19
חלקPart 3: קוד נקי ו-OOPClean code & OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

בדיקות עם pytestTesting with pytest

assert, פונקציות בדיקה, fixtures ו-parametrize.

assert, test functions, fixtures and parametrize.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

שלוש בדיקות ראשונותYour first three tests

תזכורת: מה ביקשוReminder: the task

נתונה is_even(n). כתבו test_is_even() עם שלושה assert לפחות: מספר זוגי, מספר אי-זוגי, ואפס.

Given is_even(n). Write test_is_even() with at least three asserts: an even number, an odd number, and zero.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def is_even(n):
    return n % 2 == 0

def test_is_even():
    assert is_even(4)
    assert not is_even(7)
    assert is_even(0)

test_is_even()
print("ok")
פלטOutput
ok

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

בדיקה שתופסת באגA test that catches a bug

תזכורת: מה ביקשוReminder: the task

ל-average(nums) יש באג ברשימה ריקה. כתבו test_average() שבודקת ממוצע רגיל ושרשימה ריקה מחזירה 0, ואז תקנו את הפונקציה כך שהבדיקה תעבור.

average(nums) has a bug with an empty list. Write test_average() checking a normal average and that an empty list returns 0, then fix the function so the test passes.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def average(nums):
    if not nums:
        return 0
    return sum(nums) / len(nums)

def test_average():
    assert average([2, 4]) == 3
    assert average([]) == 0

test_average()
print("ok")
פלטOutput
ok

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

לבדוק שגיאהTesting an error

תזכורת: מה ביקשוReminder: the task

כתבו parse_age(text) שמחזירה int, ומעלה ValueError אם הגיל שלילי או מעל 130 (ו-int() כבר מעלה ValueError לטקסט לא מספרי). כתבו test_parse_age() שבודקת ערך תקין, ובעזרת pytest.raises שלושה מקרים שגויים: "-1", "200", "abc".

Write parse_age(text) returning an int, raising ValueError if negative or above 130 (int() already raises ValueError for non-numbers). Write test_parse_age() checking a valid value and, with pytest.raises, three bad cases: "-1", "200", "abc".

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import pytest

def parse_age(text):
    age = int(text)
    if not 0 <= age <= 130:
        raise ValueError(f"age out of range: {age}")
    return age

def test_parse_age():
    assert parse_age(" 42 ") == 42
    for bad in ["-1", "200", "abc"]:
        with pytest.raises(ValueError):
            parse_age(bad)

test_parse_age()
print("ok")
פלטOutput
ok

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

parametrizeparametrize

תזכורת: מה ביקשוReminder: the task

כתבו to_celsius(f) (מעוגל ל-1) ובדיקה עם @pytest.mark.parametrize("f, c", [...]) שמכסה לפחות ארבעה זוגות, כולל 32→0 ו-212→100.

Write to_celsius(f) (rounded to 1) and a test with @pytest.mark.parametrize("f, c", [...]) covering at least four pairs, including 32→0 and 212→100.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import pytest

def to_celsius(f):
    return round((f - 32) * 5 / 9, 1)

@pytest.mark.parametrize("f, c", [(32, 0), (212, 100), (-40, -40), (98.6, 37.0)])
def test_to_celsius(f, c):
    assert to_celsius(f) == c

for f, c in [(32, 0), (212, 100), (-40, -40), (98.6, 37.0)]:
    test_to_celsius(f, c)
print("ok")
פלטOutput
ok

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 19: עשר בדיקותShelf, step 19: ten tests

תזכורת: מה ביקשוReminder: the task

נתונות add ו-find של המדף. כתבו לפחות חמש פונקציות test_... (אפשר יותר) שבודקות: ההחזרה של add, ניקוי רווחים, דחיית כותרת ריקה (pytest.raises), find בלי רגישות לאותיות, ו-find שמחזירה None. בסוף הקוד מריץ את כל פונקציות הבדיקה.

Given the shelf's add and find. Write at least five test_... functions (more is fine) checking: add's return value, stripping spaces, rejecting an empty title (pytest.raises), case-insensitive find, and find returning None. The code then runs every test function.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
test_shelf.py
def add(shelf, title, author):
    title = title.strip()
    if not title:
        raise ValueError("title is empty")
    shelf.append({"title": title, "author": author.strip()})
    return len(shelf)

def find(shelf, title):
    for b in shelf:
        if b["title"].lower() == title.strip().lower():
            return b
    return None

import pytest

def test_add_returns_count():
    shelf = []
    assert add(shelf, "Dune", "Frank Herbert") == 1
    assert add(shelf, "Emma", "Jane Austen") == 2

def test_add_strips():
    shelf = []
    add(shelf, " Dune ", " Frank Herbert ")
    assert shelf == [{"title": "Dune", "author": "Frank Herbert"}]

def test_empty_title():
    with pytest.raises(ValueError):
        add([], "  ", "x")

def test_find_case():
    shelf = [{"title": "Dune", "author": "F"}]
    assert find(shelf, "dUNE")["author"] == "F"

def test_find_none():
    assert find([], "Dune") is None

tests = [f for name, f in list(globals().items()) if name.startswith("test_")]
for t in tests:
    t()
print(len(tests), "tests passed")
פלטOutput
5 tests passed

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

TDD: סיסמה חזקהTDD: a strong password

תזכורת: מה ביקשוReminder: the task

כתבו קודם test_strength() ואז strength(pw) שמחזירה ציון 0–4: נקודה לאורך 8 ומעלה, לאות גדולה, לספרה ולסימן שאינו אות או ספרה. הבדיקה צריכה לכסות לפחות חמישה מקרים, כולל מחרוזת ריקה.

First write test_strength() and then strength(pw) returning a 0–4 score: a point for length 8+, an uppercase letter, a digit, and a character that's neither letter nor digit. The test should cover at least five cases, including an empty string.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def test_strength():
    assert strength("") == 0
    assert strength("abcdefgh") == 1
    assert strength("Abcdefgh") == 2
    assert strength("Abcdefg1") == 3
    assert strength("Abcdef1!") == 4
    assert strength("A1!") == 3

def strength(pw):
    return sum([
        len(pw) >= 8,
        any(c.isupper() for c in pw),
        any(c.isdigit() for c in pw),
        any(not c.isalnum() for c in pw),
    ])

test_strength()
print(strength("Shelf2026!"))
פלטOutput
4

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

בודק הבדיקותTesting the tests

תזכורת: מה ביקשוReminder: the task

כתבו mutation_score(test, func, mutants): מריצה את test על הפונקציה האמיתית (חייבת לעבור), ואז על כל מוטנט (גרסה שבורה). מחזירה כמה מוטנטים "נהרגו", כלומר הבדיקה נכשלה עליהם. הבדיקה מקבלת את הפונקציה כפרמטר.

Write mutation_score(test, func, mutants): runs test on the real function (must pass), then on each mutant (a broken version). Returns how many mutants were "killed", i.e. the test failed on them. The test takes the function as a parameter.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def mutation_score(test, func, mutants):
    test(func)
    killed = 0
    for m in mutants:
        try:
            test(m)
        except AssertionError:
            killed += 1
    return killed

def maximum(a, b):
    return a if a > b else b

mutants = [lambda a, b: a, lambda a, b: b, lambda a, b: min(a, b), lambda a, b: a if a >= b else b]

def weak_test(f):
    assert f(2, 1) == 2

def strong_test(f):
    assert f(2, 1) == 2 and f(1, 2) == 2 and f(3, 3) == 3

print(mutation_score(weak_test, maximum, mutants), mutation_score(strong_test, maximum, mutants))
פלטOutput
2 3

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich