CodeBlanks Logo Icon CodeBlanks

Summary - Pytest

Combine fixture, parametrize and monkeypatch to write a calculator test.

Summary - Pytest

This group covered the core tools of pytest. assert checks conditions; fixture injects setup code into tests; parametrize runs the same test with many inputs; monkeypatch changes values temporarily.

The final task combines parametrize with a helper function: you'll test a filter function with several inputs.

Practice filter test with parametrize

The function keep_positive(nums) returns [n for n in nums if n > 0]. Decorate test_keep_positive with @pytest.mark.parametrize; first string "nums,expected", second argument [([1, -2, 3], [1, 3]), ([-1, -2], [])]. The test body contains assert keep_positive(nums) == expected. End with test_keep_positive([1, -2, 3], [1, 3]) and print("ok").

Starter code

main.py
import pytest

# keep_positive(nums): list items where n > 0
# test_keep_positive: use parametrize with two cases
# body compares keep_positive(nums) with expected
# finally test_keep_positive([1, -2, 3], [1, 3]) and print("ok")

Sample solution

main.py
import pytest

def keep_positive(nums):
    return [n for n in nums if n > 0]

@pytest.mark.parametrize("nums,expected", [([1, -2, 3], [1, 3]), ([-1, -2], [])])
def test_keep_positive(nums, expected):
    assert keep_positive(nums) == expected

test_keep_positive([1, -2, 3], [1, 3])
print("ok")

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the best way to test a function with many inputs?

  • Copy and paste the same test manually
  • Use @pytest.mark.parametrize Correct answer
  • Generate random data inside the test
  • Run with only one fixed input

Explanation: parametrize avoids repetition and provides data-driven testing.

2 Complete the summary parametrize

Question
import pytest

@____("nums,expected", [([1, 2, 3], 6), ([10, 20], 30)])
def test_sum(nums, expected):
    assert sum(nums) == expected
Answer
import pytest

@pytest.mark.parametrize("nums,expected", [([1, 2, 3], 6), ([10, 20], 30)])
def test_sum(nums, expected):
    assert sum(nums) == expected

Explanation: The pytest.mark.parametrize decorator repeats the test with a data list.

3 Match the group tools

Term Meaning
assert Checks a condition
fixture Injects setup
parametrize Data-driven repeat
monkeypatch Temporary change

All lessons in Advanced