0
0
PyTesttesting~10 mins

Testing with external services in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if our code correctly fetches user data from an external API and verifies the response contains expected user information.

Test Code - pytest
PyTest
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")
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsTest runner initialized, no tests executed yet-PASS
2Calls fetch_user(1) which sends GET request to https://jsonplaceholder.typicode.com/users/1HTTP request sent to external API-PASS
3Receives HTTP 200 response with user JSON dataResponse contains user data with id=1, name, email, etc.-PASS
4Parses JSON response and returns user dictionaryUser data available as Python dict-PASS
5Asserts user["id"] == 1User id is 1Check user id matches requested idPASS
6Asserts "name" key exists in user dictionaryUser data includes name fieldVerify user has a namePASS
7Asserts user["email"] ends with '.biz'User email is a string ending with '.biz'Check email domain suffixFAIL
8Test completes successfullyAll assertions passed, test finished-PASS
Failure Scenario
Failing Condition: External API is down or returns error status
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the user data?
AUser id is 2 and email ends with '.com'
BUser id is 1, name exists, and email ends with '.biz'
CUser has a phone number and address
DUser data is empty
Key Result
When testing code that calls external services, it is best to mock those calls to avoid flaky tests caused by network issues or service downtime.