חלקPart 3: קוד נקי ו-OOPClean code & OOP
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
בדיקות עם pytestTesting with pytest
assert, פונקציות בדיקה, fixtures ו-parametrize.
assert, test functions, fixtures and parametrize.
הנקודות החשובותKey points
- בדיקה ידנית = לשכוח משהוManual checking = forgetting something
- בדיקה אוטומטית רצה בשנייהAn automated test runs in a second
- קובץ בשם
test_*.pyA file namedtest_*.py - פונקציות בשם
test_*Functions namedtest_* - F במקום נקודהF instead of a dot
- pytest מראה את הערכים בפועלpytest shows the actual values
with pytest.raises(ValueError):with pytest.raises(ValueError):- מקרי קצה: ריק, אפס, גבולEdge cases: empty, zero, limit
- fixture: נתונים מוכנים לכל בדיקהfixture: ready data for each test
מונחיםTerms
- בדיקת יחידהunit test: פונקציה קטנה שבודקת חלק אחד בקוד: מריצה אותו עם קלט ידוע ובודקת עם assert שהתוצאה נכונה.A small function that checks one piece of code: runs it with known input and asserts the result is right.
- pytestpytest: הכלי הנפוץ ביותר להרצת בדיקות בפייתון. מוצא לבד קבצים
test_*.pyופונקציותtest_*.The most popular tool for running tests in Python. Findstest_*.pyfiles andtest_*functions by itself. - fixturefixture: פונקציה שמכינה נתונים לבדיקה (למשל מדף עם שלושה ספרים). בדיקה מקבלת אותה כפרמטר לפי השם.A function that prepares data for tests (e.g. a shelf with three books). A test receives it as a parameter by name.
- מקרה קצהedge case: קלט בגבולות: רשימה ריקה, אפס, מחרוזת ריקה, הערך הגדול ביותר. שם מתחבאים רוב הבאגים.Input at the limits: an empty list, zero, an empty string, the largest value. Most bugs hide there.
- רגרסיהregression: באג שתוקן וחזר. בדיקה שנכתבת לכל באג מונעת שהוא יחזור בשקט.A fixed bug that came back. A test written for each bug stops it returning silently.
- TDDTDD: Test-Driven Development: כותבים קודם בדיקה שנכשלת, אחר כך קוד שמעביר אותה, ואז מסדרים.Test-Driven Development: first write a failing test, then code that passes it, then tidy up.
Cheatsheet
למהWhy
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0pytestpytest
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)
קצוותEdges
import pytest
from shelf import add
def test_empty_title_is_rejected():
with pytest.raises(ValueError):
add([], " ", "Nobody")fixturesFixtures
import pytest
from shelf import add, find
@pytest.fixture
def shelf():
s = []TDDTDD
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()שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
AssertionError | בדיקה שתמיד עוברת, כי שכחו את ה-assert.A test that always passes because the assert was forgotten. | 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. |
AssertionError | משנים את הבדיקה כדי שתעבור, במקום לתקן את הקוד.Changing the test to make it pass, instead of fixing the code. | 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. |
AssertionError | כותבים בדיקה שתלויה בבדיקה אחרת.Writing a test that depends on another test. | 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. |