Question presented to candidate: "Say you have just written a pricing function and a small shopping-cart class. How would you test them in Python? Show me what a test looks like in unittest and in pytest, how you give each test a clean setup, how you test errors, and how you avoid calling a real external API."
What a strong answer should cover:
- unittest is the standard library's xUnit framework: subclass
unittest.TestCase, name methodstest_*, useself.assertEqual/assertRaises, andsetUp/tearDownaround every test; run withpython -m unittest discover. - pytest is the third-party de facto standard: plain functions and the plain
assertstatement (pytest rewrites asserts to print both sides on failure), and it also runs existing unittest tests unchanged. - Fixtures: pytest injects them by parameter name,
yieldsplits setup from teardown, built-ins such astmp_pathandmonkeypatch;@pytest.mark.parametrizeturns one test into a table of cases (unittest's nearest issubTest). - Testing failure paths:
assertRaises/pytest.raises(..., match=...), and approximate float comparison (assertAlmostEqual,pytest.approx). - Test doubles with
unittest.mock:Mock,return_value,side_effect,assert_called_once_with,create_autospec, and patching where the name is looked up, not where it is defined. - Good test hygiene: each test independent, fast and deterministic; no real network, clock or randomness without control.
Clarifying questions expected:
- Is the project already on unittest or pytest, and is adding a dev dependency acceptable?
- Which dependencies are external (HTTP APIs, databases, the clock) and need to be faked?
Code / implementation expected: Yes โ a few real tests in either framework, including one error case and one mocked dependency.