api_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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(filepath.Join(tdir, "g.py"), []byte(`
  23. print('gpy 1')
  24. print('gpy 2')
  25. `))
  26. w(conf_file, []byte(
  27. `error main
  28. # igno
  29. \re me
  30. a one
  31. #: other
  32. include
  33. \ sub/b.conf
  34. b x
  35. include non-exis
  36. \tent
  37. globin
  38. \clude sub/c?.c
  39. \onf
  40. badline
  41. geninclude g.py
  42. `))
  43. w(filepath.Join(tdir, "sub/b.conf"), []byte("incb cool\ninclude a.conf"))
  44. w(filepath.Join(tdir, "sub/c1.conf"), []byte("inc1 cool"))
  45. w(filepath.Join(tdir, "sub/c2.conf"), []byte("inc2 cool\nenvinclude ENVINCLUDE"))
  46. w(filepath.Join(tdir, "sub/c.conf"), []byte("inc notcool\nerror sub"))
  47. var parsed_lines []string
  48. pl := func(key, val string) error {
  49. if key == "error" {
  50. return fmt.Errorf("%s", val)
  51. }
  52. parsed_lines = append(parsed_lines, key+" "+val)
  53. return nil
  54. }
  55. p := ConfigParser{LineHandler: pl, override_env: []string{"ENVINCLUDE=env cool\ninclude c.conf"}}
  56. err := p.ParseFiles(conf_file)
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. if err = p.ParseOverrides("over one", "over two"); err != nil {
  61. t.Fatal(err)
  62. }
  63. diff := cmp.Diff([]string{"a one", "incb cool", "b x", "inc1 cool", "inc2 cool", "env cool", "inc notcool", "gpy 1", "gpy 2", "over one", "over two"}, parsed_lines)
  64. if diff != "" {
  65. t.Fatalf("Unexpected parsed config values:\n%s", diff)
  66. }
  67. bad_lines := []string{}
  68. for _, bl := range p.BadLines() {
  69. bad_lines = append(bad_lines, fmt.Sprintf("%s: %d", filepath.Base(bl.Src_file), bl.Line_number))
  70. }
  71. diff = cmp.Diff([]string{"a.conf: 1", "c.conf: 2", "a.conf: 14"}, bad_lines)
  72. if diff != "" {
  73. t.Fatalf("Unexpected bad lines:\n%s", diff)
  74. }
  75. }