|
| 1 | +package webhook |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | + |
| 9 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 10 | +) |
| 11 | + |
| 12 | +// Note: The maxAppNameLength constant must also be defined in your main code. |
| 13 | +// We define it here for the test. The value 63 is a common length |
| 14 | +// limit for labels in Kubernetes. |
| 15 | + |
| 16 | +func TestValidateNameLength(t *testing.T) { |
| 17 | + // Define test cases |
| 18 | + testCases := []struct { |
| 19 | + name string |
| 20 | + appName string |
| 21 | + expectError bool |
| 22 | + errorMsg string |
| 23 | + }{ |
| 24 | + { |
| 25 | + name: "name with valid length", |
| 26 | + appName: "my-awesome-application", |
| 27 | + expectError: false, |
| 28 | + }, |
| 29 | + { |
| 30 | + name: "empty name", |
| 31 | + appName: "", |
| 32 | + expectError: false, // Length is 0, which is less than the limit |
| 33 | + }, |
| 34 | + { |
| 35 | + name: "name at max length boundary", |
| 36 | + appName: strings.Repeat("a", maxAppNameLength), |
| 37 | + expectError: false, |
| 38 | + }, |
| 39 | + { |
| 40 | + name: "name exceeding max length by 1 character", |
| 41 | + appName: strings.Repeat("a", maxAppNameLength+1), |
| 42 | + expectError: true, |
| 43 | + errorMsg: fmt.Sprintf("metadata.name: Invalid value: %q: name must be no more than %d characters to allow for resource suffixes", strings.Repeat("a", maxAppNameLength+1), maxAppNameLength), |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "long name significantly over the limit", |
| 47 | + appName: "this-is-a-very-very-very-long-application-name-that-definitely-exceeds-the-kubernetes-label-length-limit", |
| 48 | + expectError: true, |
| 49 | + errorMsg: fmt.Sprintf("metadata.name: Invalid value: %q: name must be no more than %d characters to allow for resource suffixes", "this-is-a-very-very-very-long-application-name-that-definitely-exceeds-the-kubernetes-label-length-limit", maxAppNameLength), |
| 50 | + }, |
| 51 | + } |
| 52 | + |
| 53 | + // Run tests in a loop |
| 54 | + for _, tc := range testCases { |
| 55 | + t.Run(tc.name, func(t *testing.T) { |
| 56 | + // Prepare test data |
| 57 | + appMeta := metav1.ObjectMeta{ |
| 58 | + Name: tc.appName, |
| 59 | + } |
| 60 | + |
| 61 | + // Call the function under test |
| 62 | + err := validateNameLength(context.Background(), appMeta) |
| 63 | + |
| 64 | + // Check the result |
| 65 | + if tc.expectError { |
| 66 | + if err == nil { |
| 67 | + t.Errorf("expected an error but got nil") |
| 68 | + return |
| 69 | + } |
| 70 | + if err.Error() != tc.errorMsg { |
| 71 | + t.Errorf("expected error message:\n%q\ngot:\n%q", tc.errorMsg, err.Error()) |
| 72 | + } |
| 73 | + } else { |
| 74 | + if err != nil { |
| 75 | + t.Errorf("unexpected error: %v", err) |
| 76 | + } |
| 77 | + } |
| 78 | + }) |
| 79 | + } |
| 80 | +} |
0 commit comments