watcher_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package store
  2. import (
  3. "math/rand"
  4. "strconv"
  5. "testing"
  6. "time"
  7. )
  8. func TestWatch(t *testing.T) {
  9. s := CreateStore(100)
  10. watchers := make([]*Watcher, 10)
  11. for i, _ := range watchers {
  12. // create a new watcher
  13. watchers[i] = NewWatcher()
  14. // add to the watchers list
  15. s.AddWatcher("foo", watchers[i], 0)
  16. }
  17. s.Set("/foo/foo", "bar", time.Unix(0, 0), 1)
  18. for _, watcher := range watchers {
  19. // wait for the notification for any changing
  20. res := <-watcher.C
  21. if res == nil {
  22. t.Fatal("watcher is cleared")
  23. }
  24. }
  25. for i, _ := range watchers {
  26. // create a new watcher
  27. watchers[i] = NewWatcher()
  28. // add to the watchers list
  29. s.AddWatcher("foo/foo/foo", watchers[i], 0)
  30. }
  31. s.watcher.stopWatchers()
  32. for _, watcher := range watchers {
  33. // wait for the notification for any changing
  34. res := <-watcher.C
  35. if res != nil {
  36. t.Fatal("watcher is cleared")
  37. }
  38. }
  39. }
  40. // BenchmarkWatch creates 10K watchers watch at /foo/[paht] each time.
  41. // Path is randomly chosen with max depth 10.
  42. // It should take less than 15ms to wake up 10K watchers.
  43. func BenchmarkWatch(b *testing.B) {
  44. s := CreateStore(100)
  45. key := make([]string, 10000)
  46. for i := 0; i < 10000; i++ {
  47. key[i] = "/foo/"
  48. depth := rand.Intn(10)
  49. for j := 0; j < depth; j++ {
  50. key[i] += "/" + strconv.Itoa(rand.Int()%10)
  51. }
  52. }
  53. b.ResetTimer()
  54. for i := 0; i < b.N; i++ {
  55. watchers := make([]*Watcher, 10000)
  56. for i := 0; i < 10000; i++ {
  57. // create a new watcher
  58. watchers[i] = NewWatcher()
  59. // add to the watchers list
  60. s.AddWatcher(key[i], watchers[i], 0)
  61. }
  62. s.watcher.stopWatchers()
  63. for _, watcher := range watchers {
  64. // wait for the notification for any changing
  65. <-watcher.C
  66. }
  67. s.watcher = newWatcherHub()
  68. }
  69. }