parser_test.go 1.7 KB

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