Skip to content
This repository
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 69 lines (54 sloc) 1.695 kb
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
require "spec/helper/all"
require "em-synchrony/iterator"

describe EventMachine::Synchrony::Iterator do

  it "should wait until the iterator is done" do
    EM.synchrony do

      results = []
      i = EM::Synchrony::Iterator.new(1..50, 10).each do |num, iter|
        results.push num
        iter.next
      end

      results.should == (1..50).to_a
      results.size.should == 50
      EventMachine.stop
    end
  end

  it "should map values within the iterator" do
    EM.synchrony do
      results = EM::Synchrony::Iterator.new(1..50, 10).map do |num, iter|
        iter.return(num + 1)
      end

      results.should == (2..51).to_a
      results.size.should == 50
      EventMachine.stop
    end
  end

  it "should sum values within the iterator" do
    EM.synchrony do
      data = (1..50).to_a
      res = EM::Synchrony::Iterator.new(data, 10).inject(0) do |total, num, iter|
        total += num
        iter.return(total)
      end

      res.should == data.inject(:+)
      EventMachine.stop
    end
  end

  it "should fire async http requests in blocks of 2" do
    EM.synchrony do
      num_urls = 4
      concurrency = 2
      delay = 0.25
      
      s = StubServer.new("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nFoo", delay)
      urls = ['http://localhost:8081/'] * num_urls
      
      start = now
      results = EM::Synchrony::Iterator.new(urls, concurrency).map do |url, iter|
        http = EventMachine::HttpRequest.new(url).aget
        http.callback { iter.return(http) }
      end

      results.size.should == 4
      (now - start.to_f).should be_within(delay * 0.15).of(delay * (num_urls / concurrency))
      
      EventMachine.stop
    end
  end

end
Something went wrong with that request. Please try again.