dcache_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package dcache
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. func TestQueue(t *testing.T) {
  7. dcache := New(time.Millisecond)
  8. dcache.Set("key1", "val1")
  9. dcache.Set("key2", "val2")
  10. var key string
  11. key = dcache.pop()
  12. if key != "key1" {
  13. t.Errorf("Expected 'key1' got: %s", key)
  14. }
  15. key = dcache.pop()
  16. if key != "key2" {
  17. t.Errorf("Expected 'key2' got: %s", key)
  18. }
  19. if len(dcache.queue) != 0 {
  20. t.Errorf("Expected len of queue to be 0 got: %d", len(dcache.queue))
  21. }
  22. }
  23. // TestSimpleCRUD simple operations with no worker on.
  24. func TestSimpleCRUD(t *testing.T) {
  25. dcache := New(time.Second)
  26. testKey := "testing-key"
  27. testVal := "testing-val"
  28. dcache.Set(testKey, testVal)
  29. if dcache.Size() != 1 {
  30. t.Errorf("Expected %d got: %d", 1, dcache.Size())
  31. }
  32. val, err := dcache.Get(testKey)
  33. if err != nil {
  34. t.Error(err)
  35. }
  36. if val != testVal {
  37. t.Errorf("Expected %s got: %s", testVal, val)
  38. }
  39. if err := dcache.Remove(testKey, true); err != nil {
  40. t.Error(err)
  41. }
  42. if dcache.Has(testKey) {
  43. t.Errorf("Expected %s to be deleted", testKey)
  44. }
  45. }
  46. func TestWorker(t *testing.T) {
  47. dcache := New(10 * time.Millisecond)
  48. testVals := []string{"1", "2"}
  49. // Checking for collected entries
  50. go func() {
  51. select {
  52. case c := <-dcache.Collect():
  53. // validating value collected
  54. if !Contain(testVals, c.val.(string)) {
  55. t.Errorf("Collected invalid value: %s", c.val)
  56. }
  57. }
  58. }()
  59. dcache.Set("1", "1")
  60. dcache.Set("2", "2")
  61. dcache.StartCycle()
  62. time.Sleep(30 * time.Millisecond)
  63. if dcache.Size() != 0 {
  64. t.Errorf("Expected 0 got: %d", dcache.Size())
  65. }
  66. }
  67. func Contain(arr []string, val string) bool {
  68. for _, str := range arr {
  69. if str == val {
  70. return true
  71. }
  72. }
  73. return false
  74. }