0
0
PyTesttesting~10 mins

API client testing in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the API client correctly fetches user data from a web service and verifies the response content.

Test Code - pytest
PyTest
import requests
import pytest

def get_user(user_id):
    response = requests.get(f"https://jsonplaceholder.typicode.com/users/{user_id}")
    response.raise_for_status()
    return response.json()


def test_get_user():
    user = get_user(1)
    assert user["id"] == 1
    assert user["username"] == "Bret"
    assert "email" in user
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls get_user(1) which sends GET request to https://jsonplaceholder.typicode.com/users/1HTTP request sent to API server-PASS
3Receives HTTP 200 OK response with JSON user dataResponse JSON: {"id":1,"username":"Bret","email":"Sincere@april.biz", ...}-PASS
4Asserts user["id"] == 1User data loaded in memoryCheck if user id equals 1PASS
5Asserts user["username"] == "Bret"User data loaded in memoryCheck if username is 'Bret'PASS
6Asserts "email" key exists in user dataUser data loaded in memoryCheck if 'email' field is presentPASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: API returns 404 Not Found or user data is missing expected fields
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the API response?
AThe user id is 1 and username is 'Bret'
BThe API returns a 500 server error
CThe user has no email field
DThe API response is empty
Key Result
Always verify both the HTTP status and the content of the API response to ensure the client handles data correctly.