0
0
PyTesttesting~20 mins

pytest-mock for enhanced mocking - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
pytest-mock Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A404
B200
CAttributeError
DNone
Attempts:
2 left
💡 Hint
The mock replaces requests.get and sets the status_code attribute.
assertion
intermediate
1: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?
Aassert mock_func.call_count() == 2
Bassert mock_func.called == 2
Cassert mock_func.call_args == 2
Dassert mock_func.call_count == 2
Attempts:
2 left
💡 Hint
Check the attribute that counts calls on a mock object.
🔧 Debug
advanced
2: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()
AAttributeError because 'nonexistent_function' does not exist in mymodule
BSyntaxError due to missing colon
CTypeError because patch requires a callable
DNo error, test passes
Attempts:
2 left
💡 Hint
Check if the target to patch exists in the module.
framework
advanced
1:30remaining
pytest-mock fixture usage in test functions
Which statement about the pytest-mock fixture 'mocker' is true?
AThe 'mocker' fixture automatically patches all functions without explicit use
BThe 'mocker' fixture must be included as a test function argument to use it
CThe 'mocker' fixture can only patch functions in the standard library
DThe 'mocker' fixture requires manual import in each test file
Attempts:
2 left
💡 Hint
Think about how pytest fixtures are injected.
🧠 Conceptual
expert
2: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?
APatch the external API URL string to a local server address
BAvoid mocking and always make real HTTP requests during tests for accuracy
CPatch the exact function that makes the HTTP request in the module under test, not the external library directly
DPatch the external library's HTTP request function globally in conftest.py for all tests
Attempts:
2 left
💡 Hint
Consider test isolation and minimizing side effects.