נבנה על ידי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.

01למה לבדוק?Why test?

כל פעם ששיניתם קוד, הרצתם ובדקתם בעיניים שהכול עדיין עובד. בדיקה אוטומטית עושה את זה בשבילכם: היא מריצה את הקוד עם קלט ידוע ובודקת עם assert שהתוצאה נכונה. ככל שהפרויקט גדל, הבדיקות הן מה שנותן אומץ לשנות בלי לשבור. התרגילים באתר הזה בנויים בדיוק כך.

Every time you changed code, you ran it and eyeballed that everything still works. An automated test does that for you: it runs code with known input and asserts the result is right. As a project grows, tests give you the courage to change it without breaking things. This site's exercises are built exactly this way.

first_test.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

test_add()
print("כל הבדיקות עברו")
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

test_add()
print("all tests passed")
פלטOutput
כל הבדיקות עברו
all tests passed
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

בדיקות הן כמו רשימת בדיקה של טייס לפני המראה: גם טייס ותיק לא סומך על הזיכרון, כי פספוס אחד יקר מדי.

Tests are like a pilot's pre-flight checklist: even a veteran doesn't trust memory, because one miss costs too much.

טעות נפוצהCommon mistake

בדיקה שתמיד עוברת, כי שכחו את ה-assert.

A test that always passes because the assert was forgotten.

first_test.py
def double(n):
    return n * 3

def test_double():
    double(2) == 4

test_double()
assert double(2) == 4, "the test above passed, yet double(2) is 6: it had no assert"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/first_test.py", line 8, in <module>
    assert double(2) == 4, "the test above passed, yet double(2) is 6: it had no assert"
           ^^^^^^^^^^^^^^
AssertionError: the test above passed, yet double(2) is 6: it had no assert
בעברית פשוטה: In plain words: AssertionError: the test above passed, yet double(2) is 6: ...: השוואה בלי assert לא בודקת כלום. כל בדיקה חייבת assert.AssertionError: the test above passed, yet double(2) is 6: ...: a comparison without assert checks nothing. Every test needs an assert.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02הרצה עם pytestRunning pytest

pytest מחפש בתיקייה קבצים ששמם מתחיל ב-test_, ובתוכם פונקציות שמתחילות ב-test_, ומריץ כל אחת בנפרד. נקודה ירוקה לכל בדיקה שעברה. הנה קובץ קוד shelf.py וקובץ בדיקות test_shelf.py:

pytest looks in the folder for files whose name starts with test_, and inside them for functions starting with test_, and runs each separately. A dot for every passing test. Here's a code file shelf.py and a test file test_shelf.py:

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
test_shelf.py
from shelf import add, find


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


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


def test_find_ignores_case():
    shelf = [{"title": "Dune", "author": "Frank Herbert"}]
    assert find(shelf, "DUNE")["author"] == "Frank Herbert"


def test_find_missing_returns_none():
    assert find([], "Dune") is None
Terminal
python3 -m pytest -q
פלטOutput
....                                                                     [100%]
4 passed in 0.01s
אנלוגיה מהחייםReal-life analogy

pytest הוא כמו בוחן שעובר על כל השאלות במבחן לפי הסדר ומסמן וי או איקס, בלי להתעייף ובלי לדלג.

pytest is like an examiner going through every question in order, marking each right or wrong, never tiring and never skipping.

טעות נפוצהCommon mistake

קובץ הבדיקות לא מתחיל ב-test_, ו-pytest לא מוצא כלום.

The test file doesn't start with test_, so pytest finds nothing.

Terminal
python3 -m pytest -q
מה הטרמינל עונהWhat the terminal says
no tests ran in 0.01s
בעברית פשוטה: In plain words: no tests ran: pytest מחפש רק קבצים test_*.py (או *_test.py). משנים את השם ל-test_shelf.py.no tests ran: pytest only looks for test_*.py (or *_test.py) files. Rename to test_shelf.py.

פונקציית בדיקה היא פונקציה רגילה עם assert.

A test function is a normal function with assert.

עוד דוגמה: בדיקה בסגנון pytestOne more: a pytest-style test
example.py
def is_even(n):
    return n % 2 == 0

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

test_is_even()
print("test passed")
פלטOutput
test passed
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03לקרוא כישלוןReading a failure

כשבדיקה נכשלת, pytest מסמן F ומראה בדיוק באיזו שורה ומה השתבש. בואו נכניס באג: find משווה בלי להתעלם מאותיות גדולות. הבדיקה תופסת אותו מיד:

When a test fails, pytest marks F and shows exactly which line and what went wrong. Let's plant a bug: find compares without ignoring case. The test catches it at once:

Terminal
python3 -m pytest -q --tb=short
פלטOutput
..F.                                                                     [100%]
=================================== FAILURES ===================================
____________________________ test_find_ignores_case ____________________________
test_shelf.py:18: in test_find_ignores_case
    assert find(shelf, "DUNE")["author"] == "Frank Herbert"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E   TypeError: 'NoneType' object is not subscriptable
=========================== short test summary info ============================
FAILED test_shelf.py::test_find_ignores_case - TypeError: 'NoneType' object i...
1 failed, 3 passed in 0.01s
אנלוגיה מהחייםReal-life analogy

כישלון בבדיקה הוא כמו גלאי עשן שמצפצף: מעצבן לרגע, אבל עדיף בהרבה על לגלות את השריפה מאוחר.

A failing test is like a smoke alarm beeping: annoying for a moment, but far better than finding the fire late.

טעות נפוצהCommon mistake

משנים את הבדיקה כדי שתעבור, במקום לתקן את הקוד.

Changing the test to make it pass, instead of fixing the code.

find.py
def find(shelf, title):
    for b in shelf:
        if b == title:
            return b

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

test_find()
assert find(["Dune"], "dune") == "Dune", "the test was bent to match the bug: users still can't find dune"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/find.py", line 10, in <module>
    assert find(["Dune"], "dune") == "Dune", "the test was bent to match the bug: users still can't find dune"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: the test was bent to match the bug: users still can't find dune
בעברית פשוטה: In plain words: AssertionError: the test was bent to match the bug: ...: הבדיקה מתארת מה צריך לקרות. כשהיא נכשלת, קודם חושדים בקוד.AssertionError: the test was bent to match the bug: ...: the test describes what should happen. When it fails, suspect the code first.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04בדיקת שגיאות ומקרי קצהTesting errors and edge cases

לפעמים ההתנהגות הנכונה היא לזרוק שגיאה. pytest.raises בודק שהשגיאה באמת נזרקת. ואיפה כדאי לבדוק? במקרי קצה: רשימה ריקה, מחרוזת של רווחים, אפס. וכל באג שמצאתם מקבל בדיקה משלו, כדי שלא יחזור בשקט (רגרסיה).

Sometimes the right behaviour is to raise an error. pytest.raises checks the error really is raised. Where to test? At edge cases: an empty list, a string of spaces, zero. And every bug you find gets its own test, so it can't quietly come back (a regression).

test_errors.py
import pytest
from shelf import add


def test_empty_title_is_rejected():
    with pytest.raises(ValueError):
        add([], "   ", "Nobody")


def test_shelf_unchanged_after_error():
    shelf = []
    with pytest.raises(ValueError):
        add(shelf, "", "x")
    assert shelf == []
Terminal
python3 -m pytest -q test_errors.py
פלטOutput
..                                                                       [100%]
2 passed in 0.01s
אנלוגיה מהחייםReal-life analogy

מקרי קצה הם כמו לבדוק גשר עם המשאית הכי כבדה ולא רק עם אופניים: אם הוא מחזיק את הקצה, הוא מחזיק את הכול.

Edge cases are like testing a bridge with the heaviest truck, not just a bicycle: if it holds the extreme, it holds everything.

טעות נפוצהCommon mistake

מצפים לשגיאה, אבל הקוד לא זורק אותה.

Expecting an error that the code never raises.

Terminal
python3 -m pytest -q --tb=line
מה הטרמינל עונהWhat the terminal says
F                                                                        [100%]
=================================== FAILURES ===================================
E   Failed: DID NOT RAISE ZeroDivisionError
/Users/you/python-course/test_calc.py:6: Failed: DID NOT RAISE ZeroDivisionError
=========================== short test summary info ============================
FAILED test_calc.py::test_zero_raises - Failed: DID NOT RAISE ZeroDivisionError
1 failed in 0.01s
בעברית פשוטה: In plain words: Failed: DID NOT RAISE: הבדיקה ציפתה ל-ZeroDivisionError והקוד החזיר 0. מחליטים מה ההתנהגות הרצויה, ומתקנים את הקוד או את הבדיקה בהתאם.Failed: DID NOT RAISE: the test expected ZeroDivisionError and the code returned 0. Decide what the desired behaviour is, then fix the code or the test to match.

05fixtures ו-parametrizeFixtures and parametrize

כשכמה בדיקות צריכות את אותו מדף, כותבים fixture: פונקציה עם @pytest.fixture שמחזירה אותו, ובדיקה שרוצה אותו פשוט מקבלת פרמטר באותו שם. כל בדיקה מקבלת עותק חדש. parametrize מריץ בדיקה אחת על רשימת קלטים, וכל קלט נספר כבדיקה נפרדת.

When several tests need the same shelf, write a fixture: a function with @pytest.fixture that returns it, and a test that wants it just takes a parameter with that name. Each test gets a fresh copy. parametrize runs one test over a list of inputs, each counted as a separate test.

test_fixture.py
import pytest
from shelf import add, find


@pytest.fixture
def shelf():
    s = []
    add(s, "Dune", "Frank Herbert")
    add(s, "Emma", "Jane Austen")
    return s


def test_has_two(shelf):
    assert len(shelf) == 2


@pytest.mark.parametrize("query", ["Dune", "dune", " DUNE "])
def test_find_variants(shelf, query):
    assert find(shelf, query)["author"] == "Frank Herbert"
Terminal
python3 -m pytest -v --no-header -p no:cacheprovider test_fixture.py
פלטOutput
============================= test session starts ==============================
collecting ... collected 4 items

test_fixture.py::test_has_two PASSED                                     [ 25%]
test_fixture.py::test_find_variants[Dune] PASSED                         [ 50%]
test_fixture.py::test_find_variants[dune] PASSED                         [ 75%]
test_fixture.py::test_find_variants[ DUNE ] PASSED                       [100%]

============================== 4 passed in 0.01s ===============================
אנלוגיה מהחייםReal-life analogy

fixture הוא כמו מטבח שמסודר מחדש לפני כל מנה בתחרות בישול: כל מתחרה מקבל אותם מצרכים טריים.

A fixture is like a kitchen reset before every dish in a cooking contest: each contestant gets the same fresh ingredients.

טעות נפוצהCommon mistake

טעות כתיב בשם ה-fixture.

A typo in the fixture's name.

Terminal
python3 -m pytest -q --tb=short
מה הטרמינל עונהWhat the terminal says
E                                                                        [100%]
==================================== ERRORS ====================================
_________________________ ERROR at setup of test_empty _________________________
file /Users/you/python-course/test_fx.py, line 9
  def test_empty(shelff):
E       fixture 'shelff' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, shelf, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

/Users/you/python-course/test_fx.py:9
=========================== short test summary info ============================
ERROR test_fx.py::test_empty
1 error in 0.01s
בעברית פשוטה: In plain words: ERROR ... fixture 'shelff' not found: pytest מחפש fixture לפי שם הפרמטר בדיוק. מתקנים ל-shelf.ERROR ... fixture 'shelff' not found: pytest looks a fixture up by the exact parameter name. Fix it to shelf.

06לכתוב בדיקה קודם (TDD)Test first (TDD)

ב-TDD כותבים קודם את הבדיקה, רואים אותה נכשלת (אדום), כותבים את הקוד הפשוט ביותר שמעביר אותה (ירוק), ואז משפרים את הקוד בביטחון, כי הבדיקות ישמרו עליכם. זה מכריח לחשוב מה בדיוק רוצים לפני שכותבים.

In TDD you write the test first, watch it fail (red), write the simplest code that passes (green), then improve the code with confidence, because the tests protect you. It forces you to decide exactly what you want before you write.

tdd.py
def test_slug():
    assert slug("The Little Prince") == "the-little-prince"
    assert slug("  Dune  ") == "dune"
    assert slug("Hello,  World!") == "hello-world"

def slug(text):
    words = "".join(c if c.isalnum() or c == " " else " " for c in text).split()
    return "-".join(words).lower()

test_slug()
print(slug("Harry Potter: The Philosopher's Stone"))
פלטOutput
harry-potter-the-philosopher-s-stone
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

TDD הוא כמו לכתוב את השאלות למבחן לפני שמלמדים: כך יודעים בדיוק מה התלמיד צריך לדעת בסוף.

TDD is like writing the exam questions before teaching: you know exactly what the student must know at the end.

טעות נפוצהCommon mistake

כותבים בדיקה שתלויה בבדיקה אחרת.

Writing a test that depends on another test.

tdd.py
shelf = []

def test_add():
    shelf.append("Dune")

def test_count():
    assert len(shelf) == 1, f"shelf has {len(shelf)} books: this test only passes if test_add ran first"

test_count()
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/tdd.py", line 9, in <module>
    test_count()
    ~~~~~~~~~~^^
  File "/Users/you/python-course/tdd.py", line 7, in test_count
    assert len(shelf) == 1, f"shelf has {len(shelf)} books: this test only passes if test_add ran first"
           ^^^^^^^^^^^^^^^
AssertionError: shelf has 0 books: this test only passes if test_add ran first
בעברית פשוטה: In plain words: AssertionError: shelf has 0 books: ...: בדיקות צריכות להיות עצמאיות. משתמשים ב-fixture שמכין מדף טרי לכל בדיקה.AssertionError: shelf has 0 books: ...: tests must be independent. Use a fixture that makes a fresh shelf for each test.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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