require 'test_helper' require 'bloom_filter/server' class BloomFilterServerTest < Test::Unit::TestCase def expects_send_data(str) @em.expects(:send_data).with('sig', str, str.size) end context "with a server" do setup do @server = BloomFilter.new_server(100, 0.1).new("sig") @em = EventMachine @filter = @server.class.filter end should "add elements" do @filter.expects(:add).with("hello") expects_send_data("#{[1].pack('N')}#{BloomFilter::Protocol::TRUE}") @server.receive_data("#{[6].pack("N")}#{BloomFilter::Protocol::ADD}hello") end should "check for elements" do @filter.expects(:include?).with("hello").returns(true) expects_send_data("#{[1].pack("N")}#{BloomFilter::Protocol::TRUE}") @server.receive_data("#{[6].pack("N")}#{BloomFilter::Protocol::INCLUDE}hello") end should "check for multiple elements" do @filter.expects(:include?).with("hello").returns(true).twice @filter.expects(:include?).with("bye").returns(false).twice expects_send_data("#{[1].pack("N")}#{1.chr}") # 1.chr => false, true expects_send_data("#{[1].pack("N")}#{2.chr}") # 2.chr => true, false @server.receive_data("#{[10].pack("N")}#{BloomFilter::Protocol::INCLUDE_MANY}hello,bye") @server.receive_data("#{[10].pack("N")}#{BloomFilter::Protocol::INCLUDE_MANY}bye,hello") end should "send dump" do path = "/tmp/f" @filter.expects(:dump).returns("dumped_data") file = mock() File.expects(:open).with(path, 'w').yields(file) file.expects(:write).with("dumped_data") expects_send_data("#{[1].pack("N")}#{BloomFilter::Protocol::TRUE}") @server.receive_data("#{[path.size + 1].pack("N")}#{BloomFilter::Protocol::DUMP}#{path}") end should "send load" do path = "/tmp/f" file = mock() @filter.expects(:replace).with(file) File.expects(:open).with(path, 'r').yields(file) expects_send_data("#{[1].pack("N")}#{BloomFilter::Protocol::TRUE}") @server.receive_data("#{[path.size + 1].pack("N")}#{BloomFilter::Protocol::LOAD}#{path}") end should "properly buffer partial messages" do @filter.expects(:add).with("hello") expects_send_data("#{[1].pack('N')}#{BloomFilter::Protocol::TRUE}") @server.receive_data("#{[6].pack("N")}#{BloomFilter::Protocol::ADD}hel") @server.receive_data("lo") end should "handle two messages sent at once" do @filter.expects(:add).with("hello") expects_send_data("#{[1].pack('N')}#{BloomFilter::Protocol::TRUE}").twice() @filter.expects(:add).with("bye") @server.receive_data("#{[6].pack("N")}#{BloomFilter::Protocol::ADD}hello#{[4].pack("N")}#{BloomFilter::Protocol::ADD}bye") end end end