1
0

ini_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package ini
  2. import (
  3. "reflect"
  4. "strings"
  5. "testing"
  6. )
  7. func TestLoad(t *testing.T) {
  8. src := `
  9. # Comments are ignored
  10. herp = derp
  11. [foo]
  12. hello=world
  13. whitespace should = not matter
  14. ; sneaky semicolon-style comment
  15. multiple = equals = signs
  16. [bar]
  17. this = that`
  18. file, err := Load(strings.NewReader(src))
  19. if err != nil {
  20. t.Fatal(err)
  21. }
  22. check := func(section, key, expect string) {
  23. if value, _ := file.Get(section, key); value != expect {
  24. t.Errorf("Get(%q, %q): expected %q, got %q", section, key, expect, value)
  25. }
  26. }
  27. check("", "herp", "derp")
  28. check("foo", "hello", "world")
  29. check("foo", "whitespace should", "not matter")
  30. check("foo", "multiple", "equals = signs")
  31. check("bar", "this", "that")
  32. }
  33. func TestSyntaxError(t *testing.T) {
  34. src := `
  35. # Line 2
  36. [foo]
  37. bar = baz
  38. # Here's an error on line 6:
  39. wut?
  40. herp = derp`
  41. _, err := Load(strings.NewReader(src))
  42. t.Logf("%T: %v", err, err)
  43. if err == nil {
  44. t.Fatal("expected an error, got nil")
  45. }
  46. syntaxErr, ok := err.(ErrSyntax)
  47. if !ok {
  48. t.Fatal("expected an error of type ErrSyntax")
  49. }
  50. if syntaxErr.Line != 6 {
  51. t.Fatal("incorrect line number")
  52. }
  53. if syntaxErr.Source != "wut?" {
  54. t.Fatal("incorrect source")
  55. }
  56. }
  57. func TestDefinedSectionBehaviour(t *testing.T) {
  58. check := func(src string, expect File) {
  59. file, err := Load(strings.NewReader(src))
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. if !reflect.DeepEqual(file, expect) {
  64. t.Errorf("expected %v, got %v", expect, file)
  65. }
  66. }
  67. // No sections for an empty file
  68. check("", File{})
  69. // Default section only if there are actually values for it
  70. check("foo=bar", File{"": {"foo": "bar"}})
  71. // User-defined sections should always be present, even if empty
  72. check("[a]\n[b]\nfoo=bar", File{
  73. "a": {},
  74. "b": {"foo": "bar"},
  75. })
  76. check("foo=bar\n[a]\nthis=that", File{
  77. "": {"foo": "bar"},
  78. "a": {"this": "that"},
  79. })
  80. }