api_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package config
  3. import (
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "testing"
  8. "github.com/google/go-cmp/cmp"
  9. )
  10. var _ = fmt.Print
  11. func TestConfigParsing(t *testing.T) {
  12. tdir := t.TempDir()
  13. conf_file := filepath.Join(tdir, "a.conf")
  14. if err := os.Mkdir(filepath.Join(tdir, "sub"), 0o700); err != nil {
  15. t.Fatal(err)
  16. }
  17. w := func(path string, data []byte) {
  18. if err := os.WriteFile(path, data, 0o600); err != nil {
  19. t.Fatal(err)
  20. }
  21. }
  22. w(conf_file, []byte(
  23. `error main
  24. # igno
  25. \re me
  26. a one
  27. #: other
  28. include
  29. \ sub/b.conf
  30. b x
  31. include non-exis
  32. \tent
  33. globin
  34. \clude sub/c?.c
  35. \onf
  36. badline
  37. `))
  38. w(filepath.Join(tdir, "sub/b.conf"), []byte("incb cool\ninclude a.conf"))
  39. w(filepath.Join(tdir, "sub/c1.conf"), []byte("inc1 cool"))
  40. w(filepath.Join(tdir, "sub/c2.conf"), []byte("inc2 cool\nenvinclude ENVINCLUDE"))
  41. w(filepath.Join(tdir, "sub/c.conf"), []byte("inc notcool\nerror sub"))
  42. var parsed_lines []string
  43. pl := func(key, val string) error {
  44. if key == "error" {
  45. return fmt.Errorf("%s", val)
  46. }
  47. parsed_lines = append(parsed_lines, key+" "+val)
  48. return nil
  49. }
  50. p := ConfigParser{LineHandler: pl, override_env: []string{"ENVINCLUDE=env cool\ninclude c.conf"}}
  51. err := p.ParseFiles(conf_file)
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. if err = p.ParseOverrides("over one", "over two"); err != nil {
  56. t.Fatal(err)
  57. }
  58. diff := cmp.Diff([]string{"a one", "incb cool", "b x", "inc1 cool", "inc2 cool", "env cool", "inc notcool", "over one", "over two"}, parsed_lines)
  59. if diff != "" {
  60. t.Fatalf("Unexpected parsed config values:\n%s", diff)
  61. }
  62. bad_lines := []string{}
  63. for _, bl := range p.BadLines() {
  64. bad_lines = append(bad_lines, fmt.Sprintf("%s: %d", filepath.Base(bl.Src_file), bl.Line_number))
  65. }
  66. diff = cmp.Diff([]string{"a.conf: 1", "c.conf: 2", "a.conf: 14"}, bad_lines)
  67. if diff != "" {
  68. t.Fatalf("Unexpected bad lines:\n%s", diff)
  69. }
  70. }