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

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. איזה קובץ pytest ימצא?Which file will pytest find?

2. מה הבעיה בבדיקה?What's wrong with this test?
python
def test_total():
    total([1, 2]) == 3

3. מה זה fixture?What is a fixture?

תרגיליםExercises

תרגילExercise 1

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

נתונה 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.

איך הפלט אמור להיראות?What should the output look like?
ok
main.py
רמזHint 1: assert is_even(4)assert is_even(4)
רמזHint 2: לאי-זוגי: assert not is_even(7).For odd: assert not is_even(7).
לפתרוןSolution
תרגילExercise 2

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

ל-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.

איך הפלט אמור להיראות?What should the output look like?
ok
main.py
רמזHint 1: assert average([]) == 0assert average([]) == 0
רמזHint 2: בפונקציה: if not nums: return 0.In the function: if not nums: return 0.
לפתרוןSolution
תרגילExercise 3

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

כתבו 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".

איך הפלט אמור להיראות?What should the output look like?
ok
main.py
רמזHint 1: with pytest.raises(ValueError): לכל מקרה בנפרד.with pytest.raises(ValueError): for each case separately.
רמזHint 2: או לולאה: for bad in [...]: ובתוכה with.Or a loop: for bad in [...]: with the with inside.
לפתרוןSolution
תרגילExercise 4

parametrizeparametrize

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
ok
main.py
רמזHint 1: round((f - 32) * 5 / 9, 1)round((f - 32) * 5 / 9, 1)
רמזHint 2: def test_to_celsius(f, c): assert to_celsius(f) == cdef test_to_celsius(f, c): assert to_celsius(f) == c
לפתרוןSolution
תרגילExercise 5

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

פרויקט מלווהCompanion project

נתונות 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.

איך הפלט אמור להיראות?What should the output look like?
5 tests passed
test_shelf.py
רמזHint 1: כל בדיקה מתחילה במדף ריק משלה: shelf = [].Each test starts with its own empty shelf: shelf = [].
רמזHint 2: הלולאה בסוף מוצאת לבד כל פונקציה ששמה מתחיל ב-test_.The loop at the end finds every function starting with test_.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

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

כתבו קודם 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.

איך הפלט אמור להיראות?What should the output look like?
4
main.py
רמזHint 1: any(c.isupper() for c in pw)any(c.isupper() for c in pw)
רמזHint 2: True נספר כ-1 בסכום: sum([...]).True counts as 1 in a sum: sum([...]).
לפתרוןSolution
אתגרChallenge 2

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
2 3
main.py
רמזHint 1: עטפו כל הרצה ב-try/except AssertionError.Wrap each run in try/except AssertionError.
רמזHint 2: על הפונקציה האמיתית: אם נכשל, raise ValueError.On the real function: if it fails, raise ValueError.
לפתרוןSolution

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