aboutsummaryrefslogtreecommitdiffstats
path: root/actioncable/test/channel/periodic_timers_test.rb
blob: 8d9482577cf1d8de3ebcc12e0c9ee7a873af7adf (plain) (blame)
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
# frozen_string_literal: true

require "test_helper"
require "stubs/test_connection"
require "stubs/room"
require "active_support/time"
require "active_support/testing/method_call_assertions"

class ActionCable::Channel::PeriodicTimersTest < ActiveSupport::TestCase
  include ActiveSupport::Testing::MethodCallAssertions

  class ChatChannel < ActionCable::Channel::Base
    # Method name arg
    periodically :send_updates, every: 1

    # Proc arg
    periodically -> { ping }, every: 2

    # Block arg
    periodically every: 3 do
      ping
    end

    private
      def ping
      end
  end

  setup do
    @connection = TestConnection.new
  end

  test "periodic timers definition" do
    timers = ChatChannel.periodic_timers

    assert_equal 3, timers.size

    timers.each_with_index do |timer, i|
      assert_kind_of Proc, timer[0]
      assert_equal i + 1, timer[1][:every]
    end
  end

  test "disallow negative and zero periods" do
    [ 0, 0.0, 0.seconds, -1, -1.seconds, "foo", :foo, Object.new ].each do |invalid|
      e = assert_raise ArgumentError do
        ChatChannel.periodically :send_updates, every: invalid
      end
      assert_match(/Expected every:/, e.message)
    end
  end

  test "disallow block and arg together" do
    e = assert_raise ArgumentError do
      ChatChannel.periodically(:send_updates, every: 1) { ping }
    end
    assert_match(/not both/, e.message)
  end

  test "disallow unknown args" do
    [ "send_updates", Object.new, nil ].each do |invalid|
      e = assert_raise ArgumentError do
        ChatChannel.periodically invalid, every: 1
      end
      assert_match(/Expected a Symbol/, e.message)
    end
  end

  test "timer start and stop" do
    mock = Minitest::Mock.new
    3.times { mock.expect(:shutdown, nil) }

    assert_called(
      @connection.server.event_loop,
      :timer,
      times: 3,
      returns: mock
    ) do
      channel = ChatChannel.new @connection, "{id: 1}", id: 1

      channel.subscribe_to_channel
      channel.unsubscribe_from_channel
      assert_equal [], channel.send(:active_periodic_timers)
    end

    assert mock.verify
  end
end