0
0
PyTesttesting~10 mins

Why mocking isolates code under test in PyTest - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the mocking tool.

PyTest
from unittest.mock import [1]
Drag options to blanks, or click blank then click option'
Amock
BTestCase
CMagicMock
Dpatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'mock' instead of 'patch' which is the correct function to replace objects.
Importing 'TestCase' which is for test classes, not mocking.
2fill in blank
medium

Complete the code to mock the requests.get method in the test.

PyTest
@patch('[1]')
def test_fetch_data(mock_get):
    mock_get.return_value.status_code = 200
    assert fetch_data() == 'Success'
Drag options to blanks, or click blank then click option'
Arequests.get
Brequests.post
Cfetch_data
Dmock_get
Attempts:
3 left
💡 Hint
Common Mistakes
Mocking 'requests.post' which is not called in the function.
Mocking 'fetch_data' itself instead of its dependency.
3fill in blank
hard

Fix the error in the test by completing the mock patch target correctly.

PyTest
@patch('[1]')
def test_process_data(mock_func):
    mock_func.return_value = 42
    result = process_data()
    assert result == 42
Drag options to blanks, or click blank then click option'
Amodule_under_test.external_api_call
Bexternal_api_call
Cprocess_data.external_api_call
Dmodule_under_test.process_data
Attempts:
3 left
💡 Hint
Common Mistakes
Patching the global function name instead of the module's reference.
Patching the function under test itself.
4fill in blank
hard

Fill both blanks to mock a database call and check the return value.

PyTest
@patch('[1]')
def test_get_user(mock_db_call):
    mock_db_call.return_value = [2]
    user = get_user(1)
    assert user == {'id': 1, 'name': 'Alice'}
Drag options to blanks, or click blank then click option'
Adatabase.fetch_user
B{'id': 1, 'name': 'Alice'}
C{'id': 2, 'name': 'Bob'}
Ddatabase.get_user
Attempts:
3 left
💡 Hint
Common Mistakes
Mocking the wrong database function.
Returning a user dictionary that does not match the test assertion.
5fill in blank
hard

Fill all three blanks to mock a service call, set its return value, and assert the call count.

PyTest
@patch('[1]')
def test_service_call(mock_service):
    mock_service.return_value = [2]
    result = call_service()
    mock_service.[3]()
    assert result == 'OK'
Drag options to blanks, or click blank then click option'
Aservices.api_call
B'OK'
Cassert_called_once
Dassert_called_once_with
Attempts:
3 left
💡 Hint
Common Mistakes
Using assert_called_once_with without arguments when the call has none.
Setting the wrong return value that does not match the assertion.