Challenge - 5 Problems
pytest-mock Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a pytest-mock patch usage
What is the output of this pytest test when run with pytest-mock?
PyTest
import requests def fetch_data(): response = requests.get('https://api.example.com/data') return response.status_code def test_fetch_data(mocker): mock_get = mocker.patch('requests.get') mock_get.return_value.status_code = 404 result = fetch_data() print(result)
Attempts:
2 left
💡 Hint
The mock replaces requests.get and sets the status_code attribute.
✗ Incorrect
The mocker.patch replaces requests.get with a mock object. Setting return_value.status_code to 404 means fetch_data returns 404.
❓ assertion
intermediate1:30remaining
Correct assertion to verify mock call count
Which assertion correctly verifies that the mocked function was called exactly twice?
PyTest
def test_calls(mocker): mock_func = mocker.Mock() mock_func() mock_func() # Which assertion below is correct?
Attempts:
2 left
💡 Hint
Check the attribute that counts calls on a mock object.
✗ Incorrect
The call_count attribute holds the number of times the mock was called. It is an integer, so assert mock_func.call_count == 2 is correct.
🔧 Debug
advanced2:00remaining
Identify the error in mock patching
Why does this test raise an AttributeError when run?
PyTest
import mymodule def test_func(mocker): mocker.patch('mymodule.nonexistent_function') mymodule.nonexistent_function()
Attempts:
2 left
💡 Hint
Check if the target to patch exists in the module.
✗ Incorrect
Patching a non-existing attribute causes AttributeError because the patch target must exist.
❓ framework
advanced1:30remaining
pytest-mock fixture usage in test functions
Which statement about the pytest-mock fixture 'mocker' is true?
Attempts:
2 left
💡 Hint
Think about how pytest fixtures are injected.
✗ Incorrect
pytest fixtures like 'mocker' are injected by including them as parameters in test functions.
🧠 Conceptual
expert2:30remaining
Best practice for mocking external API calls with pytest-mock
Which approach best ensures tests using pytest-mock remain reliable and isolated when mocking external API calls?
Attempts:
2 left
💡 Hint
Consider test isolation and minimizing side effects.
✗ Incorrect
Patching the function in the module under test avoids affecting other tests and keeps mocks focused and reliable.