topic_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package server
  2. import (
  3. "math/rand"
  4. "sync/atomic"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/require"
  8. )
  9. func TestTopic_CancelSubscribersExceptUser(t *testing.T) {
  10. t.Parallel()
  11. subFn := func(v *visitor, msg *message) error {
  12. return nil
  13. }
  14. canceled1 := atomic.Bool{}
  15. cancelFn1 := func() {
  16. canceled1.Store(true)
  17. }
  18. canceled2 := atomic.Bool{}
  19. cancelFn2 := func() {
  20. canceled2.Store(true)
  21. }
  22. to := newTopic("mytopic")
  23. to.Subscribe(subFn, "", cancelFn1)
  24. to.Subscribe(subFn, "u_phil", cancelFn2)
  25. to.CancelSubscribersExceptUser("u_phil")
  26. require.True(t, canceled1.Load())
  27. require.False(t, canceled2.Load())
  28. }
  29. func TestTopic_CancelSubscribersUser(t *testing.T) {
  30. t.Parallel()
  31. subFn := func(v *visitor, msg *message) error {
  32. return nil
  33. }
  34. canceled1 := atomic.Bool{}
  35. cancelFn1 := func() {
  36. canceled1.Store(true)
  37. }
  38. canceled2 := atomic.Bool{}
  39. cancelFn2 := func() {
  40. canceled2.Store(true)
  41. }
  42. to := newTopic("mytopic")
  43. to.Subscribe(subFn, "u_another", cancelFn1)
  44. to.Subscribe(subFn, "u_phil", cancelFn2)
  45. to.CancelSubscriberUser("u_phil")
  46. require.False(t, canceled1.Load())
  47. require.True(t, canceled2.Load())
  48. }
  49. func TestTopic_Keepalive(t *testing.T) {
  50. t.Parallel()
  51. to := newTopic("mytopic")
  52. to.lastAccess = time.Now().Add(-1 * time.Hour)
  53. to.Keepalive()
  54. require.True(t, to.LastAccess().Unix() >= time.Now().Unix()-2)
  55. require.True(t, to.LastAccess().Unix() <= time.Now().Unix()+2)
  56. }
  57. func TestTopic_Subscribe_DuplicateID(t *testing.T) {
  58. t.Parallel()
  59. to := newTopic("mytopic")
  60. // Fix random seed to force same number generation
  61. rand.Seed(1)
  62. a := rand.Int()
  63. to.subscribers[a] = &topicSubscriber{
  64. userID: "a",
  65. subscriber: nil,
  66. cancel: func() {},
  67. }
  68. subFn := func(v *visitor, msg *message) error {
  69. return nil
  70. }
  71. // Force rand.Int to generate the same id once more
  72. rand.Seed(1)
  73. id := to.Subscribe(subFn, "b", func() {})
  74. res := to.subscribers[id]
  75. require.NotEqual(t, id, a)
  76. require.Equal(t, "b", res.userID, "b")
  77. }