|
| 1 | +package common |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/google/go-cmp/cmp" |
| 7 | +) |
| 8 | + |
| 9 | +func TestParseLabels(t *testing.T) { |
| 10 | + tests := []struct { |
| 11 | + description string |
| 12 | + input string |
| 13 | + expectedMap map[string]string |
| 14 | + expectError bool |
| 15 | + }{ |
| 16 | + { |
| 17 | + description: "single label", |
| 18 | + input: "key1=val1", |
| 19 | + expectedMap: map[string]string{"key1": "val1"}, |
| 20 | + expectError: false, |
| 21 | + }, |
| 22 | + { |
| 23 | + description: "multiple labels", |
| 24 | + input: "key1=val1,key2=val2", |
| 25 | + expectedMap: map[string]string{"key1": "val1", "key2": "val2"}, |
| 26 | + expectError: false, |
| 27 | + }, |
| 28 | + { |
| 29 | + description: "empty value", |
| 30 | + input: "key1=", |
| 31 | + expectedMap: map[string]string{"key1": ""}, |
| 32 | + expectError: false, |
| 33 | + }, |
| 34 | + { |
| 35 | + description: "value with equals sign", |
| 36 | + input: "key1=value=with=equals", |
| 37 | + expectedMap: map[string]string{"key1": "value=with=equals"}, |
| 38 | + expectError: false, |
| 39 | + }, |
| 40 | + { |
| 41 | + description: "special case: empty string to clear labels", |
| 42 | + input: "", |
| 43 | + expectedMap: map[string]string{}, // Should be an empty map, not nil |
| 44 | + expectError: false, |
| 45 | + }, |
| 46 | + { |
| 47 | + description: "invalid format - no equals", |
| 48 | + input: "key1val1", |
| 49 | + expectedMap: nil, |
| 50 | + expectError: true, |
| 51 | + }, |
| 52 | + { |
| 53 | + description: "invalid format - empty key", |
| 54 | + input: "=val1", |
| 55 | + expectedMap: nil, |
| 56 | + expectError: true, |
| 57 | + }, |
| 58 | + { |
| 59 | + description: "mixed valid and invalid pair", |
| 60 | + input: "key1=val1,key2", |
| 61 | + expectedMap: nil, |
| 62 | + expectError: true, |
| 63 | + }, |
| 64 | + { |
| 65 | + description: "invalid format - leading comma", |
| 66 | + input: ",key1=val1", |
| 67 | + expectedMap: nil, |
| 68 | + expectError: true, |
| 69 | + }, |
| 70 | + { |
| 71 | + description: "invalid format - trailing comma", |
| 72 | + input: "key1=val1,", |
| 73 | + expectedMap: nil, |
| 74 | + expectError: true, |
| 75 | + }, |
| 76 | + } |
| 77 | + |
| 78 | + for _, tt := range tests { |
| 79 | + t.Run(tt.description, func(t *testing.T) { |
| 80 | + parsedMap, err := ParseLabels(tt.input) |
| 81 | + |
| 82 | + if !tt.expectError && err != nil { |
| 83 | + t.Fatalf("did not expect an error, but got: %v", err) |
| 84 | + } |
| 85 | + |
| 86 | + if tt.expectError && err == nil { |
| 87 | + t.Fatalf("expected an error, but got nil") |
| 88 | + } |
| 89 | + |
| 90 | + if diff := cmp.Diff(tt.expectedMap, parsedMap); diff != "" { |
| 91 | + t.Errorf("map mismatch (-want +got):\n%s", diff) |
| 92 | + } |
| 93 | + }) |
| 94 | + } |
| 95 | +} |
0 commit comments