blob: c8e1a865fec503ae55a8bed8ff6f87a0e05e60f9 [file] [log] [blame]
Serge Bazanski1f789542024-05-22 14:01:50 +02001package node
2
3import (
4 "errors"
5 "testing"
Serge Bazanskidd2b80f2024-09-24 13:06:27 +00006
7 "k8s.io/apimachinery/pkg/util/validation"
Serge Bazanski1f789542024-05-22 14:01:50 +02008)
9
Serge Bazanskidd2b80f2024-09-24 13:06:27 +000010func TestValidateLabelKey(t *testing.T) {
11 for i, te := range []struct {
12 in string
13 want error
14 }{
15 {"foo", nil},
16 {"example.com/", ErrLabelEmpty},
17 {"foo-bar.baz_barfoo", nil},
18 {"-", ErrLabelInvalidFirstCharacter},
19 {"-invalid", ErrLabelInvalidFirstCharacter},
20 {"invalid-", ErrLabelInvalidLastCharacter},
21 {"", ErrLabelEmpty},
22 {"accordingtoallknownlawsofaviationthereisnowaythatabeeshouldbeabletofly", ErrLabelTooLong},
23 {"example.com/annotation", nil},
24 {"/annotation", ErrLabelEmptyPrefix},
25 {"_internal.example.com/annotation", ErrLabelInvalidPrefix},
26 {"./annotation", ErrLabelInvalidPrefix},
27 {"../annotation", ErrLabelInvalidPrefix},
28 {"tcp:80.example.com/annotation", ErrLabelInvalidPrefix},
29 {"github.com/monogon-dev/monogon/annotation", ErrLabelInvalidPrefix},
30 } {
31 if got := ValidateLabelKey(te.in); !errors.Is(got, te.want) {
32 t.Errorf("%d (%q): wanted %v, got %v", i, te.in, te.want, got)
33 }
34 }
35}
36
37func TestValidateLabelValue(t *testing.T) {
Serge Bazanski1f789542024-05-22 14:01:50 +020038 for i, te := range []struct {
39 in string
40 want error
41 }{
42 {"foo", nil},
43 {"foo-bar.baz_barfoo", nil},
44 {"-", ErrLabelInvalidFirstCharacter},
45 {"-invalid", ErrLabelInvalidFirstCharacter},
46 {"invalid-", ErrLabelInvalidLastCharacter},
Serge Bazanskidd2b80f2024-09-24 13:06:27 +000047 {"", nil},
Serge Bazanski1f789542024-05-22 14:01:50 +020048 {"accordingtoallknownlawsofaviationthereisnowaythatabeeshouldbeabletofly", ErrLabelTooLong},
49 {"example.com/annotation", ErrLabelInvalidCharacter},
Serge Bazanskidd2b80f2024-09-24 13:06:27 +000050 {"/annotation", ErrLabelInvalidFirstCharacter},
51 {"_internal.example.com/annotation", ErrLabelInvalidFirstCharacter},
52 {"./annotation", ErrLabelInvalidFirstCharacter},
53 {"../annotation", ErrLabelInvalidFirstCharacter},
54 {"tcp:80.example.com/annotation", ErrLabelInvalidCharacter},
55 {"github.com/monogon-dev/monogon/annotation", ErrLabelInvalidCharacter},
Serge Bazanski1f789542024-05-22 14:01:50 +020056 } {
Serge Bazanskidd2b80f2024-09-24 13:06:27 +000057 // Test our implementation against test cases.
58 if got := ValidateLabelValue(te.in); !errors.Is(got, te.want) {
59 t.Errorf("%d (%q): wanted %v, got %v", i, te.in, te.want, got)
60 }
61 // Validate test cases against Kubernetes.
62 if errs := validation.IsValidLabelValue(te.in); (te.want == nil) != (len(errs) == 0) {
63 t.Errorf("%d (%q): wanted %v, kubernetes implementation returned %v", i, te.in, te.want, errs)
Serge Bazanski1f789542024-05-22 14:01:50 +020064 }
65 }
66}