L5·Intermediate/Advanced
🧪Testing with pytest & unittest
assert-based tests, fixtures, parametrize and mocking.
pytestunittestmockTDD
§ 1Why test
Tests prove code works and catch regressions when you change it later. Interviewers love candidates who mention edge cases and tests.
§ 2pytest
Write functions named test_*, use plain assert. @pytest.mark.parametrize runs one test with many inputs; fixtures provide shared setup.
1import pytest2@pytest.mark.parametrize("a,b,out", [(1, 2, 3), (0, 0, 0)])3def test_add(a, b, out):4 assert add(a, b) == out§ 3Mocking
unittest.mock.patch replaces slow or external things (APIs, time, DB) with fakes so tests run fast and deterministic.
Worked example
1import unittest23def is_even(n):4 return n % 2 == 056class TestEven(unittest.TestCase):7 def test_even(self):8 self.assertTrue(is_even(4))9 def test_odd(self):10 self.assertFalse(is_even(7))11 def test_zero(self):12 self.assertTrue(is_even(0))1314unittest.main(argv=["x"], exit=False, verbosity=2)Try it live · Python runs in your browser
Loading playground…
Checkpoint quiz
Question 1 / 2
pytest discovers functions named:
Lesson test
Take an 8-question test on “Testing with pytest & unittest” — concepts, output prediction, bug spotting and interview questions.