Published 2 months ago

Master Local Testing of Google Cloud Functions

Software Development
Master Local Testing of Google Cloud Functions

Testing Google Cloud Functions Locally

Google Cloud Functions provide a serverless platform to execute code in response to events, eliminating the need for server management. This two-part tutorial focuses on local testing and deployment from GitHub. Part one, detailed below, covers local testing.

Prerequisites

  • A Google Cloud account
  • A Service Account with necessary permissions to deploy Cloud Functions
  • Your code ready for deployment (example provided below)

The following example fetches currency exchange rates (USD to other currencies) from a public API and saves the data to a BigQuery dataset:

import requests
import pandas_gbq
import pandas as pd
from google.oauth2 import service_account 


def get_currency():
    """
    Fetches currency exchange rates and saves them to BigQuery.
    Returns a confirmation message.
    """
    url = "https://open.er-api.com/v6/latest/USD" 
    response = requests.get(url=url)

    data = response.json()
    df = pd.DataFrame(list(data['rates'].items()), columns=["currency", "exchange_rate"])

    if not df.empty:
        save_to_bigquery(df)
        return "Process completed!"
    else:
        return "No data found."


def save_to_bigquery(dataframe):
    """
    Saves the DataFrame to a specified BigQuery dataset.
    Requires a service_account.json file with appropriate credentials.
    """
    df = dataframe
    project_id = "erthal-blog-de-projects" 
    dataset_table = "financial.currency"
    credentials = service_account.Credentials.from_service_account_file("service_account.json")

    pandas_gbq.to_gbq(df, dataset_table, project_id, credentials = credentials, if_exists='replace')

Functions Framework

Google's Functions Framework simplifies local testing by creating a local development server to trigger your function via HTTP requests.

Installation

pip install functions-framework

Setting up the HTTP Server

This involves importing the framework and defining an entry point for your function.

Import

import functions_framework

Entry Point

The @functions_framework.http decorator designates the function to handle incoming HTTP requests:

@functions_framework.http
def get_currency(request):
    """
    Fetches currency exchange rates from the API and calls save_to_bigquery to save data to BigQuery.
    Returns a message indicating processing status.
    """
    url = "https://open.er-api.com/v6/latest/USD" 
    response = requests.get(url=url)

    data = response.json()
    df = pd.DataFrame(list(data['rates'].items()), columns=["currency", "exchange_rate"])

    if not df.empty:
        save_to_bigquery(df)
        return functions_framework.HttpResponse("Process completed!", status=200)
    else:
        return functions_framework.HttpResponse("No data found.", status=200)

Note: The request parameter is crucial for handling HTTP requests in Google Cloud Functions.

Running the Function Locally

functions-framework --target=main --port=8080

This starts an HTTP server on port 8080 (default). Successful execution indicates a ready server.

Stopping the Function

To stop the server, use (on Ubuntu):

fuser -k 8080/tcp

Testing the Function

Send a request using curl (or Postman):

curl localhost:8080 -X POST -H "Content-Type: application/json"

A successful response (HTTP 200) and logs in the terminal confirm proper setup.

Conclusion

This guide facilitates local testing of Google Cloud Functions. Remember to adapt this process for your specific function requirements and continue to the next tutorial for deploying from GitHub.

Hashtags: #GoogleCloudFunctions # Serverless # LocalTesting # FunctionsFramework # CloudDevelopment # Deployment # HTTPRequests # BigQuery # Python # Testing

Related Articles

thumb_nail_Unveiling the Haiku License: A Fair Code Revolution

Software Development

Unveiling the Haiku License: A Fair Code Revolution

Dive into the innovative Haiku License, a game-changer in open-source licensing that balances open access with fair compensation for developers. Learn about its features, challenges, and potential to reshape the software development landscape. Explore now!

Read More
thumb_nail_Leetcode - 1. Two Sum

Software Development

Leetcode - 1. Two Sum

Master LeetCode's Two Sum problem! Learn two efficient JavaScript solutions: the optimal hash map approach and a practical two-pointer technique. Improve your coding skills today!

Read More
thumb_nail_The Future of Digital Credentials in 2025: Trends, Challenges, and Opportunities

Business, Software Development

The Future of Digital Credentials in 2025: Trends, Challenges, and Opportunities

Digital credentials are transforming industries in 2025! Learn about blockchain's role, industry adoption trends, privacy enhancements, and the challenges and opportunities shaping this exciting field. Discover how AI and emerging technologies are revolutionizing identity verification and workforce management. Explore the future of digital credentials today!

Read More
Your Job, Your Community
logo
© All rights reserved 2024