config_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "os"
  4. "os/user"
  5. "testing"
  6. )
  7. func TestConfig(t *testing.T) {
  8. var filename string = "/invalid"
  9. testValues := map[string]string{
  10. "turns": "5",
  11. "planet": "Earth",
  12. "size": "Medium",
  13. "PI": "Raspberry",
  14. }
  15. u, err := user.Current()
  16. if err != nil {
  17. t.Fatalf("user.Current: %v", err)
  18. }
  19. if u.Name == "root" {
  20. t.Skip("Don't run tests as root.")
  21. }
  22. err = SaveConfig(filename, testValues)
  23. if err == nil {
  24. t.Errorf("SaveConfig: Expected error writing to %s\n", filename)
  25. }
  26. fail, err := LoadConfig(filename)
  27. if fail == nil {
  28. t.Errorf("LoadConfig: Expected error reading %s\n", filename)
  29. }
  30. filename = ".test.config"
  31. os.Remove(filename)
  32. if FileExists(filename) {
  33. t.Errorf("FileExists says %s exists.\n", filename)
  34. }
  35. err = SaveConfig(filename, testValues)
  36. if err != nil {
  37. t.Errorf("SaveConfig: %s\n", err)
  38. }
  39. file, err := os.OpenFile(filename, os.O_APPEND|os.O_RDWR, 0666)
  40. if err != nil {
  41. t.Errorf("OpenFile %s : %s\n", filename, err)
  42. }
  43. file.WriteString("\n")
  44. file.WriteString("# Comment goes here\n")
  45. file.Close()
  46. if !FileExists(filename) {
  47. t.Errorf("FileExists say %s missing.\n", filename)
  48. }
  49. got, err := LoadConfig(filename)
  50. if err != nil {
  51. t.Errorf("LoadConfig: Got error reading %s : %s\n", filename, err)
  52. }
  53. for k, v := range got {
  54. testValue, ok := testValues[k]
  55. if !ok {
  56. t.Errorf("LoadConfig key %s wasn't in original\n", k)
  57. } else {
  58. if testValue != v {
  59. t.Errorf("LoadConfig key %s expected %s, got %s\n", k, v, testValue)
  60. }
  61. }
  62. }
  63. os.Remove(filename)
  64. var b bool
  65. b = SetConfigDefault(&got, "turns", "10")
  66. if !b {
  67. t.Errorf("Setting existing key default failed.\n")
  68. }
  69. b = SetConfigDefault(&got, "missing", "yes")
  70. if b {
  71. t.Errorf("Setting missing default returned true.\n")
  72. }
  73. }