parser_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "os"
  4. "testing"
  5. "github.com/beanzilla/gonode"
  6. )
  7. func TestParseLoad(t *testing.T) {
  8. err := os.WriteFile(
  9. "_tmp1.txt",
  10. []byte("pilot Test Pilot\nship \"Little Fish\"\n\tname \"Hello World\"\n\tkind \"Space Fish\""),
  11. 0660,
  12. )
  13. if err != nil {
  14. t.Errorf("Failed creating temp file")
  15. }
  16. defer func() {
  17. err = os.Remove("_tmp1.txt")
  18. if err != nil {
  19. t.Errorf("Failed cleaning up temp file")
  20. }
  21. }()
  22. p := Parser{}
  23. root, err := p.Load("_tmp1.txt")
  24. if err != nil {
  25. t.Fail()
  26. t.Logf("Unexpected error, %v", err)
  27. p.Debug = true
  28. p.Load("_tmp1.txt")
  29. p.Debug = false
  30. }
  31. if root.Len() != 2 {
  32. t.Fail()
  33. t.Logf("Incorrect child count for Root node, expected 2")
  34. t.Logf("%#v", root)
  35. for k := range root.Iter() {
  36. t.Logf("%#v", k)
  37. }
  38. }
  39. k := root.Child(1)
  40. if k == nil {
  41. t.Errorf("Unexpected nil value")
  42. }
  43. if k.Data() != "ship \"Little Fish\"" || k.Depth() != 0 {
  44. t.Errorf("Expected 'ship \"Little Fish\"' depth of 0, got '%s' (depth=%d)", k.Data(), k.Depth())
  45. }
  46. if k.Len() != 2 {
  47. t.Fail()
  48. t.Logf("Incorrect child count for Root.1 node, expected 2")
  49. t.Logf("%#v", k)
  50. for k0 := range k.Iter() {
  51. t.Logf("%#v", k0)
  52. }
  53. }
  54. k1 := k.Child(0)
  55. if k1 == nil {
  56. t.Errorf("Unexpected nil value")
  57. }
  58. if k1.Data() != "name \"Hello World\"" || k1.Depth() != 1 {
  59. t.Errorf("Expected 'name \"Hello World\"' depth 1, got '%s' (depth=%d)", k1.Data(), k1.Depth())
  60. }
  61. }
  62. func TestParseSave(t *testing.T) {
  63. n := gonode.NewNode()
  64. n.NewChildWithData("Hello World")
  65. n1 := n.NewChildWithData("Tacocat")
  66. n1.NewChildWithData("Meow?")
  67. p := Parser{Debug: true}
  68. err := p.Save("_tmp2.txt", n)
  69. if err != nil {
  70. t.Errorf("Unexpected error, %v", err)
  71. }
  72. defer func() {
  73. os.Remove("_tmp2.txt")
  74. }()
  75. }