When you run pytest, the test fails. What is the most likely reason?
medium
A. The test unexpectedly passed, causing failure due to strict=True
B. The xfail decorator was not applied correctly
C. The test failed because the assertion is incorrect
D. The test was skipped accidentally
Solution
Step 1: Check the assertion logic
The sum of [1, 2, 3] is 6, but the test asserts it equals 5, so the assertion fails.
Step 2: Understand strict=True effect
strict=True causes failure only if the test unexpectedly passes, but here the test fails as expected.
Final Answer:
The test failed because the assertion is incorrect -> Option C
Quick Check:
Wrong assertion causes failure, not strict=True [OK]
Hint: Check assertion values carefully; strict=True fails only on unexpected pass [OK]
Common Mistakes:
Assuming strict=True causes failure on test fail
Thinking test was skipped
Believing decorator syntax is wrong
5. You have a test that sometimes passes and sometimes fails due to a flaky external API. You want pytest to mark it as expected failure but fail the test run if it unexpectedly passes. Which is the best way to write this?
hard
A. @pytest.mark.xfail()
def test_api():
assert call_api() == 'OK'
B. @pytest.mark.skip(reason='Flaky API')
def test_api():
assert call_api() == 'OK'
C. @pytest.mark.xfail(strict=False, reason='Flaky API')
def test_api():
assert call_api() == 'OK'
D. @pytest.mark.xfail(strict=True, reason='Flaky API')
def test_api():
assert call_api() == 'OK'
Solution
Step 1: Identify requirement for strict checking
You want pytest to fail the test run if the test unexpectedly passes, so strict=True is needed.
Step 2: Use xfail with reason for clarity
Marking the test with @pytest.mark.xfail(strict=True, reason='Flaky API') clearly documents the expected failure and enforces strict checking.