Source

event_shipper / spec / lib / event_shipper / udp_spec.rb

Full commit
require 'spec_helper'

require 'event_shipper'
require 'event_shipper/udp'
require 'event_shipper/protocol'

describe EventShipper::UDP do
  let(:udp) { described_class.new('127.0.0.1', 5050) }
  let(:event) { EventShipper::Protocol.event({
    queue: 'queue',
    json: { key: 'value' }.to_json }) }

  describe "#send(hash)" do
    let(:socket) { UDPSocket.new }
    it "turns the hash into a bson string and sends it" do
      socket.bind '127.0.0.1', 5050
      msg, info = nil, nil
      ready = false

      Thread.start do
        msg, info = socket.recvfrom(10 * 1024)
        ready = true
      end

      udp.send(a: 1)
      sleep 0.01 until ready

      transmission = EventShipper::Protocol.parse_transmission(msg)
      transmission.version.should == 1

      transmission.events.first.tap { |event| 
        JSON.parse(event.json).should == {'a' => 1} }
    end 
  end
  describe "#handle_message(string)" do
    let(:msg) { udp.encode(event) }
    
    it "yields a decoded message to the block" do
      button = flexmock('button').tap { |fm| fm.should_receive(:press).
        once }
        
      udp.handle_message(msg) do |message, attributes|
        attributes.should == {:queue=>"queue"}
        message.should == {"key"=>"value"}
        button.press
      end
    end
    it "ignores messages that cannot be decoded" do
      button = flexmock('button').tap { |fm| fm.should_receive(:press).
        never }
        
      udp.handle_message('invalid messages') do
        button.press
      end
    end
  end

  class SeqFilter
    @call_seq = []
    class << self
      attr_accessor :call_seq
    end
    
    def initialize name
      @name = name
    end
    def en obj
      obj.tap { self.class.call_seq << @name }
    end
    def de *args
      args.tap { self.class.call_seq << @name }
    end
  end

  describe '#encode' do
    let(:a) { SeqFilter.new(:a) }
    let(:b) { SeqFilter.new(:b) }
    it 'calls filters in order' do
      SeqFilter.call_seq = []
      udp.wrap a
      udp.wrap b

      udp.encode(event)

      SeqFilter.call_seq.should == [:a, :b]
    end
  end
  describe '#decode' do
    let(:c) { SeqFilter.new(:c) }
    let(:d) { SeqFilter.new(:d) }
    it 'calls filters in reverse order' do
      SeqFilter.call_seq = []
      udp.wrap c
      udp.wrap d

      udp.decode(udp.encode(event))

      SeqFilter.call_seq.should == [:c, :d, :d, :c]
    end

    it 'returns nil if message is invalid' do
      udp.decode('invalid_message').should be_nil
    end
  end
end