manager_test.go 2.0 KB

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