env_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package env
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "testing"
  7. )
  8. func TestDefaultString(t *testing.T) {
  9. v := defaultString("a", "test")
  10. if v != "test" {
  11. t.Fatal("v must be test")
  12. }
  13. if err := os.Setenv("a", "test1"); err != nil {
  14. t.Fatal(err)
  15. }
  16. v = defaultString("a", "test")
  17. if v != "test1" {
  18. t.Fatal("v must be test1")
  19. }
  20. }
  21. func TestEnv(t *testing.T) {
  22. tests := []struct {
  23. flag string
  24. env string
  25. def string
  26. val *string
  27. }{
  28. {
  29. "region",
  30. "REGION",
  31. _region,
  32. &Region,
  33. },
  34. {
  35. "zone",
  36. "ZONE",
  37. _zone,
  38. &Zone,
  39. },
  40. {
  41. "deploy.env",
  42. "DEPLOY_ENV",
  43. _deployEnv,
  44. &DeployEnv,
  45. },
  46. {
  47. "appid",
  48. "APP_ID",
  49. "",
  50. &AppID,
  51. },
  52. {
  53. "http.port",
  54. "DISCOVERY_HTTP_PORT",
  55. _httpPort,
  56. &HTTPPort,
  57. },
  58. {
  59. "gorpc.port",
  60. "DISCOVERY_GORPC_PORT",
  61. _gorpcPort,
  62. &GORPCPort,
  63. },
  64. {
  65. "grpc.port",
  66. "DISCOVERY_GRPC_PORT",
  67. _grpcPort,
  68. &GRPCPort,
  69. },
  70. {
  71. "deploy.color",
  72. "DEPLOY_COLOR",
  73. "",
  74. &Color,
  75. },
  76. }
  77. for _, test := range tests {
  78. // flag set value
  79. t.Run(fmt.Sprintf("%s: flag set", test.env), func(t *testing.T) {
  80. fs := flag.NewFlagSet("", flag.ContinueOnError)
  81. addFlag(fs)
  82. err := fs.Parse([]string{fmt.Sprintf("-%s=%s", test.flag, "test")})
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. if *test.val != "test" {
  87. t.Fatal("val must be test")
  88. }
  89. })
  90. // flag not set, env set
  91. t.Run(fmt.Sprintf("%s: flag not set, env set", test.env), func(t *testing.T) {
  92. *test.val = ""
  93. os.Setenv(test.env, "test2")
  94. fs := flag.NewFlagSet("", flag.ContinueOnError)
  95. addFlag(fs)
  96. err := fs.Parse([]string{})
  97. if err != nil {
  98. t.Fatal(err)
  99. }
  100. if *test.val != "test2" {
  101. t.Fatal("val must be test")
  102. }
  103. })
  104. // flag not set, env not set
  105. t.Run(fmt.Sprintf("%s: flag not set, env not set", test.env), func(t *testing.T) {
  106. *test.val = ""
  107. os.Setenv(test.env, "")
  108. fs := flag.NewFlagSet("", flag.ContinueOnError)
  109. addFlag(fs)
  110. err := fs.Parse([]string{})
  111. if err != nil {
  112. t.Fatal(err)
  113. }
  114. if *test.val != test.def {
  115. t.Fatal("val must be test")
  116. }
  117. })
  118. }
  119. }