跳至主要内容

使用KIND为pytest提供Kubernetes测试支持

项目描述

pytest-kind

Build Status PyPI PyPI - Python Version License CalVer

使用kindpytest测试您的Python Kubernetes应用程序/操作员端到端。

pytest-kind是pytest的一个插件,它提供了一个kind_cluster固定装置。该装置将安装kind 0.17.0,创建一个Kubernetes 1.25集群,并提供如端口转发等便利功能。

用法

通过pip或通过poetry安装pytest-kind,例如。

poetry add --dev pytest-kind

编写您的pytest函数并使用提供的kind_cluster固定装置,例如。

def test_kubernetes_version(kind_cluster):
    assert kind_cluster.api.version == ('1', '25')

加载您的自定义Docker镜像并应用部署清单

import requests
from pykube import Pod

def test_myapp(kind_cluster):
    kind_cluster.load_docker_image("myapp")
    kind_cluster.kubectl("apply", "-f", "deployment.yaml")
    kind_cluster.kubectl("rollout", "status", "deployment/myapp")

    # using Pykube to query pods
    for pod in Pod.objects(kind_cluster.api).filter(selector="app=myapp"):
        assert "Sucessfully started" in pod.logs()

    with kind_cluster.port_forward("service/myapp", 80) as port:
        r = requests.get(f"http://localhost:{port}/hello/world")
        r.raise_for_status()
        assert r.text == "Hello world!"

查看examples目录中的示例项目和kube-web-view,它使用pytest-kind进行其端到端测试。

KindCluster对象

kind_cluster固定装置是KindCluster类的实例,具有以下方法

  • load_docker_image(docker_image): 将指定的Docker镜像加载到kind集群中
  • kubectl(*args): 在集群上运行指定参数的kubectl二进制文件。返回作为字符串的过程输出。
  • port_forward(service_or_pod_name, remote_port, *args): 为给定的服务/Pod运行"kubectl port-forward"并返回(随机)本地端口。用作上下文管理器("with"语句)。通过"-n","mynamespace"将命名空间作为附加参数传递给kubectl。

KindCluster具有以下属性

  • name: kind集群名称
  • kubeconfig_path:访问集群的Kubeconfig文件路径
  • kind_path:kind二进制文件的路径
  • kubectl_path:kubectl二进制文件的路径
  • api:用于从Python访问集群的pykube HTTPClient实例

您也可以直接使用KindCluster而不使用pytest

from pytest_kind import KindCluster

cluster = KindCluster("myclustername")
cluster.create()
cluster.kubectl("apply", "-f", "..")
# ...
cluster.delete()

pytest选项

可以通过CLI选项--cluster-name设置kind集群名称。

每次pytest会话后都会删除kind集群,您可以通过将--keep-cluster传递给pytest来保留集群。

请注意,您可以使用PYTEST_ADDOPTS环境变量将这些选项传递给pytest。如果从Makefile调用pytest,这也适用。

# for test debugging: don't delete the kind cluster
PYTEST_ADDOPTS=--keep-cluster make test

注意事项

  • kind_cluster固定作用域为会话级,即将在所有测试模块/函数中使用相同的集群。
  • kind和kubectl二进制文件将一次性下载到本地目录./.pytest-kind/{cluster-name}/。您可以使用它们与集群交互(例如,当使用--keep-cluster时)。
  • 某些集群Pod可能不会立即就绪(例如,kind的CoreDNS需要一点时间),根据需要添加等待/轮询功能,以使您的测试更加可预测。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分布

pytest-kind-22.11.1.tar.gz (18.0 kB 查看散列)

上传时间

构建分布

pytest_kind-22.11.1-py3-none-any.whl (18.5 kB 查看散列)

上传时间 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面