5. You want to ensure your function process_data() raises a KeyError when a required key is missing in input. Which pytest test best ensures robustness by checking this error path?
hard
A. def test_process_data_keyerror():
with pytest.raises(KeyError):
process_data({'name': 'Alice'})
B. def test_process_data_keyerror():
assert process_data({'name': 'Alice'}) == None
C. def test_process_data_keyerror():
try:
process_data({'name': 'Alice'})
except KeyError:
pass
D. def test_process_data_keyerror():
result = process_data({'name': 'Alice'})
assert result != None
Solution
Step 1: Understand the goal to test error path
We want to confirm process_data raises KeyError when key missing.
Step 2: Identify pytest way to check expected error
Using 'with pytest.raises(KeyError):' ensures test fails if error not raised.
Step 3: Evaluate options
def test_process_data_keyerror():
with pytest.raises(KeyError):
process_data({'name': 'Alice'}) uses pytest.raises correctly; others do not check error properly.
Final Answer:
def test_process_data_keyerror():\n with pytest.raises(KeyError):\n process_data({'name': 'Alice'}) -> Option A
Quick Check:
Use pytest.raises to check error path = A [OK]
Hint: Use pytest.raises to confirm expected errors for robustness [OK]
Common Mistakes:
Using assert instead of pytest.raises for error checking
Catching error but not failing test if missing
Checking result instead of error raised
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.