10. Testing, Quality & Performance
Write fast, focused tests; keep code style consistent; reason about complexity.
Question: Why is testing important, and what is a common library used for it?
Answer: Testing ensures your code works as expected and prevents regressions. pytest
is the standard library for testing in Python due to its simple assert
syntax and powerful fixture system. Tools like ruff
or flake8
are used for linting to enforce code quality.
# test_example.py
def add(a: int, b: int) -> int:
return a + b
def test_add():
assert add(2, 3) == 5
Question: How to parametrize tests with
pytest
?
Answer: Use @pytest.mark.parametrize
to run the same test over multiple inputs/expected outputs.
import pytest
@pytest.mark.parametrize("a,b,expected", [(2,3,5), (0,0,0), (-1,1,0)])
def test_add_param(a, b, expected):
assert add(a, b) == expected
@patch("module_under_test.requests.get")
def test_fetch_user(get_mock):
get_mock.return_value.json.return_value = {"id": 1}
assert fetch_user(1)["id"] == 1
Question: How to mock dependencies?
Answer: Use unittest.mock
to replace objects during tests; prefer small, well-scoped patches.
from unittest.mock import patch
def fetch_user(id: int):
return requests.get(f"/users/{id}").json()
@patch("module_under_test.requests.get")
def test_fetch_user(get_mock):
get_mock.return_value.json.return_value = {"id": 1}
assert fetch_user(1)["id"] == 1
Question: What are fixtures in
pytest
?
Answer: Reusable setup/teardown logic injected into tests by name.
import pytest
@pytest.fixture
def sample_dir(tmp_path):
p = tmp_path / "data.txt"
p.write_text("hello", encoding="utf-8")
return tmp_path
def test_reads(sample_dir):
assert (sample_dir/"data.txt").read_text(encoding="utf-8") == "hello"
Question: What are the performance characteristics of lists and dictionaries?
Answer:
dict
/set
: Average O(1) (very fast and constant time) for adding, removing, and checking for an item.list
: O(1) for adding/removing at the end (append
,pop
). O(n) (slower, scales with list size) for adding/removing at the beginning or searching for an item (in
).
Question: What is a common pitfall with list multiplication?
Answer: When creating a list of lists, [[]] * 3
creates three references to the same inner list. Modifying one will modify them all. The correct way is to use a list comprehension: [[] for _ in range(3)]
.