Test Overview
This test checks if our code correctly fetches user data from an external API and verifies the response contains expected user information.
Jump into concepts and practice - no test required
This test checks if our code correctly fetches user data from an external API and verifies the response contains expected user information.
import requests import pytest def fetch_user(user_id): response = requests.get(f"https://jsonplaceholder.typicode.com/users/{user_id}") response.raise_for_status() return response.json() def test_fetch_user(): user = fetch_user(1) assert user["id"] == 1 assert "name" in user assert user["email"].endswith(".biz")
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test runner initialized, no tests executed yet | — | PASS |
| 2 | Calls fetch_user(1) which sends GET request to https://jsonplaceholder.typicode.com/users/1 | HTTP request sent to external API | — | PASS |
| 3 | Receives HTTP 200 response with user JSON data | Response contains user data with id=1, name, email, etc. | — | PASS |
| 4 | Parses JSON response and returns user dictionary | User data available as Python dict | — | PASS |
| 5 | Asserts user["id"] == 1 | User id is 1 | Check user id matches requested id | PASS |
| 6 | Asserts "name" key exists in user dictionary | User data includes name field | Verify user has a name | PASS |
| 7 | Asserts user["email"] ends with '.biz' | User email is a string ending with '.biz' | Check email domain suffix | FAIL |
| 8 | Test completes successfully | All assertions passed, test finished | — | PASS |
get_data from module external_api using pytest's patch decorator?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')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'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?