【问题标题】:How to run python unit test for Google Cloud Functions using Cloud Builds?如何使用 Cloud Builds 为 Google Cloud Functions 运行 python 单元测试?
【发布时间】:2020-06-16 17:59:52
【问题描述】:

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

现在我也想要一些测试文件。这意味着每当我将它推送到源存储库时,它也应该运行测试并构建我的 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 

【问题讨论】:

  • 你想在部署之前添加单元测试,不是吗?如果测试失败,就不会进行部署,对吧?
  • 是的,没错! @guilaume

标签: google-cloud-functions gcloud google-cloud-build google-source-repositories


【解决方案1】:

您可以在 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 用于执行命令。管道| if 用于允许多命令(多行)命令条目。

如果你只有一个 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 .

希望对您有所帮助!

【讨论】:

  • 我用的是pytest,test文件夹下有test_cloudfunction.py..
  • 我需要在我的问题步骤之后添加此步骤吗?
  • 我更新了我的答案。让我知道它是否足够清楚
  • 我正在使用 pytest 进行测试。我只是使用 pytest 来测试功能。我需要在 'c' 参数之后加上 'pytest' 吗?我对 CI/CD 完全陌生,如果可能的话,您能否还给我一些教程以开始并对此有一个很好的理解?谢谢!
  • 我提供了很多详细的 Cloud Build 行为。你需要更多吗?如果是这样,问我什么!
猜你喜欢
  • 2019-07-28
  • 2019-05-10
  • 2021-12-26
  • 2019-09-15
  • 2013-12-21
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
相关资源
最近更新 更多