如何使用 Cloud Builds 运行 python 对 Google Cloud Functions 进行单元测试?

How to run python unit test for Google Cloud Functions using Cloud Builds?

我正在尝试为我的 google 云函数构建一个 CI/CD 管道。 我所知道的是,我有 gcloud 和 git 的本地开发环境。 我在本地环境中编写代码并拥有 cloudbuilds.yaml 文件。 编写代码后,我将其推送到 Google Source Repository,其中我有 Build Trigger。 它构建函数并部署它。

现在我想要一些测试文件 too.That 意味着每当我将它推送到源存储库时它也应该 运行 测试并构建我的 main.py 文件然后部署它。 我的 cloudbuild.yaml 文件是

steps:
- name: 'gcr.io/cloud-builders/gcloud'
  args:
  - functions 
  - deploy
  - FunctionName
  - --runtime=python37
  - --source=.
  - --entry-point=function
  - --trigger-topic=topic_name
  - --region=europe-west3 

您可以在 Cloud Build 中添加一个步骤。我不知道你的 运行 你的测试如何,但这里有一个 运行 在 python3.7 上下文

中使用你的脚本的例子
- name: 'python:3.7'
  entrypoint: 'bash'
  args:
    - '-c'
    - |
       run the python script that you want
       pip install and others.

更新

在部署函数之前添加此步骤。如果该步骤失败(退出代码不同于 0),则云构建过程停止并且不执行部署。

更新 2

Cloud Build 的概念非常简单。您加载一个容器(在 name 中表示)。在容器中,只有卷 /workspace 被附加并从一步到下一步保留。

这个概念很重要。如果您在一个步骤中设置环境变量或其他变量,则之后的步骤将失去此上下文。只保留/workspace的文件。仅当当前步骤正确完成(退出代码 = 0)时才调用下一步。

加载容器时,触发命令。如果您使用 cloud builder,则默认调用默认入口点(例如,gcloud Cloud Builder 会自动启动 gcloud 命令)。然后你只需要添加 args 数组提交到这个入口点。范例

- name: 'gcr.io/cloud-builders/gcloud'
  args:
  - functions 
  - list

此命令表示 gcloud functions list,以 gcloud 作为入口点,以 functionslist 作为参数。

如果您的容器没有入口点(如 python 容器)或者如果您想覆盖您的入口点,您可以使用 entrypoint 关键字指定它。在我的第一个代码示例中,几乎不需要 linux 概念。入口点是 bash。 arg 是 -c 用于执行命令。管道 | 如果允许多命令(多行)命令输入。

如果你只有一个python命令启动,你可以这样做:

- name: 'python:3.7'
  entrypoint: 'python3'
  args:
    - 'test_main.py'
    - '.'

但是,您编写的步骤将不起作用。为什么?回到我开头的解释:只保留/workspace的文件。如果您执行 pip3 install,则文件不会写入 /workspace 目录,而是写入系统的其他位置。当您切换步骤时,您将失去此系统上下文。

这就是为什么多行命令很有用

- name: 'python:3.7'
  entrypoint: 'bash'
  args:
    - '-c'
    - |
       pip3 install -r requirements.txt
       python3 test_main.py .

希望对您有所帮助!