/go/consul/consul_test.go

https://github.com/xing/beetle · Go · 89 lines · 82 code · 5 blank · 2 comment · 23 complexity · b6aaf52b3ec04b0d91af802cc17c5f73 MD5 · raw file

  1. package consul
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "math/rand"
  7. "os"
  8. "os/exec"
  9. "reflect"
  10. "strconv"
  11. "testing"
  12. "time"
  13. )
  14. var testUrl = "http://localhost:8500"
  15. var testApp = "beetle"
  16. var testToken = "randomstring"
  17. func init() {
  18. log.SetFlags(0)
  19. Verbose = os.Getenv("V") == "1"
  20. if !Verbose {
  21. log.SetOutput(ioutil.Discard)
  22. }
  23. cmd := exec.Command("curl", "-X", "PUT", testUrl+"/v1/kv/datacenters", "-d", "ams1,ams2")
  24. if err := cmd.Run(); err != nil {
  25. fmt.Errorf("could not set up datacenters")
  26. }
  27. cmd = exec.Command("curl", "-X", "PUT", testUrl+"/v1/kv/apps/beetle/config/")
  28. if err := cmd.Run(); err != nil {
  29. fmt.Errorf("could not set up beetle config")
  30. }
  31. cmd = exec.Command("curl", "-X", "PUT", testUrl+"/v1/kv/shared/config/")
  32. if err := cmd.Run(); err != nil {
  33. fmt.Errorf("could not set up shared config")
  34. }
  35. }
  36. func TestConnect(t *testing.T) {
  37. client := NewClient(testUrl, testToken, testApp)
  38. client.Initialize()
  39. if !reflect.DeepEqual(client.dataCenters, []string{"ams1", "ams2"}) {
  40. t.Errorf("could not retrieve datacenters: %v", client.dataCenters)
  41. }
  42. if _, err := client.GetEnv(); err != nil {
  43. t.Errorf("could not retrieve environment: %s", err)
  44. }
  45. }
  46. func TestState(t *testing.T) {
  47. client := NewClient(testUrl, testToken, testApp)
  48. client.Initialize()
  49. value := strconv.Itoa(rand.Int())
  50. if err := client.UpdateState("test", value); err != nil {
  51. t.Errorf("could not set test key: %s", err)
  52. }
  53. kv, err := client.GetState()
  54. if err != nil {
  55. t.Errorf("could not get state keys: %s", err)
  56. }
  57. if kv["test"] != value {
  58. t.Errorf("retrieved test keys have wrong value: %+v", kv)
  59. }
  60. }
  61. func TestWatching(t *testing.T) {
  62. client := NewClient(testUrl, testToken, testApp)
  63. client.Initialize()
  64. channel, err := client.WatchConfig()
  65. if err != nil {
  66. t.Errorf("could not start watching: %v", err)
  67. }
  68. select {
  69. case <-channel:
  70. t.Errorf("we should not have received a new env")
  71. case <-time.After(250 * time.Millisecond):
  72. // this is what we expect
  73. }
  74. if os.Getenv("EDITCONSUL") == "1" {
  75. fmt.Println("please change something in consul")
  76. select {
  77. case env := <-channel:
  78. // this is what we expect
  79. fmt.Printf("new env: %+v", env)
  80. case <-time.After(10 * time.Second):
  81. t.Errorf("we should have received a new env")
  82. }
  83. }
  84. }