dirty_page_interval_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package page_writer
  2. import (
  3. "bytes"
  4. "math/rand"
  5. "testing"
  6. )
  7. func TestContinuousIntervals_AddIntervalAppend(t *testing.T) {
  8. c := &ContinuousIntervals{}
  9. // 25, 25, 25
  10. c.AddInterval(getBytes(25, 3), 0)
  11. // _, _, 23, 23, 23, 23
  12. c.AddInterval(getBytes(23, 4), 2)
  13. expectedData(t, c, 0, 25, 25, 23, 23, 23, 23)
  14. }
  15. func TestContinuousIntervals_AddIntervalInnerOverwrite(t *testing.T) {
  16. c := &ContinuousIntervals{}
  17. // 25, 25, 25, 25, 25
  18. c.AddInterval(getBytes(25, 5), 0)
  19. // _, _, 23, 23
  20. c.AddInterval(getBytes(23, 2), 2)
  21. expectedData(t, c, 0, 25, 25, 23, 23, 25)
  22. }
  23. func TestContinuousIntervals_AddIntervalFullOverwrite(t *testing.T) {
  24. c := &ContinuousIntervals{}
  25. // 1,
  26. c.AddInterval(getBytes(1, 1), 0)
  27. // _, 2,
  28. c.AddInterval(getBytes(2, 1), 1)
  29. // _, _, 3, 3, 3
  30. c.AddInterval(getBytes(3, 3), 2)
  31. // _, _, _, 4, 4, 4
  32. c.AddInterval(getBytes(4, 3), 3)
  33. expectedData(t, c, 0, 1, 2, 3, 4, 4, 4)
  34. }
  35. func TestContinuousIntervals_RealCase1(t *testing.T) {
  36. c := &ContinuousIntervals{}
  37. // 25,
  38. c.AddInterval(getBytes(25, 1), 0)
  39. // _, _, _, _, 23, 23
  40. c.AddInterval(getBytes(23, 2), 4)
  41. // _, _, _, 24, 24, 24, 24
  42. c.AddInterval(getBytes(24, 4), 3)
  43. // _, 22, 22
  44. c.AddInterval(getBytes(22, 2), 1)
  45. expectedData(t, c, 0, 25, 22, 22, 24, 24, 24, 24)
  46. }
  47. func TestRandomWrites(t *testing.T) {
  48. c := &ContinuousIntervals{}
  49. data := make([]byte, 1024)
  50. for i := 0; i < 1024; i++ {
  51. start, stop := rand.Intn(len(data)), rand.Intn(len(data))
  52. if start > stop {
  53. start, stop = stop, start
  54. }
  55. rand.Read(data[start : stop+1])
  56. c.AddInterval(data[start:stop+1], int64(start))
  57. expectedData(t, c, 0, data...)
  58. }
  59. }
  60. func expectedData(t *testing.T, c *ContinuousIntervals, offset int, data ...byte) {
  61. start, stop := int64(offset), int64(offset+len(data))
  62. for _, list := range c.lists {
  63. nodeStart, nodeStop := max(start, list.Head.Offset), min(stop, list.Head.Offset+list.Size())
  64. if nodeStart < nodeStop {
  65. buf := make([]byte, nodeStop-nodeStart)
  66. list.ReadData(buf, nodeStart, nodeStop)
  67. if bytes.Compare(buf, data[nodeStart-start:nodeStop-start]) != 0 {
  68. t.Errorf("expected %v actual %v", data[nodeStart-start:nodeStop-start], buf)
  69. }
  70. }
  71. }
  72. }
  73. func getBytes(content byte, length int) []byte {
  74. data := make([]byte, length)
  75. for i := 0; i < length; i++ {
  76. data[i] = content
  77. }
  78. return data
  79. }