如何在 Kind 集群中通过 pytest-operator 测试自定义 CRD?
解读
国内云原生岗位面试时,这道题表面问“测试流程”,实则考察四件事:
- 对 pytest-operator 插件体系的熟悉度(能否用 Python 写声明式测试)
- 对 Kind(本地 K8s)环境搭建与生命周期管理的熟练度
- 对 CRD 终态一致性模型的理解(status/condition 读写、轮询策略)
- 对 CI 场景下“一次命令跑完全链路”的落地经验(镜像构建、加载、日志dump、清理)
面试官通常用这道题区分“只写过单元测试”与“真在 CI 里跑过 Operator 端到端”的候选人。答得太浅(只说 pip install 然后跑 pytest)会被追问“如何并行”“如何断言终态”“CI 怎么缓存镜像”;答得太深(直接讲 controller-runtime 源码)会被认为偏题。因此,答案要给出“本地可复现、CI 可移植、断言可扩展”的最小闭环。
知识点
- pytest-operator 核心概念
- ops_test fixture:自动创建/销毁 Kind 集群,提供 kubectl 包装器
- build_and_deploy:把本地 charm/operator 镜像打包并 kind load 到节点
- 断言库:tenacity 重试 + kubernetes-client 读 CRD status/condition
- Kind 集群生命周期
- 多节点配置、extraPortMappings、本地镜像加载(kind load docker-image)
- 集群复用模式(--keep-storage)与 CI 隔离模式(随机集群名)
- CRD 测试模型
- Given:安装 CRD、创建 CR 实例、注入外部依赖(MinIO、MySQL)
- When:更新 CR spec 或触发外部事件
- Then:轮询 CR status.conditions、子资源(Deployment/Pod)终态、业务指标
- 并发与资源回收
- pytest-xdist 多进程并发时,每个 worker 独占一个命名空间
- yield 后的 teardown 必须保证 CR 被删除,防止 Finalizer 阻塞 Kind 删除
- 国内镜像加速
- 为 gcr.io/kubebuilder/kube-rbac-proxy 等镜像准备国内代理或提前同步到阿里云 ACR
- 在 conftest.py 里通过 DOCKER_BUILDKIT=1 与 --build-arg 统一基础镜像源
答案
步骤一:准备最小项目骨架
my-crd-operator/
├── src/
│ └── my_crd.py
├── tests/integration/
│ ├── conftest.py
│ └── test_crd_lifecycle.py
├── manifests/crd.yaml
├── Dockerfile
└── tox.ini
步骤二:conftest.py 复用 ops_test 并开启国内镜像
import pytest
from pytest_operator.plugin import OpsTest
@pytest.fixture(scope="module")
async def my_crds(ops_test: OpsTest):
# 1. 创建随机命名空间,支持并发
namespace = f"test-{ops_test.model_name}"
await ops_test.run(
"kubectl", "create", "namespace", namespace
)
# 2. 安装 CRD
await ops_test.run(
"kubectl", "apply", "-f", "manifests/crd.yaml", "-n", namespace
)
yield namespace
# 3. 强制清理,防止 Finalizer 卡住
await ops_test.run(
"kubectl", "delete", "-f", "manifests/crd.yaml", "-n", namespace, "--timeout=60s"
)
await ops_test.run(
"kubectl", "delete", "namespace", namespace, "--ignore-not-found"
)
步骤三:测试用例——创建、更新、断言终态
import yaml, tenacity, kubernetes as k8s
from pytest_operator.plugin import OpsTest
async def test_crd_scale_to_three(ops_test: OpsTest, my_crds):
namespace = my_crds
# 1. 构建并加载镜像到 Kind
image = "localhost:5000/my-crd-operator:test"
await ops_test.build_and_deploy(
bundle_path=".",
build_args={"DOCKER_BUILDKIT": "1"},
container_image=image,
)
await ops_test.run("kind", "load", "docker-image", image, "--name", ops_test.model_name)
# 2. 创建 CR 实例
cr = {
"apiVersion": "example.com/v1",
"kind": "MyApp",
"metadata": {"name": "demo", "namespace": namespace},
"spec": {"replicas": 1},
}
await ops_test.run(
"kubectl", "apply", "-f", "-", input=yaml.safe_dump(cr), check=True
)
# 3. 轮询 CR status
@tenacity.retry(
wait=tenacity.wait_fixed(3),
stop=tenacity.stop_after_delay(120),
retry=tenacity.retry_if_exception_type(AssertionError),
)
def assert_ready():
k8s.config.load_kube_config(context=f"kind-{ops_test.model_name}")
api = k8s.CustomObjectsApi()
obj = api.get_namespaced_custom_object(
group="example.com",
version="v1",
namespace=namespace,
plural="myapps",
name="demo",
)
cond = next((c for c in obj["status"]["conditions"] if c["type"] == "Ready"), None)
assert cond and cond["status"] == "True", "CR not ready"
assert obj["status"]["replicas"] == 1
assert_ready()
# 4. 更新 replicas 并再次断言
cr["spec"]["replicas"] = 3
await ops_test.run("kubectl", "apply", "-f", "-", input=yaml.safe_dump(cr), check=True)
@tenacity.retry(...)
def assert_scaled():
... # 同上,断言 replicas==3
assert_scaled()
步骤四:本地一键跑通
tox -e integration -- --model test --keep-storage=false -n 4
说明:-n 4 启用 pytest-xdist 并发,每个 worker 拿到独立命名空间;--keep-storage=false 保证 CI 跑完后 Kind 集群被销毁,避免磁盘泄漏。
步骤五:CI(GitHub Actions / 阿里云云效)
- name: Setup Kind
uses: helm/kind-action@v1
with:
config: .github/kind-config.yaml # 国内镜像仓库配置
- name: Pre-pull 国内镜像
run: |
docker pull registry.cn-hangzhou.aliyuncs.com/kubebuilder/kube-rbac-proxy:v0.13.1
kind load docker-image registry.cn-hangzhou.aliyuncs.com/kubebuilder/kube-rbac-proxy:v0.13.1
- name: Run integration
run: tox -e integration -- --model ci-${{ github.run_id }}
拓展思考
-
当 CRD 依赖外部云资源(如阿里云 RDS)时,如何在测试里做“轻量替身”?
可在 conftest.py 中通过 pytest-env 插件注入 MOCK_CLOUD=true,启动一个本地 Terraform LocalStack 或阿里云的“沙箱实例”,并在 CR 的 ProviderRef 里指向测试 Endpoint,确保用例可重复、不产生费用。 -
并行度升高后,Kind 控制面压力增大,出现 etcd 空间不足,如何调优?
在 kind-config.yaml 中给 etcd 增加配额:kubeadmConfigPatches: - | apiVersion: kubeadm.k8s.io/v1beta3 kind: ClusterConfiguration etcd: local: extraArgs: quota-backend-bytes: "8589934592"并在 CI 里定期
etcdctl defrag清理碎片。 -
如果 CRD 带有 Webhook,证书轮转失败导致测试偶发超时,如何根治?
在测试前预生成自签 CA,通过 cert-manager 的 CA Injector 把证书注入 MutatingWebhookConfiguration,关闭 Webhook 的自动轮转;测试后再删除 Issuer,避免与生产逻辑冲突。