44 / 75 · 08 Infrastructure as Code Testing · Serverless Function Testing← prev⊞ allnext →☰ Read as one page
8.3Google Cloud Functions Testing
Google Cloud Functions can be tested locally using the Functions Framework:
# Install the Functions Framework for local testing
pip install functions-framework
# Run locally
functions-framework --target=process_order --port=8080
# Test with curl
curl -X POST http://localhost:8080 \
-H "Content-Type: application/json" \
-d '{"orderId": "ORD-123"}'
Testing Cloud Functions with pytest
# tests/test_cloud_function.py
import pytest
from unittest.mock import patch, MagicMock
from flask import Flask
import json
# Import the function
from main import process_order
@pytest.fixture
def app():
return Flask(__name__)
@pytest.fixture
def client(app):
return app.test_client()
def test_process_order_valid_request(app):
"""Test processing a valid order."""
with app.test_request_context(
method="POST",
json={"orderId": "ORD-123", "amount": 99.99}
):
from flask import request
response = process_order(request)
data = json.loads(response)
assert data["status"] == "processed"
def test_process_order_missing_order_id(app):
"""Test handling of missing order ID."""
with app.test_request_context(
method="POST",
json={"amount": 99.99}
):
from flask import request
response, status_code = process_order(request)
assert status_code == 400