flag_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package flag
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "testing"
  6. )
  7. var (
  8. dbuser = flag.String("database-user", "default", "db user")
  9. dbhost = flag.String("database-host", "", "db host")
  10. dbpw = flag.String("database-password", "", "db pw")
  11. )
  12. func initTestFlags() {
  13. flag.Set("database-host", "localhost")
  14. flag.Set("database-password", "some-password")
  15. flag.Parse()
  16. }
  17. func TestFlagsrc_Read(t *testing.T) {
  18. initTestFlags()
  19. source := NewSource()
  20. c, err := source.Read()
  21. if err != nil {
  22. t.Error(err)
  23. }
  24. var actual map[string]interface{}
  25. if err := json.Unmarshal(c.Data, &actual); err != nil {
  26. t.Error(err)
  27. }
  28. actualDB := actual["database"].(map[string]interface{})
  29. if actualDB["host"] != *dbhost {
  30. t.Errorf("expected %v got %v", *dbhost, actualDB["host"])
  31. }
  32. if actualDB["password"] != *dbpw {
  33. t.Errorf("expected %v got %v", *dbpw, actualDB["password"])
  34. }
  35. // unset flags should not be loaded
  36. if actualDB["user"] != nil {
  37. t.Errorf("expected %v got %v", nil, actualDB["user"])
  38. }
  39. }
  40. func TestFlagsrc_ReadAll(t *testing.T) {
  41. initTestFlags()
  42. source := NewSource(IncludeUnset(true))
  43. c, err := source.Read()
  44. if err != nil {
  45. t.Error(err)
  46. }
  47. var actual map[string]interface{}
  48. if err := json.Unmarshal(c.Data, &actual); err != nil {
  49. t.Error(err)
  50. }
  51. actualDB := actual["database"].(map[string]interface{})
  52. // unset flag defaults should be loaded
  53. if actualDB["user"] != *dbuser {
  54. t.Errorf("expected %v got %v", *dbuser, actualDB["user"])
  55. }
  56. }