ringbuffer_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package datautil
  10. import (
  11. "fmt"
  12. "testing"
  13. )
  14. func TestRingBuffer(t *testing.T) {
  15. rb := NewRingBuffer(3)
  16. if !rb.IsEmpty() {
  17. t.Error("Initial buffer should be empty")
  18. return
  19. }
  20. if rb.Poll() != nil {
  21. t.Error("Initial buffer should be empty")
  22. return
  23. }
  24. if rb.Size() != 0 {
  25. t.Error("Unexpected size:", rb.Size())
  26. return
  27. }
  28. rb.Add("AAA")
  29. if rb.Size() != 1 {
  30. t.Error("Unexpected size:", rb.Size())
  31. return
  32. }
  33. rb.Add("BBB")
  34. rb.Add("CCC")
  35. if rb.Size() != 3 {
  36. t.Error("Unexpected size:", rb.Size())
  37. return
  38. }
  39. if rb.String() != `
  40. AAA
  41. BBB
  42. CCC`[1:] {
  43. t.Error("Unexpected result:", rb.String())
  44. return
  45. }
  46. rb.Log("DDD\nEEE")
  47. if rb.Size() != 3 {
  48. t.Error("Unexpected size:", rb.Size())
  49. return
  50. }
  51. if rb.String() != `
  52. CCC
  53. DDD
  54. EEE`[1:] {
  55. t.Error("Unexpected result:", rb.String())
  56. return
  57. }
  58. if p := rb.Poll(); p != "CCC" {
  59. t.Error("Unexpected result:", p)
  60. return
  61. }
  62. if rb.Size() != 2 {
  63. t.Error("Unexpected size:", rb.Size())
  64. return
  65. }
  66. if p := rb.Get(rb.Size() - 1); p != "EEE" {
  67. t.Error("Unexpected result:", p)
  68. return
  69. }
  70. rb = NewRingBuffer(100)
  71. rb.Add("AAA")
  72. if s := rb.String(); s != "AAA" {
  73. t.Error("Unexpected result:", s)
  74. return
  75. }
  76. rb.Add("BBB")
  77. if s := rb.String(); s != "AAA\nBBB" {
  78. t.Error("Unexpected result:", s)
  79. return
  80. }
  81. if s := rb.Slice(); fmt.Sprint(s) != "[AAA BBB]" {
  82. t.Error("Unexpected result:", s)
  83. return
  84. }
  85. rb.Reset()
  86. if !rb.IsEmpty() {
  87. t.Error("Buffer should be empty after a reset")
  88. return
  89. }
  90. }