|
14 | 14 |
|
15 | 15 | package allocation
|
16 | 16 |
|
17 |
| -// TODO: Add tests |
| 17 | +import ( |
| 18 | + "testing" |
| 19 | + |
| 20 | + "github.com/open-telemetry/opentelemetry-operator/cmd/otel-allocator/target" |
| 21 | + "github.com/prometheus/common/model" |
| 22 | + "github.com/stretchr/testify/assert" |
| 23 | + logf "sigs.k8s.io/controller-runtime/pkg/log" |
| 24 | +) |
| 25 | + |
| 26 | +var loggerPerNode = logf.Log.WithName("unit-tests") |
| 27 | + |
| 28 | +// Tests that two targets with the same target url and job name but different label set are both added. |
| 29 | +func TestAllocationPerNode(t *testing.T) { |
| 30 | + // prepare allocator with initial targets and collectors |
| 31 | + s, _ := New("per-node", loggerPerNode) |
| 32 | + |
| 33 | + cols := MakeNCollectors(3, 0) |
| 34 | + s.SetCollectors(cols) |
| 35 | + firstLabels := model.LabelSet{ |
| 36 | + "test": "test1", |
| 37 | + podNodeNameLabel: "node-0", |
| 38 | + } |
| 39 | + secondLabels := model.LabelSet{ |
| 40 | + "test": "test2", |
| 41 | + podNodeNameLabel: "node-1", |
| 42 | + } |
| 43 | + // no label, should be skipped |
| 44 | + thirdLabels := model.LabelSet{ |
| 45 | + "test": "test3", |
| 46 | + } |
| 47 | + firstTarget := target.NewItem("sample-name", "0.0.0.0:8000", firstLabels, "") |
| 48 | + secondTarget := target.NewItem("sample-name", "0.0.0.0:8000", secondLabels, "") |
| 49 | + thirdTarget := target.NewItem("sample-name", "0.0.0.0:8000", thirdLabels, "") |
| 50 | + |
| 51 | + targetList := map[string]*target.Item{ |
| 52 | + firstTarget.Hash(): firstTarget, |
| 53 | + secondTarget.Hash(): secondTarget, |
| 54 | + thirdTarget.Hash(): thirdTarget, |
| 55 | + } |
| 56 | + |
| 57 | + // test that targets and collectors are added properly |
| 58 | + s.SetTargets(targetList) |
| 59 | + |
| 60 | + // verify length |
| 61 | + actualItems := s.TargetItems() |
| 62 | + |
| 63 | + // one target should be skipped |
| 64 | + expectedTargetLen := len(targetList) - 1 |
| 65 | + assert.Len(t, actualItems, expectedTargetLen) |
| 66 | + |
| 67 | + // verify allocation to nodes |
| 68 | + for targetHash, item := range targetList { |
| 69 | + actualItem, found := actualItems[targetHash] |
| 70 | + // if third target, should be skipped |
| 71 | + if targetHash != thirdTarget.Hash() { |
| 72 | + assert.True(t, found, "target with hash %s not found", item.Hash()) |
| 73 | + } else { |
| 74 | + assert.False(t, found, "target with hash %s should not be found", item.Hash()) |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + itemsForCollector := s.GetTargetsForCollectorAndJob(actualItem.CollectorName, actualItem.JobName) |
| 79 | + assert.Len(t, itemsForCollector, 1) |
| 80 | + assert.Equal(t, actualItem, itemsForCollector[0]) |
| 81 | + } |
| 82 | +} |
0 commit comments