Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Python Google Cloud Functions locally

I'm trying out the Python3.7 runtime on Google Cloud Functions. I am able to deploy the functions and make them work once deployed, however, I can't seem to run the emulator to test them locally before I deploy.

Google's documentation is a little inconsistent where they tell you to install the google functions emulator here: https://cloud.google.com/functions/docs/emulator

But over on Firebase they tell you to npm install firebase-admin, firebase-tools and firebase-functions.

All of the emulator documentation references examples written in JS, none in Python so I'm wondering if these emulator even run Python functions locally?

Thanks

like image 515
Michael Gradek Avatar asked Dec 09 '18 15:12

Michael Gradek


People also ask

Can I test cloud functions locally?

Each Branch represents a Cloud Function. You can test or run this cloud function locally before. Once development is complete, this Cloud Function is deployed to the Google Cloud Function Service using the Google Cloud Build Service. Your development is thus directly connected to the provided function, so to speak.

How do you test a cloud function in GCP?

There are multiple ways you could test you cloud function. 1) Use a google emulator locally if you want to test your code before deployment. https://cloud.google.com/functions/docs/emulator. This would give you a similar localhost HTTP endpoint that you can send request to for testing your function.


1 Answers

You can use the Functions Framework for Python to run the function locally.

Given a function in a file named main.py like so:

def my_function(request):     return 'Hello World' 

You can do:

$ pip install functions-framework $ functions-framework --target my_function 

Which will start a local development server at http://localhost:8080.

To invoke it locally for an HTTP function:

$ curl http://localhost:8080 

For a background function with non-binary data:

$ curl -d '{"data": {"hi": "there"}}' -X POST \ -H "Content-Type: application/json" \ http://localhost:8080 

For a background function with binary data:

$ curl -d "@binary_file.file" -X POST \ -H "Ce-Type: true" \ -H "Ce-Specversion: true" \ -H "Ce-Source: true" \ -H "Ce-Id: true" \ -H "Content-Type: application/json" \ http://localhost:8080 
like image 92
Dustin Ingram Avatar answered Sep 28 '22 03:09

Dustin Ingram