require File.join(File.dirname(__FILE__), *%w[.. .. spec_helper]) describe 'Blather::Stream::Component' do class MockServer; end module ServerMock def receive_data(data) @server ||= MockServer.new @server.receive_data data, self end end def mocked_server(times = nil, &block) @client ||= mock() @client.stubs(:stopped) unless @client.respond_to?(:stopped) @client.stubs(:jid=) unless @client.respond_to?(:jid=) MockServer.any_instance.expects(:receive_data).send(*(times ? [:times, times] : [:at_least, 1])).with &block EventMachine::run { # Mocked server EventMachine::start_server '127.0.0.1', 12345, ServerMock # Stream connection EM.connect('127.0.0.1', 12345, Stream::Component, @client, @jid || 'comp.id', 'secret') { |c| @stream = c } } end it 'can be started' do client = mock() params = [client, 'comp.id', 'secret', 'host', 1234] EM.expects(:connect).with do |*parms| parms[0] == 'host' && parms[1] == 1234 && parms[3] == client && parms[4] == 'comp.id' end Stream::Component.start *params end it 'shakes hands with the server' do state = nil mocked_server(2) do |val, server| case state when nil state = :started server.send_data "" val.must_match(/stream:stream/) when :started server.send_data '' EM.stop val.must_equal "#{Digest::SHA1.hexdigest('12345'+"secret")}" end end end it 'starts the stream once the connection is complete' do mocked_server(1) { |val, _| EM.stop; val.must_match(/stream:stream/) } end it 'sends stanzas to the client when the stream is ready' do @client = mock(:stream_started) @client.expects(:call).with do |n| EM.stop n.kind_of?(Stanza::Message) && @stream.ready?.must_equal(true) end state = nil mocked_server(2) do |val, server| case state when nil state = :started server.send_data "" val.must_match(/stream:stream/) when :started server.send_data '' server.send_data "Message!" val.must_equal "#{Digest::SHA1.hexdigest('12345'+"secret")}" end end end end