python - 使单元测试失败导致 Google Cloud 构建中的构建失败

标签 python python-unittest google-cloud-build

我正在 Google Cloud Platform 上运行的 Python 项目上设置 CI/CD。代码部署工作正常,但我也为单独的功能创建了一些单元测试。这些单元测试位于几个不同的文件中,因此我创建了一个新文件,该文件包含所有这些单元测试并将它们添加到测试套件中。例如,我有一个名为 testFunction1.py 的文件如下:

from main import Function1

class TransformTests(unittest.TestCase):

    def test_function(self):
        # Test goes here


if __name__ == '__main__':
    logging.getLogger().setLevel(logging.ERROR)
    unittest.main()

然后我有一个名为 testFunction2.py 的类似文件用于不同的功能。
最后我有一个名为 executeTests.py 的文件如下:
import unittest

testmodules = [
    'testFunction1',
    'testFunction2'
]

suite = unittest.TestSuite()
loader = unittest.TestLoader()

for t in testmodules:
    mod = __import__(t, globals(), locals(), ['suite'])
    suite.addTests(loader.loadTestsFromModule(mod))

unittest.TextTestRunner().run(suite)
现在我正在运行这个文件来一次执行所有测试,这也很好用。我的问题是在 Google Cloud Build 中运行这个文件。我的 cloudbuild.yaml 文件的结构如下:
steps:
  - name: "docker.io/library/python:3.7"
    args: ["pip3", "install", "-t", "/workspace/lib", "-r", "requirements.txt"]
  - name: "docker.io/library/python:3.7"
    args: ["python3", "executeTests.py"]
    env: ["PYTHONPATH=/workspace/lib"]
这工作正常,但如果测试失败,云构建仍然通过,这当然不是我想要的。
有谁知道我如何更改此设置,以便在测试失败时云构建失败?这也是一个简单的例子,在真正的 repo 中,我有大约 50 个测试文件,所以我不想将它们每个都添加到 cloudbuild.yaml 文件中。

最佳答案

如果返回代码为 0,则 Cloud Build 认为步骤 OK。如果不是,则构建失败。
因此,在您的测试代码中,执行 exit(1)当至少一项测试失败时。构建将停止。

关于python - 使单元测试失败导致 Google Cloud 构建中的构建失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65179288/

相关文章:

python aiohttp-sse 在 6 个请求后超时

python - 使用 thread.join 确保所有线程都加入时,Pydev PyUnit 出现问题

python - 如何测试细节,删除等

google-cloud-platform - Gcloud 构建提交失败 "global"违反约束 "constraints/gcp.resourceLocations"

python - repr 调用会产生堆栈帧吗?

.net - 在 Python 中动态编写 PowerShell CmdLets

docker - COPY失败:未指定源文件

google-cloud-functions - 权限 'cloudkms.cryptoKeyVersions.useToDecrypt' 拒绝资源 ...key

Python根据列表中的日期获取记录

python - 当生产类构造函数采用额外参数时,为什么 unittest.mock 会失败?