synccache_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package lrucache
  2. import (
  3. "sync"
  4. "testing"
  5. "time"
  6. )
  7. func Test_hashCode(t *testing.T) {
  8. /*if hashCode(-1) != 1 {
  9. t.Error("case 1 failed")
  10. }
  11. if hashCode(0) != 0 {
  12. t.Error("case 2 failed")
  13. }
  14. if hashCode(0x7FFFFFFF) != 0x7FFFFFFF {
  15. t.Error("case 3 failed")
  16. }*/
  17. if hashCode("12345") != 3421846044 {
  18. t.Error("case 4 failed")
  19. }
  20. if hashCode("abcdefghijklmnopqrstuvwxyz") != 1277644989 {
  21. t.Error("case 5 failed")
  22. }
  23. /*if hashCode(123.45) != 123 {
  24. t.Error("case 6 failed")
  25. }
  26. if hashCode(-15268.45) != 15268 {
  27. t.Error("case 7 failed")
  28. }*/
  29. }
  30. func Test_nextPowOf2(t *testing.T) {
  31. if nextPowOf2(0) != 2 {
  32. t.Error("case 1 failed")
  33. }
  34. if nextPowOf2(1) != 2 {
  35. t.Error("case 2 failed")
  36. }
  37. if nextPowOf2(2) != 2 {
  38. t.Error("case 3 failed")
  39. }
  40. if nextPowOf2(3) != 4 {
  41. t.Error("case 4 failed")
  42. }
  43. if nextPowOf2(123) != 128 {
  44. t.Error("case 5 failed")
  45. }
  46. if nextPowOf2(0x7FFFFFFF) != 0x80000000 {
  47. t.Error("case 6 failed")
  48. }
  49. }
  50. func Test_timeout(t *testing.T) {
  51. sc := NewSyncCache(1, 2, 2)
  52. sc.Put("1", "2")
  53. if v, ok := sc.Get("1"); !ok || v != "2" {
  54. t.Error("case 1 failed")
  55. }
  56. time.Sleep(2 * time.Second)
  57. if _, ok := sc.Get("1"); ok {
  58. t.Error("case 2 failed")
  59. }
  60. }
  61. func Test_concurrent(t *testing.T) {
  62. sc := NewSyncCache(1, 4, 2)
  63. var wg sync.WaitGroup
  64. for index := 0; index < 100000; index++ {
  65. wg.Add(3)
  66. go func() {
  67. sc.Put("1", "2")
  68. wg.Done()
  69. }()
  70. go func() {
  71. sc.Get("1")
  72. wg.Done()
  73. }()
  74. go func() {
  75. sc.Delete("1")
  76. wg.Done()
  77. }()
  78. }
  79. wg.Wait()
  80. }