bucket_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package diskqueue
  2. import (
  3. "crypto/rand"
  4. "io"
  5. "os"
  6. "reflect"
  7. "testing"
  8. )
  9. func Test_membucket(t *testing.T) {
  10. cap := int32(16)
  11. data := make([]byte, _blockByte*cap)
  12. mb := &memBucket{
  13. cap: cap,
  14. data: data,
  15. }
  16. t.Run("test push & pop small data", func(t *testing.T) {
  17. p := []byte("hello world")
  18. err := mb.push(p)
  19. if err != nil {
  20. t.Error(err)
  21. }
  22. ret, err := mb.pop()
  23. if err != nil {
  24. t.Error(err)
  25. } else {
  26. if !reflect.DeepEqual(ret, p) {
  27. t.Errorf("%s not equal %s", ret, p)
  28. }
  29. }
  30. })
  31. t.Run("test push & pop big data", func(t *testing.T) {
  32. p := make([]byte, 1890)
  33. rand.Read(p)
  34. err := mb.push(p)
  35. if err != nil {
  36. t.Error(err)
  37. }
  38. ret, err := mb.pop()
  39. if err != nil {
  40. t.Error(err)
  41. } else {
  42. if !reflect.DeepEqual(ret, p) {
  43. t.Logf("buf: %v", mb.data)
  44. t.Errorf("%v not equal %v", ret, p)
  45. }
  46. }
  47. })
  48. t.Run("push big data", func(t *testing.T) {
  49. p := make([]byte, _blockByte*cap*2)
  50. err := mb.push(p)
  51. if err != errBucketFull {
  52. t.Errorf("expect err == errBucketFull get: %v", err)
  53. }
  54. })
  55. t.Run("pop io.EOF", func(t *testing.T) {
  56. _, err := mb.pop()
  57. if err != io.EOF {
  58. t.Errorf("expect err == io.EOF get: %v", err)
  59. }
  60. })
  61. }
  62. func Test_fileBucket(t *testing.T) {
  63. fpath := "bucket.bin"
  64. defer os.RemoveAll(fpath)
  65. cap := int32(16)
  66. data := make([]byte, _blockByte*cap)
  67. mb := &memBucket{
  68. cap: cap,
  69. data: data,
  70. }
  71. d1 := []byte("hello world")
  72. for i := 0; i < 10; i++ {
  73. mb.push(d1)
  74. }
  75. fp, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. mb.dump(fp)
  80. fp.Close()
  81. fb, err := newFileBucket(fpath)
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. count := 0
  86. for {
  87. ret, err := fb.pop()
  88. if err != nil {
  89. if err != io.EOF {
  90. t.Error(err)
  91. }
  92. break
  93. }
  94. count++
  95. if !reflect.DeepEqual(ret, d1) {
  96. t.Errorf("%v not equal %v", ret, d1)
  97. }
  98. }
  99. if count != 10 {
  100. t.Errorf("expect 10 data get %d", count)
  101. }
  102. }