文章目录
要做什么?
这次我要给我们的operator加上UT和pipeline,作为一个简单的BDD/TDD的sample。
因此我采用的测试框架为Ginkgo, CI框架为Azure
我们一个简单的逻辑
为我们的CR添加两个参数,Image和EnvValue
怎么做?
Ginkgo TDD
首先,在operator的目录里加上Ginkgo
type MykindSpec struct {
Size int32 `json:"size"`
Image string `json:"Image"`
EnvsValue string `json:"Envs"`
}
operator-sdk generate k8s
operator-sdk generate crds
在controller.go中将fun重命名为NewPodForCR
, 并且生成测试文件
ginkgo bootstrap
ginkgo generate controller
其次,添加测试
Context("newPodForCR", func() {
It("should use busybox as image by default", func() {
cr := mykindv1alpha1.MykindSpec{}
instance := &mykindv1alpha1.Mykind{Spec: cr}
Pod := mykind.NewPodForCR(instance)
Expect("busybox").To(Equal(Pod.Spec.Containers[0].Image))
})
It("should use image by given", func() {
cr := mykindv1alpha1.MykindSpec{Image: "test"}
instance := &mykindv1alpha1.Mykind{Spec: cr}
Pod := mykind.NewPodForCR(instance)
Expect("test").To(Equal(Pod.Spec.Containers[0].Image))
})
It("should pass envs if given", func() {
cr := mykindv1alpha1.MykindSpec{EnvsValue: "value"}
instance := &mykindv1alpha1.Mykind{Spec: cr}
Pod := mykind.NewPodForCR(instance)
Expect("value").To(Equal(Pod.Spec.Containers[0].Env[0].Value))
})
})
编写逻辑代码直至测试通过
func NewPodForCR(cr *mykindv1alpha1.Mykind) *corev1.Pod {
labels := map[string]string{
"app": cr.Name,
}
image := "busybox"
if cr.Spec.Image != "" {
image = cr.Spec.Image
}
EnvVar := corev1.EnvVar{
Name: "dummy",
Value: cr.Spec.EnvsValue,
}
return &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: cr.Name + "-pod",
Namespace: cr.Namespace,
Labels: labels,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "busybox",
Image: image,
Command: []string{"sleep", "3600"},
Env: []corev1.EnvVar{EnvVar},
},
},
},
}
}
Azure
pipeline
我们用Azure来保证pr都有测试了
trigger:
- master
pool:
vmImage: 'ubuntu-latest'
jobs:
- job:
displayName: build
steps:
- task: Go@0
inputs:
command: 'test'
arguments: '-v ./...'
workingDirectory: 'learning'
Build badge
Ref: https://docs.microsoft.com/en-us/learn/modules/implement-code-workflow/6-add-build-badge
结果
Ref:
https://blog.csdn.net/oe1019/article/details/106876471
https://docs.microsoft.com/en-us/learn/modules/implement-code-workflow/6-add-build-badge