aboutsummaryrefslogtreecommitdiffstats
path: root/test/connection/base_test.rb
blob: bc8b5ba568eb52415413b44c5411a295ee0d6576 (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
require 'test_helper'
require 'stubs/test_server'

class ActionCable::Connection::BaseTest < ActiveSupport::TestCase
  class Connection < ActionCable::Connection::Base
    attr_reader :websocket, :heartbeat, :subscriptions, :message_buffer, :connected

    def connect
      @connected = true
    end

    def disconnect
      @connected = false
    end
  end

  setup do
    @server = TestServer.new
    @server.config.allowed_request_origins = %w( http://rubyonrails.com )

    env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket',
      'HTTP_ORIGIN' => 'http://rubyonrails.com'

    @connection = Connection.new(@server, env)
    @response = @connection.process
  end

  test "making a connection with invalid headers" do
    connection = ActionCable::Connection::Base.new(@server, Rack::MockRequest.env_for("/test"))
    response = connection.process
    assert_equal 404, response[0]
  end

  test "websocket connection" do
    assert @connection.websocket.possible?
    assert @connection.websocket.alive?
  end

  test "rack response" do
    assert_equal [ -1, {}, [] ], @response
  end

  test "on connection open" do
    assert ! @connection.connected

    EventMachine.expects(:add_periodic_timer)
    @connection.websocket.expects(:transmit).with(regexp_matches(/\_ping/))
    @connection.message_buffer.expects(:process!)

    @connection.send :on_open

    assert_equal [ @connection ], @server.connections
    assert @connection.connected
  end

  test "on connection close" do
    # Setup the connection
    EventMachine.stubs(:add_periodic_timer).returns(true)
    @connection.send :on_open
    assert @connection.connected

    EventMachine.expects(:cancel_timer)
    @connection.subscriptions.expects(:unsubscribe_from_all)
    @connection.send :on_close

    assert ! @connection.connected
    assert_equal [], @server.connections
  end

  test "connection statistics" do
    statistics = @connection.statistics

    assert statistics[:identifier].blank?
    assert_kind_of Time, statistics[:started_at]
    assert_equal [], statistics[:subscriptions]
  end

  test "explicitly closing a connection" do
    @connection.websocket.expects(:close)
    @connection.close
  end
end