【问题标题】:How to test a Cloud Function in Google Cloud Platform (GCP)?如何在 Google Cloud Platform (GCP) 中测试云功能?
【发布时间】:2018-06-11 14:57:38
【问题描述】:

我一直在努力寻找答案,但在任何地方都找不到。在 Google Cloud Platform 控制台的 Cloud Functions 部分中,有一个标题为“测试”的部分,但我不知道应该在此处放置什么来测试函数,即语法。

为了清楚起见,我附上了一张图片:

任何帮助将不胜感激。

【问题讨论】:

    标签: google-cloud-platform google-cloud-functions


    【解决方案1】:

    HTTPS Callable 函数必须使用 POST 方法调用,Content-Type 必须是 application/json 或 application/json; charset=utf-8,并且正文必须包含一个名为 data 的字段,以便将数据传递给方法。

    示例正文:

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

    如果您通过创建自己的 http 请求来调用函数,您可能会发现改用常规 HTTPS 函数更灵活。

    Click Here了解更多信息

    【讨论】:

      【解决方案2】:

      使用 Cloud Function 默认 Hello_World 的示例,该示例会在您创建新 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!'
      

      必须使用 json 作为输入参数进行测试:

      {
          "message": "Hello Sun!"
      }
      

      在测试标签中:

      Hello Sun!
      

      在测试选项卡编辑器中:由于我们以 json 的形式为函数提供参数,否则我们会像在 python3 -m main.py MY_ARG 中那样编写它们,并且由于“消息”是该 json 的键,因此可以通过elif 并返回字典键的值作为消息,而不是“Hello World”。如果我们在没有 json args 的情况下运行脚本,代码中会到达else:,输出是“Hello World!”:

      【讨论】:

        【解决方案3】:

        这看起来与 gcloud functions call 相同,所需的 JSON 与 CLI 中提供的 --data 相同。

        您可以使用 CLI 查看the docs 以获取示例,并查看the CLI documentation itself 以获取更多详细信息。

        【讨论】:

          【解决方案4】:

          您可以通过多种方式测试云功能。

          1) 如果您想在部署前测试您的代码,请在本地使用谷歌模拟器。 https://cloud.google.com/functions/docs/emulator。 这将为您提供一个类似的 localhost HTTP 端点,您可以向该端点发送请求以测试您的功能。

          2) 在已部署函数上使用 GUI:触发事件是函数期望在请求正文中的 json 对象。例如:

              {
                "key": "value"
              }
          

          根据您对请求的函数代码依赖性,它应该触发该函数。

          【讨论】:

            【解决方案5】:

            Cloud Pub/Sub 的简单测试:

            {"data":"This is data"}
            

            Base64 'Hello World!'留言:

            {"data":"SGVsbG8gV29ybGQgIQ=="}
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2023-03-28
              • 2020-02-05
              • 2020-11-20
              • 2019-07-09
              • 2018-11-21
              • 1970-01-01
              • 2020-11-30
              • 1970-01-01
              相关资源
              最近更新 更多