config_test.go 2.1 KB

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