watchable_store_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package storage
  15. import (
  16. "os"
  17. "testing"
  18. )
  19. func TestWatch(t *testing.T) {
  20. s := newWatchableStore(tmpPath)
  21. defer func() {
  22. s.store.Close()
  23. os.Remove(tmpPath)
  24. }()
  25. testKey := []byte("foo")
  26. testValue := []byte("bar")
  27. s.Put(testKey, testValue)
  28. w := s.NewWatcher()
  29. w.Watch(testKey, true, 0)
  30. if _, ok := s.synced[string(testKey)]; !ok {
  31. // the key must have had an entry in synced
  32. t.Errorf("existence = %v, want true", ok)
  33. }
  34. }
  35. func TestNewWatcherCancel(t *testing.T) {
  36. s := newWatchableStore(tmpPath)
  37. defer func() {
  38. s.store.Close()
  39. os.Remove(tmpPath)
  40. }()
  41. testKey := []byte("foo")
  42. testValue := []byte("bar")
  43. s.Put(testKey, testValue)
  44. w := s.NewWatcher()
  45. _, cancel := w.Watch(testKey, true, 0)
  46. cancel()
  47. if _, ok := s.synced[string(testKey)]; ok {
  48. // the key shoud have been deleted
  49. t.Errorf("existence = %v, want false", ok)
  50. }
  51. }
  52. func TestUnsafeAddWatching(t *testing.T) {
  53. s := newWatchableStore(tmpPath)
  54. defer func() {
  55. s.store.Close()
  56. os.Remove(tmpPath)
  57. }()
  58. testKey := []byte("foo")
  59. testValue := []byte("bar")
  60. s.Put(testKey, testValue)
  61. size := 10
  62. ws := make([]*watching, size)
  63. for i := 0; i < size; i++ {
  64. ws[i] = &watching{
  65. key: testKey,
  66. prefix: true,
  67. cur: 0,
  68. }
  69. }
  70. // to test if unsafeAddWatching is correctly updating
  71. // synced map when adding new watching.
  72. for i, wa := range ws {
  73. if err := unsafeAddWatching(&s.synced, string(testKey), wa); err != nil {
  74. t.Errorf("#%d: error = %v, want nil", i, err)
  75. }
  76. if v, ok := s.synced[string(testKey)]; !ok {
  77. t.Errorf("#%d: ok = %v, want ok true", i, ok)
  78. } else {
  79. if len(v) != i+1 {
  80. t.Errorf("#%d: len(v) = %d, want %d", i, len(v), i+1)
  81. }
  82. if _, ok := v[wa]; !ok {
  83. t.Errorf("#%d: ok = %v, want ok true", i, ok)
  84. }
  85. }
  86. }
  87. }