buffer_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package svg // import "github.com/tdewolff/minify/svg"
  2. import (
  3. "bytes"
  4. "strconv"
  5. "testing"
  6. "github.com/tdewolff/parse/svg"
  7. "github.com/tdewolff/parse/xml"
  8. "github.com/tdewolff/test"
  9. )
  10. func TestBuffer(t *testing.T) {
  11. // 0 12 3 4 5 6 7 8 9 01
  12. s := `<svg><path d="M0 0L1 1z"/>text<tag/>text</svg>`
  13. z := NewTokenBuffer(xml.NewLexer(bytes.NewBufferString(s)))
  14. tok := z.Shift()
  15. test.That(t, tok.Hash == svg.Svg, "first token is <svg>")
  16. test.That(t, z.pos == 0, "shift first token and restore position")
  17. test.That(t, len(z.buf) == 0, "shift first token and restore length")
  18. test.That(t, z.Peek(2).Hash == svg.D, "third token is d")
  19. test.That(t, z.pos == 0, "don't change position after peeking")
  20. test.That(t, len(z.buf) == 3, "mtwo tokens after peeking")
  21. test.That(t, z.Peek(8).Hash == svg.Svg, "ninth token is <svg>")
  22. test.That(t, z.pos == 0, "don't change position after peeking")
  23. test.That(t, len(z.buf) == 9, "nine tokens after peeking")
  24. test.That(t, z.Peek(9).TokenType == xml.ErrorToken, "tenth token is an error")
  25. test.That(t, z.Peek(9) == z.Peek(10), "tenth and eleventh token are EOF")
  26. test.That(t, len(z.buf) == 10, "ten tokens after peeking")
  27. _ = z.Shift()
  28. tok = z.Shift()
  29. test.That(t, tok.Hash == svg.Path, "third token is <path>")
  30. test.That(t, z.pos == 2, "don't change position after peeking")
  31. }
  32. func TestAttributes(t *testing.T) {
  33. r := bytes.NewBufferString(`<rect x="0" y="1" width="2" height="3" rx="4" ry="5"/>`)
  34. l := xml.NewLexer(r)
  35. tb := NewTokenBuffer(l)
  36. tb.Shift()
  37. for k := 0; k < 2; k++ { // run twice to ensure similar results
  38. attrs, _ := tb.Attributes(svg.X, svg.Y, svg.Width, svg.Height, svg.Rx, svg.Ry)
  39. for i := 0; i < 6; i++ {
  40. test.That(t, attrs[i] != nil, "attr must not be nil")
  41. val := string(attrs[i].AttrVal)
  42. j, _ := strconv.ParseInt(val, 10, 32)
  43. test.That(t, int(j) == i, "attr data is bad at position", i)
  44. }
  45. }
  46. }
  47. ////////////////////////////////////////////////////////////////
  48. func BenchmarkAttributes(b *testing.B) {
  49. r := bytes.NewBufferString(`<rect x="0" y="1" width="2" height="3" rx="4" ry="5"/>`)
  50. l := xml.NewLexer(r)
  51. tb := NewTokenBuffer(l)
  52. tb.Shift()
  53. tb.Peek(6)
  54. for i := 0; i < b.N; i++ {
  55. tb.Attributes(svg.X, svg.Y, svg.Width, svg.Height, svg.Rx, svg.Ry)
  56. }
  57. }