topic_test.go 2.0 KB

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