0
0
PyTesttesting~10 mins

pytest-mock for enhanced mocking - Interactive Code Practice

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

Complete 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'
Arequests.post
Brequests.get
Crequests.put
Drequests.delete
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.
2fill in blank
medium

Complete 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'
Aassert_called_once
Bassert_called_once_with
Cassert_called
Dassert_not_called
Attempts:
3 left
💡 Hint
Common Mistakes
Using assert_called_once_with without arguments.
Using assert_called which only checks if called at least once.
3fill in blank
hard

Fix 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'
Amy_module.getdata
Bget_data
Cmy_module.get_data
Dmy_module.get_data()
Attempts:
3 left
💡 Hint
Common Mistakes
Patching only the function name without module.
Including parentheses in the patch string.
4fill in blank
hard

Fill 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'
ATrue
Bassert_called_once_with
Cassert_called_with
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using assert_called_once_with when multiple calls might happen.
Setting return_value to False by mistake.
5fill in blank
hard

Fill 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'
Acalc_module.calculate
B10
C5
Dcalc_module.calc
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong module or method name in patch.
Setting return value or call argument incorrectly.