google-cloud-functions - 如何使用 Cloud Builds 为 Google Cloud Functions 运行 python 单元测试?
问题描述
我正在尝试为我的谷歌云功能构建 CI/CD 管道。我知道的是,我有 gcloud 和 git 的本地开发环境。我在本地环境中编写代码并拥有 cloudbuilds.yaml 文件。编写代码后,我将其推送到我有 Build Trigger 的 Google Source Repository。它构建功能并部署它。
现在我也想要一些测试文件。这意味着每当我将它推送到源存储库时,它也应该运行测试并构建我的 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
with表示gcloud
为入口点,functions
and 表示list
为 args。
如果你的容器没有入口点(比如 python 容器)或者你想覆盖你的入口点,你可以用entrypoint
关键字指定它。在我的第一个代码示例中,需要很少的 linux 概念。入口点是 bash。arg-c
用于执行命令。管道|
if 用于允许多命令(多行)命令条目。
如果你只有一个 python 命令要启动,你可以这样做:
- name: 'python:3.7'
entrypoint: 'python3'
args:
- 'test_main.py'
- '.'
但是,您编写的步骤将不起作用。为什么?回到我解释的开头:只/workspace
保留文件。如果您执行 a pip3 install
,则文件不会写入/workspace
目录中,而是写入系统的其他位置。当您切换步骤时,您会失去此系统上下文。
这就是为什么多行命令很有用
- name: 'python:3.7'
entrypoint: 'bash'
args:
- '-c'
- |
pip3 install -r requirements.txt
python3 test_main.py .
希望这有帮助!
推荐阅读
- php - 递归从三维数组中获取特定值
- javascript - 仅在需要时如何向 MirajeJS js 发出请求
- azure - Azure Devops 计划部署任务拾取上次部署的新版本状态
- apache-kafka - ksqlDB 从 Json 主题中获取消息的值作为字符串列
- node.js - multer req.files.filename 始终未定义
- python - 我想接受用户输入并在 GUI 中输出
- android-layout - Android 布局 PX 转 SP
- javascript - Javascript自动文件输入填充和上传
- java - 如何在 Swing 中创建一个有组织的信息“列表”的面板
- python - 是否可以将 GradCam 应用于 TF Lite 模型