Bird
Raised Fist0
PyTesttesting~20 mins

unittest.mock.patch in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Patch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of patching a function with unittest.mock.patch
What is the output of this pytest test when the requests.get method is patched to return a mock with status_code=200?
PyTest
import requests
from unittest.mock import patch

def fetch_status():
    response = requests.get('http://example.com')
    return response.status_code

def test_fetch_status():
    with patch('requests.get') as mock_get:
        mock_get.return_value.status_code = 200
        result = fetch_status()
        assert result == 200
        print(result)
AAttributeError
B404
CNone
D200
Attempts:
2 left
💡 Hint
The patch replaces the requests.get call with a mock object whose status_code attribute is set to 200.
❓ assertion
intermediate
2:00remaining
Correct assertion to verify a patched method call
Which assertion correctly verifies that the patched open method was called exactly once with the argument 'file.txt'?
PyTest
from unittest.mock import patch

def test_file_open():
    with patch('builtins.open') as mock_open:
        open('file.txt')
        # Which assertion is correct here?
Amock_open.assert_called_once_with('file.txt')
Bmock_open.assert_called_with('file.txt', 'r')
Cmock_open.assert_called_once('file.txt')
Dmock_open.assert_called('file.txt')
Attempts:
2 left
💡 Hint
Use the method that checks the call count and arguments exactly once.
🔧 Debug
advanced
2:00remaining
Identify the error in patching a method
What error will occur when running this test code that patches module.Class.method incorrectly?
PyTest
from unittest.mock import patch
import module

def test_method():
    with patch('Class.method') as mock_method:
        module.Class().method()
        mock_method.assert_called_once()
ARuntimeError
BModuleNotFoundError
CAttributeError
DNo error, test passes
Attempts:
2 left
💡 Hint
The patch target string must include the full import path.
🧠 Conceptual
advanced
2:00remaining
Effect of patching with autospec=True
What is the main effect of using autospec=True in unittest.mock.patch?
AThe mock will automatically reset after each test
BThe mock will only allow attributes and methods that exist on the original object
CThe mock will record all calls without any restrictions
DThe mock will patch all instances of the object globally
Attempts:
2 left
💡 Hint
Think about how autospec helps catch incorrect method calls.
❓ framework
expert
3:00remaining
Correct use of patch as a decorator in pytest
Which pytest test function correctly patches os.remove using unittest.mock.patch as a decorator and verifies it was called once?
PyTest
import os
from unittest.mock import patch

def delete_file(filename):
    os.remove(filename)

# Choose the correct test function:
A
@patch('os.remove')
def test_delete_file(mock_remove):
    delete_file('temp.txt')
    mock_remove.assert_called_once_with('temp.txt')
B
@patch('os.remove')
def test_delete_file():
    delete_file('temp.txt')
    os.remove.assert_called_once_with('temp.txt')
C
def test_delete_file():
    with patch('os.remove') as mock_remove:
        delete_file('temp.txt')
    mock_remove.assert_called_once_with('temp.txt')
D
@patch('os.remove')
def test_delete_file(mock_remove):
    delete_file('temp.txt')
    mock_remove.assert_called_once()
Attempts:
2 left
💡 Hint
Remember the patched function is passed as an argument to the test when using the decorator.

Practice

(1/5)
1. What is the main purpose of using unittest.mock.patch in pytest?
easy
A. To automatically generate test data for functions
B. To speed up the execution of tests by skipping them
C. To check the syntax of the code before running tests
D. To replace parts of the code temporarily during tests to control behavior

Solution

  1. Step 1: Understand the role of patch

    unittest.mock.patch is used to replace parts of your code temporarily during tests, so you can control how those parts behave without running the real code.
  2. Step 2: Compare with other options

    The other options describe generating test data, speeding up tests by skipping them, or checking syntax, none of which patch performs.
  3. Final Answer:

    To replace parts of the code temporarily during tests to control behavior -> Option D
  4. Quick Check:

    Patch replaces code parts temporarily [OK]
Hint: Patch replaces code parts temporarily during tests [OK]
Common Mistakes:
  • Thinking patch speeds up tests by skipping them
  • Confusing patch with test data generation
  • Believing patch checks code syntax
2. Which of the following is the correct syntax to patch the function requests.get using a decorator in pytest?
easy
A. @patch(requests.get)
B. @patch('requests.get()')
C. @patch('requests.get')
D. @patch('requests->get')

Solution

  1. Step 1: Understand patch decorator syntax

    The patch decorator requires the target as a string with the full path, like 'module.function'. So, '@patch('requests.get')' is correct.
  2. Step 2: Identify incorrect syntax

    @patch(requests.get) misses quotes around the target, @patch('requests.get()') adds incorrect parentheses, and @patch('requests->get') uses an invalid arrow symbol.
  3. Final Answer:

    @patch('requests.get') -> Option C
  4. Quick Check:

    Patch target must be a string path [OK]
Hint: Patch target is always a string path in quotes [OK]
Common Mistakes:
  • Omitting quotes around the target string
  • Adding parentheses after the function name
  • Using invalid symbols like arrows in the target
3. Given the following code, what will be printed when the test runs?
import requests
from unittest.mock import patch

def fetch_data():
    return requests.get('http://example.com').status_code

@patch('requests.get')
def test_fetch(mock_get):
    mock_get.return_value.status_code = 404
    print(fetch_data())

if __name__ == '__main__':
    test_fetch()
medium
A. 404
B. 200
C. None
D. AttributeError

Solution

  1. Step 1: Understand patch effect on requests.get

    The decorator replaces requests.get with a mock object. The mock's return_value.status_code is set to 404.
  2. Step 2: Trace fetch_data call

    When fetch_data() calls requests.get, it gets the mock, whose status_code is 404, so it returns 404.
  3. Final Answer:

    404 -> Option A
  4. Quick Check:

    Mock return_value.status_code = 404 means fetch_data() returns 404 [OK]
Hint: Mock return_value sets the function's return object [OK]
Common Mistakes:
  • Expecting real HTTP status 200 instead of mocked 404
  • Confusing mock object with None
  • Thinking patch causes an error here
4. What is wrong with this test code using patch?
from unittest.mock import patch

def test_api_call():
    with patch('api.requests.get') as mock_get:
        mock_get.status_code = 200
        response = api_call()
        assert response == 'success'
medium
A. The assert statement syntax is incorrect
B. mock_get.status_code should be set on mock_get.return_value, not mock_get
C. The patch should be used as a decorator, not a context manager
D. The patch target string is missing quotes

Solution

  1. Step 1: Understand mock object structure

    When patching a function, the mock object replaces the function. The function call returns mock_get.return_value. So, attributes like status_code must be set on mock_get.return_value.
  2. Step 2: Identify the error in code

    The code sets mock_get.status_code = 200 which is incorrect; it should be mock_get.return_value.status_code = 200.
  3. Final Answer:

    mock_get.status_code should be set on mock_get.return_value, not mock_get -> Option B
  4. Quick Check:

    Set attributes on return_value, not mock function [OK]
Hint: Set return_value attributes, not mock function attributes [OK]
Common Mistakes:
  • Setting attributes directly on the mock function
  • Forgetting quotes around patch target
  • Thinking patch must be decorator only
  • Miswriting assert syntax
5. You want to test a function process_data() that calls fetch_from_api() internally. You want to patch fetch_from_api only during the test to return a fixed value. Which is the best way to do this using unittest.mock.patch?
hard
A. Use @patch('module.fetch_from_api') decorator on the test function and set mock_fetch.return_value
B. Replace fetch_from_api globally in the module before running tests
C. Modify fetch_from_api code to return fixed value during tests
D. Call fetch_from_api directly in the test without patching

Solution

  1. Step 1: Understand patch scope and usage

    Using @patch('module.fetch_from_api') decorator temporarily replaces fetch_from_api only during the test, allowing control over its return value.
  2. Step 2: Evaluate other options

    Replace fetch_from_api globally in the module before running tests changes global code, which is unsafe. Modify fetch_from_api code to return fixed value during tests modifies production code, which is bad practice. Call fetch_from_api directly in the test without patching does not isolate the test.
  3. Final Answer:

    Use @patch('module.fetch_from_api') decorator on the test function and set mock_fetch.return_value -> Option A
  4. Quick Check:

    Patch with decorator for safe, temporary replacement [OK]
Hint: Patch with decorator for temporary, safe replacement [OK]
Common Mistakes:
  • Changing global code instead of patching
  • Modifying production code for tests
  • Not patching and calling real function
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