Bird
Raised Fist0
PyTesttesting~20 mins

Testing with external services in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
External Service Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of pytest test with mocked external API call
What is the output of this pytest test when the external API call is mocked to return status code 200?
PyTest
import requests
import pytest
from unittest.mock import patch

def fetch_data():
    response = requests.get('https://api.example.com/data')
    if response.status_code == 200:
        return response.json()
    return None

@patch('requests.get')
def test_fetch_data(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json = lambda: {'key': 'value'}
    result = fetch_data()
    assert result == {'key': 'value'}
    print('Test passed')
ATest passed
BTypeError
CAssertionError
DNo output
Attempts:
2 left
💡 Hint
Consider what the mock object returns for status_code and json method.
assertion
intermediate
1:30remaining
Correct assertion for API response content
Which assertion correctly verifies that the API response contains a 'user' key with a non-empty dictionary?
PyTest
response = {'user': {'id': 1, 'name': 'Alice'}}
Aassert 'user' in response and isinstance(response['user'], dict) and response['user']
Bassert response['user'] != None
Cassert response['user'] is not None and len(response['user']) > 0
Dassert response.get('user') == {}
Attempts:
2 left
💡 Hint
Check for key existence, type, and non-empty dictionary.
🔧 Debug
advanced
2:00remaining
Identify the cause of test failure with external service timeout
Given this pytest test, why does it fail with a TimeoutError?
PyTest
import requests
import pytest

def get_data():
    return requests.get('https://slow.api.example.com/data', timeout=1).json()

def test_get_data():
    data = get_data()
    assert 'result' in data
AThe requests.get call is missing required headers causing a connection error
BThe external API is too slow and exceeds the 1 second timeout causing TimeoutError
CThe test assertion is incorrect and causes AssertionError
DThe function get_data returns None causing TypeError
Attempts:
2 left
💡 Hint
Consider the timeout parameter in requests.get and the error type.
framework
advanced
1:30remaining
Best pytest fixture scope for external service setup
Which pytest fixture scope is best to minimize external service setup overhead when running multiple tests that share the same service state?
Amodule - runs setup once per module
Bfunction - runs setup before each test function
Csession - runs setup once per test session
Dclass - runs setup once per test class
Attempts:
2 left
💡 Hint
Think about how often you want to initialize the external service for all tests.
🧠 Conceptual
expert
2:30remaining
Handling flaky tests caused by external service instability
Which strategy is most effective to handle flaky tests caused by intermittent failures of an external service?
ARun the tests only manually when needed
BIgnore the flaky tests to avoid blocking the pipeline
CIncrease the test timeout indefinitely to wait for the service
DUse test retries with exponential backoff and mock the external service in CI
Attempts:
2 left
💡 Hint
Consider reliability and automation best practices.

Practice

(1/5)
1. What is the main reason to use mocking when testing with external services in pytest?
easy
A. To avoid calling the real external service and make tests faster
B. To increase the number of real API calls during testing
C. To make tests dependent on internet speed
D. To test the external service itself

Solution

  1. Step 1: Understand the role of mocking in tests

    Mocking replaces real external calls with fake ones to avoid delays and failures.
  2. Step 2: Identify the benefit of mocking external services

    Mocking makes tests faster and more reliable by not depending on real services.
  3. Final Answer:

    To avoid calling the real external service and make tests faster -> Option A
  4. Quick Check:

    Mocking speeds up tests by faking external calls [OK]
Hint: Mock external calls to speed tests and avoid failures [OK]
Common Mistakes:
  • Thinking mocking increases real API calls
  • Believing tests should depend on internet speed
  • Confusing testing external service with testing your code
2. Which of the following is the correct way to mock a function get_data from module external_api using pytest's patch decorator?
easy
A. @patch('external_api.get_data')
B. @patch('get_data.external_api')
C. @patch('external_api->get_data')
D. @patch('external_api.getData')

Solution

  1. Step 1: Recall correct patch syntax

    The patch decorator requires the full import path as a string: 'module.function'.
  2. Step 2: Match the correct option

    @patch('external_api.get_data') uses 'external_api.get_data' which is the correct format and case-sensitive.
  3. Final Answer:

    @patch('external_api.get_data') -> Option A
  4. Quick Check:

    patch('module.function') syntax is correct [OK]
Hint: Use 'module.function' string in patch decorator [OK]
Common Mistakes:
  • Swapping module and function order
  • Using wrong separators like '->'
  • Incorrect function name casing
3. Given the following pytest test code, what will be the output when running the test?
from unittest.mock import patch
import requests

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

@patch('requests.get')
def test_fetch_status(mock_get):
    mock_get.return_value.status_code = 200
    assert fetch_status() == 200
    print('Test passed')
medium
A. TypeError
B. AssertionError
C. Test passed
D. No output

Solution

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

    The patch replaces requests.get with a mock that returns an object with status_code 200.
  2. Step 2: Check assertion and print statement

    fetch_status() returns 200, matching the assertion, so 'Test passed' is printed.
  3. Final Answer:

    Test passed -> Option C
  4. Quick Check:

    Mocked return_value.status_code = 200 makes test pass [OK]
Hint: Mock return_value to control function output [OK]
Common Mistakes:
  • Forgetting to set return_value.status_code
  • Expecting real HTTP call instead of mock
  • Missing print output due to assertion failure
4. Identify the error in the following pytest test that mocks an external service call:
from unittest.mock import patch
import myservice

@patch('myservice.call_api')
def test_api(mock_call):
    mock_call.return_value = {'status': 'ok'}
    result = myservice.call_api()
    assert result.status == 'ok'
medium
A. The patch decorator is missing parentheses
B. The assertion should use result['status'] instead of result.status
C. mock_call.return_value should be a string, not a dict
D. The test function is missing a return statement

Solution

  1. Step 1: Analyze the mocked return value type

    The mock returns a dictionary {'status': 'ok'}, so result is a dict.
  2. Step 2: Check the assertion syntax

    Accessing dict keys requires bracket notation, not dot notation; result.status causes AttributeError.
  3. Final Answer:

    The assertion should use result['status'] instead of result.status -> Option B
  4. Quick Check:

    Dict keys need brackets, not dot notation [OK]
Hint: Use brackets for dict keys in assertions [OK]
Common Mistakes:
  • Using dot notation on dicts
  • Forgetting parentheses in patch decorator (not here)
  • Expecting return_value must be string always
5. You want to test a function process_data() that calls an external API fetch_data(). The API sometimes returns null. How should you mock fetch_data in pytest to test process_data handles null correctly?
hard
A. Do not mock fetch_data; test process_data only with real data
B. Call the real fetch_data to see if it returns null
C. Mock fetch_data to always raise an exception
D. Use patch to make fetch_data return null and assert process_data handles it

Solution

  1. Step 1: Understand the need to test null handling

    Since fetch_data can return null, tests must simulate this to check process_data behavior.
  2. Step 2: Use patch to mock fetch_data returning null

    Mocking fetch_data to return null allows controlled testing of process_data's handling of that case.
  3. Final Answer:

    Use patch to make fetch_data return null and assert process_data handles it -> Option D
  4. Quick Check:

    Mock null return to test edge case handling [OK]
Hint: Mock edge cases like null to test error handling [OK]
Common Mistakes:
  • Calling real external API in tests
  • Mocking only success cases, ignoring null
  • Ignoring exceptions instead of testing them