stream_test.rb 1.9 KB
Newer Older
1 2
# frozen_string_literal: true

3
require "test_helper"
U
utilum 已提交
4
require "active_support/testing/method_call_assertions"
U
utilum 已提交
5
require "minitest/mock"
6
require "stubs/test_server"
7 8

class ActionCable::Connection::StreamTest < ActionCable::TestCase
U
utilum 已提交
9 10
  include ActiveSupport::Testing::MethodCallAssertions

11
  class Connection < ActionCable::Connection::Base
12
    attr_reader :connected, :websocket, :errors
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

    def initialize(*)
      super
      @errors = []
    end

    def connect
      @connected = true
    end

    def disconnect
      @connected = false
    end

    def send_async(method, *args)
      send method, *args
    end

    def on_error(message)
      @errors << message
    end
  end

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

  [ EOFError, Errno::ECONNRESET ].each do |closed_exception|
    test "closes socket on #{closed_exception}" do
      run_in_eventmachine do
        connection = open_connection

        # Internal hax = :(
        client = connection.websocket.send(:websocket)
U
utilum 已提交
48 49 50 51 52
        rack_hijack_io = client.instance_variable_get("@stream").instance_variable_get("@rack_hijack_io")
        rack_hijack_io.stub(:write, proc { raise(closed_exception, "foo") }) do
          assert_called(client, :client_gone) do
            client.write("boo")
          end
U
utilum 已提交
53
        end
54 55 56 57 58 59 60
        assert_equal [], connection.errors
      end
    end
  end

  private
    def open_connection
61 62 63 64
      env = Rack::MockRequest.env_for "/test",
        "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket",
        "HTTP_HOST" => "localhost", "HTTP_ORIGIN" => "http://rubyonrails.com"
      env["rack.hijack"] = -> { env["rack.hijack_io"] = StringIO.new }
65 66 67 68 69 70 71 72

      Connection.new(@server, env).tap do |connection|
        connection.process
        connection.send :handle_open
        assert connection.connected
      end
    end
end