Back to Repositories

Testing GitHub API Authentication Workflow in TheAlgorithms/Python

This test suite validates the GitHub API authentication and user information retrieval functionality in the fetch_github_info module. It ensures proper handling of API responses and authentication token verification through mocked HTTP requests.

Test Coverage Overview

The test coverage focuses on validating the GitHub API authentication flow and response parsing.

Key areas tested include:
  • Authentication token formatting and header inclusion
  • API endpoint URL validation
  • JSON response parsing and data extraction
  • User information field validation

Implementation Analysis

The testing approach utilizes Python’s monkeypatch fixture to mock the requests library’s GET method, enabling isolated testing of the API integration.

Implementation features:
  • Custom FakeResponse class to simulate HTTP responses
  • Mock response validation with specific assertions
  • Structured response data verification

Technical Details

Testing components:
  • pytest framework for test execution
  • monkeypatch fixture for dependency injection
  • requests library mocking
  • JSON response simulation
  • Assert statements for validation

Best Practices Demonstrated

The test implementation showcases several testing best practices for API integration testing.

Notable practices include:
  • Isolation of external dependencies through mocking
  • Explicit assertion messages
  • Comprehensive header validation
  • Proper response structure verification

thealgorithms/python

web_programming/test_fetch_github_info.py

            
import json

import requests

from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info


def test_fetch_github_info(monkeypatch):
    class FakeResponse:
        def __init__(self, content) -> None:
            assert isinstance(content, (bytes, str))
            self.content = content

        def json(self):
            return json.loads(self.content)

    def mock_response(*args, **kwargs):
        assert args[0] == AUTHENTICATED_USER_ENDPOINT
        assert "Authorization" in kwargs["headers"]
        assert kwargs["headers"]["Authorization"].startswith("token ")
        assert "Accept" in kwargs["headers"]
        return FakeResponse(b'{"login":"test","id":1}')

    monkeypatch.setattr(requests, "get", mock_response)
    result = fetch_github_info("token")
    assert result["login"] == "test"
    assert result["id"] == 1