watchable_store_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. wa := &watching{
  62. key: testKey,
  63. prefix: true,
  64. cur: 0,
  65. }
  66. if err := unsafeAddWatching(&s.synced, string(testKey), wa); err != nil {
  67. t.Error(err)
  68. }
  69. if v, ok := s.synced[string(testKey)]; !ok {
  70. // the key must have had entry in synced
  71. t.Errorf("existence = %v, want true", ok)
  72. } else {
  73. if len(v) != 1 {
  74. // the key must have ONE entry in its watching map
  75. t.Errorf("len(v) = %d, want 1", len(v))
  76. }
  77. }
  78. if err := unsafeAddWatching(&s.synced, string(testKey), wa); err == nil {
  79. // unsafeAddWatching should have returned error
  80. // when putting the same watch twice"
  81. t.Error(`error = nil, want "put the same watch twice"`)
  82. }
  83. }