File: publish_subscribe_test.rb

package info (click to toggle)
ruby-redis 5.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,160 kB
  • sloc: ruby: 11,445; makefile: 117; sh: 24
file content (90 lines) | stat: -rw-r--r-- 1,946 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# frozen_string_literal: true

require "helper"

class TestDistributedPublishSubscribe < Minitest::Test
  include Helper::Distributed

  def test_subscribe_and_unsubscribe
    assert_raises Redis::Distributed::CannotDistribute do
      r.subscribe("foo", "bar") {}
    end

    assert_raises Redis::Distributed::CannotDistribute do
      r.subscribe("{qux}foo", "bar") {}
    end
  end

  def test_subscribe_and_unsubscribe_with_tags
    @subscribed = false
    @unsubscribed = false

    thread = Thread.new do
      r.subscribe("foo") do |on|
        on.subscribe do |_channel, total|
          @subscribed = true
          @t1 = total
        end

        on.message do |_channel, message|
          if message == "s1"
            r.unsubscribe
            @message = message
          end
        end

        on.unsubscribe do |_channel, total|
          @unsubscribed = true
          @t2 = total
        end
      end
    end

    # Wait until the subscription is active before publishing
    Thread.pass until @subscribed

    Redis::Distributed.new(NODES).publish("foo", "s1")

    thread.join

    assert @subscribed
    assert_equal 1, @t1
    assert @unsubscribed
    assert_equal 0, @t2
    assert_equal "s1", @message
  end

  def test_subscribe_within_subscribe
    @channels = []

    thread = Thread.new do
      r.subscribe("foo") do |on|
        on.subscribe do |channel, _total|
          @channels << channel

          r.subscribe("bar") if channel == "foo"
          r.unsubscribe if channel == "bar"
        end
      end
    end

    thread.join

    assert_equal ["foo", "bar"], @channels
  end

  def test_other_commands_within_a_subscribe
    r.subscribe("foo") do |on|
      on.subscribe do |_channel, _total|
        r.set("bar", "s2")
        r.unsubscribe("foo")
      end
    end
  end

  def test_subscribe_without_a_block
    assert_raises Redis::SubscriptionError do
      r.subscribe("foo")
    end
  end
end