master
go 80 lines 2.12 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package functions
4
5 import (
6 "testing"
7
8 "github.com/stretchr/testify/assert"
9 "github.com/stretchr/testify/require"
10 )
11
12 func TestLookupFunction_SnapshotScenarios(t *testing.T) {
13 tests := map[string]struct {
14 run func(t *testing.T, mgr *Manager)
15 }{
16 "uses direct snapshot": {
17 run: func(t *testing.T, mgr *Manager) {
18 called := make(chan struct{}, 1)
19 mgr.Register("fn", func(Function) { called <- struct{}{} })
20
21 handler, ok := mgr.lookupFunction("fn")
22 require.True(t, ok)
23
24 mgr.Unregister("fn")
25 handler(Function{Name: "fn"})
26
27 select {
28 case <-called:
29 default:
30 t.Fatal("snapshot handler should still invoke the originally resolved direct function")
31 }
32 },
33 },
34 "uses prefix snapshot": {
35 run: func(t *testing.T, mgr *Manager) {
36 called := make(chan struct{}, 1)
37 mgr.RegisterPrefix("config", "collector:", func(Function) { called <- struct{}{} })
38
39 handler, ok := mgr.lookupFunction("config")
40 require.True(t, ok)
41
42 mgr.UnregisterPrefix("config", "collector:")
43 handler(Function{Name: "config", Args: []string{"collector:job"}})
44
45 select {
46 case <-called:
47 default:
48 t.Fatal("snapshot handler should still route using the prefix set captured at lookup time")
49 }
50 },
51 },
52 "overlapping prefix registration is rejected": {
53 run: func(t *testing.T, mgr *Manager) {
54 longHits := 0
55 shortHits := 0
56
57 mgr.RegisterPrefix("config", "collector:", func(Function) { shortHits++ })
58 mgr.RegisterPrefix("config", "collector:job:", func(Function) { longHits++ })
59
60 require.NotNil(t, mgr.functionRegistry["config"])
61 require.Len(t, mgr.functionRegistry["config"].prefixes, 1)
62 _, longRegistered := mgr.functionRegistry["config"].prefixes["collector:job:"]
63 assert.False(t, longRegistered)
64
65 handler, ok := mgr.lookupFunction("config")
66 require.True(t, ok)
67
68 handler(Function{Name: "config", Args: []string{"collector:job:alpha"}})
69 assert.Equal(t, 0, longHits)
70 assert.Equal(t, 1, shortHits)
71 },
72 },
73 }
74
75 for name, tc := range tests {
76 t.Run(name, func(t *testing.T) {
77 tc.run(t, NewManager())
78 })
79 }
80 }