config_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package config
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. "github.com/BurntSushi/toml"
  7. "github.com/ayn2op/discordo/internal/consts"
  8. tviewkeybind "github.com/ayn2op/tview/keybind"
  9. "github.com/gdamore/tcell/v3"
  10. "github.com/google/go-cmp/cmp"
  11. "github.com/google/go-cmp/cmp/cmpopts"
  12. )
  13. func TestDefaultPath(t *testing.T) {
  14. t.Run("user config dir fallback", func(t *testing.T) {
  15. t.Setenv("AppData", "")
  16. t.Setenv("HOME", "")
  17. t.Setenv("home", "")
  18. t.Setenv("XDG_CONFIG_HOME", "")
  19. // filepath.Join strips the leading dot.
  20. got := DefaultPath()
  21. want := filepath.Join(".", consts.Name, fileName)
  22. if got != want {
  23. t.Fatalf("got = %v, want = %v", got, want)
  24. }
  25. })
  26. }
  27. func TestLoad(t *testing.T) {
  28. t.Run("invalid default config returns error", func(t *testing.T) {
  29. orig := defaultCfg
  30. defaultCfg = []byte("invalid =")
  31. t.Cleanup(func() { defaultCfg = orig })
  32. if _, err := Load("does-not-matter.toml"); err == nil {
  33. t.Fatal(err)
  34. }
  35. })
  36. t.Run("invalid config returns error", func(t *testing.T) {
  37. path := filepath.Join(t.TempDir(), "bad.toml")
  38. if err := os.WriteFile(path, []byte("invalid ="), os.ModePerm); err != nil {
  39. t.Fatal(err)
  40. }
  41. if _, err := Load(path); err == nil {
  42. t.Fatal("expected error")
  43. }
  44. })
  45. t.Run("valid config does not return error", func(t *testing.T) {
  46. path := filepath.Join(t.TempDir(), "good.toml")
  47. if err := os.WriteFile(path, []byte("mouse = false"), os.ModePerm); err != nil {
  48. t.Fatal(err)
  49. }
  50. cfg, err := Load(path)
  51. if err != nil {
  52. t.Fatal(err)
  53. }
  54. if cfg.Mouse != false {
  55. t.Fatalf("got = %v, want = false", cfg.Mouse)
  56. }
  57. })
  58. t.Run("open with bad path returns error (!= ErrNotExist)", func(t *testing.T) {
  59. if _, err := Load("bad\x00path"); err == nil {
  60. t.Fatal("expected error")
  61. }
  62. })
  63. t.Run("missing file uses defaults", func(t *testing.T) {
  64. path := filepath.Join(t.TempDir(), "missing.toml")
  65. cfg, err := Load(path)
  66. if err != nil {
  67. t.Fatal(err)
  68. }
  69. var defCfg Config
  70. if err := toml.Unmarshal(defaultCfg, &defCfg); err != nil {
  71. t.Fatal(err)
  72. }
  73. applyDefaults(&defCfg)
  74. if diff := cmp.Diff(
  75. defCfg,
  76. *cfg,
  77. cmpopts.EquateComparable(tcell.Style{}),
  78. cmpopts.IgnoreUnexported(tviewkeybind.Keybind{}),
  79. cmpopts.IgnoreFields(Config{}, "Path"),
  80. ); diff != "" {
  81. t.Fatalf("got = -, want = +, diff=%s", diff)
  82. }
  83. })
  84. }