Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to mock the requests.get method using pytest-mock.
PyTest
def test_api_call(mocker): mock_get = mocker.patch('[1]') mock_get.return_value.status_code = 200 response = requests.get('http://example.com') assert response.status_code == 200
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mocking the wrong HTTP method like post or put.
Not specifying the full path to the method to mock.
✗ Incorrect
We use
mocker.patch('requests.get') to mock the get method from the requests library.2fill in blank
mediumComplete the code to assert that the mocked method was called exactly once.
PyTest
def test_api_call(mocker): mock_get = mocker.patch('requests.get') requests.get('http://example.com') mock_get.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
assert_called_once_with without arguments.Using
assert_called which only checks if called at least once.✗ Incorrect
The method
assert_called_once() checks that the mock was called exactly one time.3fill in blank
hardFix the error in the code to correctly mock a function get_data from my_module.
PyTest
def test_get_data(mocker): mock_func = mocker.patch('[1]') mock_func.return_value = {'key': 'value'} result = my_module.get_data() assert result == {'key': 'value'}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Patching only the function name without module.
Including parentheses in the patch string.
✗ Incorrect
The correct way is to patch the full path to the function as a string without calling it.
4fill in blank
hardFill both blanks to create a mock that returns True when called and assert it was called with argument 42.
PyTest
def test_mock_behavior(mocker): mock_func = mocker.patch('module.func') mock_func.return_value = [1] result = mock_func(42) assert result is True mock_func.[2](42)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
assert_called_once_with when multiple calls might happen.Setting
return_value to False by mistake.✗ Incorrect
Set
return_value to True and use assert_called_with(42) to check the call argument.5fill in blank
hardFill all three blanks to mock a method calculate in calc_module, set its return value to 10, call it with argument 5, and assert the call.
PyTest
def test_calculate(mocker): mock_calc = mocker.patch('[1]') mock_calc.return_value = [2] result = mock_calc([3]) assert result == 10 mock_calc.assert_called_once_with(5)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong module or method name in patch.
Setting return value or call argument incorrectly.
✗ Incorrect
Patch the full method path, set return value to 10, and call with 5.