Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a Cloud Function in Google Cloud Platform (GCP)?

I have been trying to find the answer to this but am unable to find it anywhere. On the Cloud Functions section in the Google Cloud Platform console there is a section title 'Testing' but I have no idea what one is supposed to put here to test the function, i.e. syntax.

I have attached an image for clarity: I have attached an image for clarity

Any help would be much appreciated.

like image 732
Jacob Avatar asked Oct 17 '22 17:10

Jacob


2 Answers

HTTPS Callable functions must be called using the POST method, the Content-Type must be application/json or application/json; charset=utf-8, and the body must contain a field called data for the data to be passed to the method.

Example body:

{
    "data": {
        "aString": "some string",
        "anInt": 57,
        "aFloat": 1.23,
    }
}

If you are calling a function by creating your own http request, you may find it more flexible to use a regular HTTPS function instead.

Click Here for more information

like image 81
Shyam Avatar answered Nov 15 '22 08:11

Shyam


Example with the Cloud Function default Hello_World that is inserted automatically whenever you create a new Cloud Function:

def hello_world(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    request_json = request.get_json()
    if request.args and 'message' in request.args:
        return request.args.get('message')
    elif request_json and 'message' in request_json:
        return request_json['message']
    else:
        return f'Hello World!'

enter image description here

Must be tested with a json as the input args:

{
    "message": "Hello Sun!"
}

Out in the Testing Tab:

Hello Sun!

enter image description here

In the Testing tab editor: since we give the function the args in form of a json as we would elsewise write them like in python3 -m main.py MY_ARG, and since "message" is a key of that json, it is found by the elif and returns the value of the dictionary key as the message, instead of "Hello World". If we run the script without json args, else: is reached in the code, and output is "Hello World!":

enter image description here

like image 42
questionto42standswithUkraine Avatar answered Nov 15 '22 09:11

questionto42standswithUkraine