Bird
Raised Fist0
PyTesttesting~10 mins

pytest-mock for enhanced mocking - Interactive Code Practice

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using pytest-mock in tests?
easy
A. To replace parts of code with mock objects during testing
B. To speed up test execution by skipping tests
C. To automatically generate test data
D. To format test output for better readability

Solution

  1. Step 1: Understand pytest-mock functionality

    pytest-mock is a plugin that helps replace parts of your code with mock objects during tests.
  2. Step 2: Identify the main use case

    This replacement allows you to control and verify behavior without running actual code parts.
  3. Final Answer:

    To replace parts of code with mock objects during testing -> Option A
  4. Quick Check:

    pytest-mock = mocking code parts [OK]
Hint: Remember pytest-mock is for replacing code parts with mocks [OK]
Common Mistakes:
  • Confusing mocking with test skipping
  • Thinking pytest-mock generates test data
  • Assuming pytest-mock formats output
2. Which of the following is the correct way to mock a function get_data in module my_module using pytest-mock?
easy
A. mocker.patch('my_module.get_data')
B. mocker.patch(get_data)
C. mocker.mock('my_module.get_data')
D. mocker.replace('my_module.get_data')

Solution

  1. Step 1: Recall pytest-mock patch syntax

    The correct syntax uses a string with the full path: mocker.patch('module.function').
  2. Step 2: Identify correct option

    mocker.patch('my_module.get_data') uses the correct string path format. Options A, B, and D use incorrect methods or arguments.
  3. Final Answer:

    mocker.patch('my_module.get_data') -> Option A
  4. Quick Check:

    Use string path in mocker.patch() [OK]
Hint: Use string 'module.function' in mocker.patch() [OK]
Common Mistakes:
  • Passing function object instead of string path
  • Using mocker.mock instead of patch
  • Using mocker.replace which doesn't exist
3. Given the code below, what will be the output of the test?
def fetch_data():
    return 'real data'

def test_fetch(mocker):
    mocker.patch('__main__.fetch_data', return_value='mocked data')
    result = fetch_data()
    assert result == 'mocked data'
    print(result)
medium
A. real data
B. Test fails with AssertionError
C. mocked data
D. None

Solution

  1. Step 1: Understand patch effect on fetch_data

    The patch replaces fetch_data to always return 'mocked data'.
  2. Step 2: Analyze test assertions and print

    The assertion checks for 'mocked data' and passes. The print outputs 'mocked data'.
  3. Final Answer:

    mocked data -> Option C
  4. Quick Check:

    Patched function returns mocked data [OK]
Hint: Patched functions return mocked values, not real ones [OK]
Common Mistakes:
  • Expecting original function output
  • Confusing patch target string
  • Assuming patch does not affect print
4. Identify the error in the following test code using pytest-mock:
def test_api_call(mocker):
    mocker.patch('api.call', return_value=200)
    response = api.call()
    assert response == 200
medium
A. The return_value should be a string, not an integer
B. assert statement syntax is wrong
C. mocker.patch should be called after the function call
D. The patch target string 'api.call' is incorrect or incomplete

Solution

  1. Step 1: Check patch target correctness

    The patch target 'api.call' must be the full import path. If 'api' is not imported or incomplete, patch fails.
  2. Step 2: Validate other parts

    Return value as integer is valid, patch before call is correct, and assert syntax is fine.
  3. Final Answer:

    The patch target string 'api.call' is incorrect or incomplete -> Option D
  4. Quick Check:

    Patch target must be full import path [OK]
Hint: Always use full import path in patch target string [OK]
Common Mistakes:
  • Using partial or wrong patch target strings
  • Thinking return_value must be string
  • Calling patch after function call
5. You want to test a function process_data() that calls fetch_from_api(). Using pytest-mock, how do you mock fetch_from_api to return different values on consecutive calls: first 'data1', then 'data2'?
hard
A. mocker.patch('module.fetch_from_api', return_value=['data1', 'data2'])
B. mocker.patch('module.fetch_from_api', side_effect=['data1', 'data2'])
C. mocker.patch('module.fetch_from_api', side_effect='data1', 'data2')
D. mocker.patch('module.fetch_from_api', return_values=['data1', 'data2'])

Solution

  1. Step 1: Understand side_effect usage

    To return different values on consecutive calls, use side_effect with a list of return values.
  2. Step 2: Identify correct syntax

    mocker.patch('module.fetch_from_api', side_effect=['data1', 'data2']) correctly uses side_effect=['data1', 'data2']. Options B, C, and D use incorrect parameters or syntax.
  3. Final Answer:

    mocker.patch('module.fetch_from_api', side_effect=['data1', 'data2']) -> Option B
  4. Quick Check:

    Use side_effect list for multiple return values [OK]
Hint: Use side_effect list to mock multiple return values [OK]
Common Mistakes:
  • Using return_value with a list instead of side_effect
  • Incorrect side_effect syntax with multiple arguments
  • Using non-existent return_values parameter
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard