使用KIND为pytest提供Kubernetes测试支持
项目描述
pytest-kind
使用kind和pytest测试您的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 查看散列)
关闭
pytest-kind-22.11.1.tar.gz的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | ae7a4c753fcbbf9e44a0cc587d5219a0b8b2b1e7bcc9cbe14234f745dd5db681 |
|
MD5 | 85d27f3b4035580a04ef7b7b0fd225dc |
|
BLAKE2b-256 | 28bc5816716a372636e90251bbf81a2d51c2eb340dc77cb5e7237c1a455fa3f4 |
关闭
pytest_kind-22.11.1-py3-none-any.whl的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | 35fd99e4f94e0374834b5893ee4a95e33ad5dc1c18080356f01fadf21224e830 |
|
MD5 | abd790716ca4d74928a43cd2f915d95e |
|
BLAKE2b-256 | 7df2c9eda764e0a32b8c14eab539d6dcb409d7b1cabaceb5caa9db89c769b2f0 |