cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
config/manager_test.go
88lines · modecode
| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "testing" |
| 6 | |
| 7 | "github.com/rs/zerolog" |
| 8 | "github.com/stretchr/testify/assert" |
| 9 | |
| 10 | "github.com/cloudflare/cloudflared/watcher" |
| 11 | ) |
| 12 | |
| 13 | type mockNotifier struct { |
| 14 | configs []Root |
| 15 | } |
| 16 | |
| 17 | func (n *mockNotifier) ConfigDidUpdate(c Root) { |
| 18 | n.configs = append(n.configs, c) |
| 19 | } |
| 20 | |
| 21 | type mockFileWatcher struct { |
| 22 | path string |
| 23 | notifier watcher.Notification |
| 24 | ready chan struct{} |
| 25 | } |
| 26 | |
| 27 | func (w *mockFileWatcher) Start(n watcher.Notification) { |
| 28 | w.notifier = n |
| 29 | w.ready <- struct{}{} |
| 30 | } |
| 31 | |
| 32 | func (w *mockFileWatcher) Add(string) error { |
| 33 | return nil |
| 34 | } |
| 35 | |
| 36 | func (w *mockFileWatcher) Shutdown() { |
| 37 | |
| 38 | } |
| 39 | |
| 40 | func (w *mockFileWatcher) TriggerChange() { |
| 41 | w.notifier.WatcherItemDidChange(w.path) |
| 42 | } |
| 43 | |
| 44 | func TestConfigChanged(t *testing.T) { |
| 45 | filePath := "config.yaml" |
| 46 | f, err := os.Create(filePath) |
| 47 | assert.NoError(t, err) |
| 48 | defer func() { |
| 49 | _ = f.Close() |
| 50 | _ = os.Remove(filePath) |
| 51 | }() |
| 52 | c := &Root{ |
| 53 | Forwarders: []Forwarder{ |
| 54 | { |
| 55 | URL: "test.daltoniam.com", |
| 56 | Listener: "127.0.0.1:8080", |
| 57 | }, |
| 58 | }, |
| 59 | } |
| 60 | configRead := func(configPath string, log *zerolog.Logger) (Root, error) { |
| 61 | return *c, nil |
| 62 | } |
| 63 | wait := make(chan struct{}) |
| 64 | w := &mockFileWatcher{path: filePath, ready: wait} |
| 65 | |
| 66 | log := zerolog.Nop() |
| 67 | |
| 68 | service, err := NewFileManager(w, filePath, &log) |
| 69 | service.ReadConfig = configRead |
| 70 | assert.NoError(t, err) |
| 71 | |
| 72 | n := &mockNotifier{} |
| 73 | go service.Start(n) |
| 74 | |
| 75 | <-wait |
| 76 | c.Forwarders = append(c.Forwarders, Forwarder{URL: "add.daltoniam.com", Listener: "127.0.0.1:8081"}) |
| 77 | w.TriggerChange() |
| 78 | |
| 79 | service.Shutdown() |
| 80 | |
| 81 | assert.Len(t, n.configs, 2, "did not get 2 config updates as expected") |
| 82 | assert.Len(t, n.configs[0].Forwarders, 1, "not the amount of forwarders expected") |
| 83 | assert.Len(t, n.configs[1].Forwarders, 2, "not the amount of forwarders expected") |
| 84 | |
| 85 | assert.Equal(t, n.configs[0].Forwarders[0].Hash(), c.Forwarders[0].Hash(), "forwarder hashes don't match") |
| 86 | assert.Equal(t, n.configs[1].Forwarders[0].Hash(), c.Forwarders[0].Hash(), "forwarder hashes don't match") |
| 87 | assert.Equal(t, n.configs[1].Forwarders[1].Hash(), c.Forwarders[1].Hash(), "forwarder hashes don't match") |
| 88 | } |