I'm working on a Google cloud gen1 non http triggered cloud function and I would like to test it locally before deploying.

The function makes an api request to github actions. It works locally with a 204 response when I just run the script on it's own. However, when I try to either run from the GCP functions UI using the testing tab, or via functions-framework, I get a 401 error.

Billing is enabled for the project.

Variable PAT is in .env file on local, on GCP it's a secret manifested as an env var.

The trigger for the function occurs once every 24 hours and I did notice that the function ran via the pub/sub trigger. I just cannot invoke the function locally or via the UI during the course of development and testing (the 401 response).

Here's main.py:

import requests
import os
from dotenv import load_dotenv

# globals, reads .env if present, else reads host env vars
load_dotenv()
OWNER = os.environ['OWNER']
REPO = os.environ['REPO']
EVENT_TYPE = os.environ['EVENT_TYPE']
PAT = os.environ['PAT']

# the function
def requestGHA(PAT=PAT, OWNER=OWNER, REPO=REPO, EVENT_TYPE=EVENT_TYPE):

    # Set up the headers for the API request
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {PAT}",
    }

    # Set up the URL for the API request
    url = f"https://api.github.com/repos/{OWNER}/{REPO}/dispatches" 

    # Set up the payload for the API request
    payload = {
        "event_type": EVENT_TYPE,
        "client_payload": {
            "db_schema": "dev"
        }
    }

    # Make the API request
    response = requests.post(url, json=payload, headers=headers)
    
    return str(response.status_code)

If I run this in a python console and then type requestGHA(), everything works with a 204 response. But when I try e.g. via functions framework:

$ functions-framework --target requestGHA --debug
 * Serving Flask app "requestGHA" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://192.168.0.33:8080/ (Press CTRL+C to quit)
 * Restarting with watchdog (inotify)
 * Debugger is active!
 * Debugger PIN: 103-819-696

After running this if I visit http://localhost:8080/ I see 401.

Why can't I run my cloud function locally?

0

There are 0 best solutions below