How to Mock GCP Cloud Functions HTTP Events in Python

Simulate a GCP Cloud Functions HTTP event with a Python mock handler that constructs a realistic event payload and returns a JSON response.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

45 lines
Python 3.9+
import json
from datetime import datetime, timezone


def mock_http_event(data):
    """Simulate a GCP Cloud Function HTTP event."""
    event = {
        "event_id": "mock-event-12345",
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "event_type": "google.cloud.functions.http",
        "resource": "projects/demo-project/locations/us-central1/functions/mock-function",
        "data": {
            "body": data.get("body", {}),
            "headers": data.get("headers", {}),
            "method": data.get("method", "GET"),
            "query_params": data.get("query", {}),
            "path": data.get("path", "/")
        }
    }
    return event


def mock_cloud_function(request_data):
    """Simulate a Cloud Function handler."""
    event = mock_http_event(request_data)

    # Simulate processing the event
    response = {
        "status": "success",
        "message": "Mock GCP Cloud Function executed",
        "received_event": event,
        "processed_at": datetime.now(timezone.utc).isoformat()
    }
    return json.dumps(response, indent=2)


if __name__ == "__main__":
    sample_request = {
        "method": "POST",
        "path": "/api/data",
        "headers": {"Content-Type": "application/json"},
        "query": {"param1": "value1"},
        "body": {"key": "value", "count": 42}
    }
    print(mock_cloud_function(sample_request))

Output

stdout
{
  "status": "success",
  "message": "Mock GCP Cloud Function executed",
  "received_event": {
    "event_id": "mock-event-12345",
    "timestamp": "2025-03-15T12:34:56.789012+00:00",
    "event_type": "google.cloud.functions.http",
    "resource": "projects/demo-project/locations/us-central1/functions/mock-function",
    "data": {
      "body": {
        "key": "value",
        "count": 42
      },
      "headers": {
        "Content-Type": "application/json"
      },
      "method": "POST",
      "query_params": {
        "param1": "value1"
      },
      "path": "/api/data"
    }
  },
  "processed_at": "2025-03-15T12:34:56.789123+00:00"
}

How it works

The mock_http_event function builds a dictionary that mirrors the structure of a real GCP Cloud Functions HTTP event, including event_id, timestamp, resource, and nested request data. json.dumps with indent=2 produces a human-readable JSON string for the response. The code uses datetime.now(timezone.utc).isoformat() to generate UTC timestamps, matching Cloud Functions behavior. This mock is useful for testing handlers locally without deploying to GCP or triggering actual HTTP requests.

Common mistakes

  • Forgetting to use timezone-aware datetimes in UTC, which can cause timestamp format issues.
  • Overwriting the request's HTTP method or path instead of reading them from the input data.
  • Not including all typical event fields (like event_id or resource), breaking downstream code that expects them.

Variations

  1. Use `unittest.mock` or `pytest` fixtures to patch the handler's dependencies instead of a full event mock.
  2. Build the event directly from a Flask or FastAPI test client request to more closely mimic real HTTP behavior.

Real-world use cases

  • Unit testing a Cloud Function handler locally before deploying to GCP, ensuring logic works without cloud dependencies.
  • Simulating webhook events from external services (like Stripe or GitHub) to verify your function processes payloads correctly.
  • Writing integration tests for CI/CD pipelines that validate Cloud Function responses against expected event structures.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.