Say I have the following structure with kubebuilder validation markers:
type ToySpec struct {
// +kubebuilder:validation:MaxLength=15
// +kubebuilder:validation:MinLength=1
Name string `json:"name,omitempty"`
}
I want to do something like this:
spec = ToySpec{Name: ""}
err := Validate(spec) // Should return error as name has length of 0
Is this currently possible?
First of all you need to import metav1
:
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
Then you can test your ToySpec
like this:
package controllers
import (
"testing"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestToySpecValidation(t *testing.T) {
// Test for Name field exceeding MaxLength
toy := &ToySpec{
Name: "ThisNameIsTooLongToPassValidation",
}
err := toy.Validate()
assert.Error(t, err, "Expected validation error for Name exceeding MaxLength")
// Test for Name field below MinLength
toy.Name = ""
err = toy.Validate()
assert.Error(t, err, "Expected validation error for Name below MinLength")
// Test case for valid Name field
toy.Name = "ValidName"
err = toy.Validate()
assert.NoError(t, err, "Expected no validation error for valid Name")
}