Sha256: 082dacbc7e2767fe2079a4391ab49af2067041f7c8b7821691235794ac0405e0

Contents?: true

Size: 1.35 KB

Versions: 24

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true
module Msgr
  class TestPool
    def initialize(*)
      @queue = []
      @mutex = Mutex.new
      @event = ConditionVariable.new
    end

    def post(message, &block)
      @mutex.synchronize do
        @queue << [block, message]
        @event.signal
      end
    end

    def run(**kwargs)
      @mutex.synchronize do
        ns_run(**kwargs)
      end
    end

    def clear
      @mutex.synchronize do
        @queue.clear
      end
    end

    alias reset clear

    private

    # rubocop:disable Metrics/AbcSize
    # rubocop:disable Metrics/MethodLength
    def ns_run(count: 1, timeout: 5)
      received = 0

      while received < count
        if (item = @queue.pop)
          item[0].call item[1]
          received += 1
        else
          start = Time.now.to_f

          @event.wait(@mutex, timeout)

          stop = Time.now.to_f
          diff = stop - start
          timeout -= diff

          if timeout <= 0
            raise TimeoutError.new \
              "Expected to receive #{count} messages but received #{received}."
          end
        end
      end
    end

    class << self
      def new(*args)
        @instance ||= super(*args)
      end

      def run(*args)
        new.run(*args)
      end

      def clear
        @instance ? @instance.clear : nil
      end

      alias reset clear
    end
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
msgr-0.15.2.1.b157 lib/msgr/test_pool.rb
msgr-0.15.2.1.b156 lib/msgr/test_pool.rb
msgr-0.15.2.1.b155 lib/msgr/test_pool.rb
msgr-0.15.2.1.b154 lib/msgr/test_pool.rb
msgr-0.15.2.1.b152 lib/msgr/test_pool.rb
msgr-0.15.1.1.b151 lib/msgr/test_pool.rb
msgr-0.15.2 lib/msgr/test_pool.rb
msgr-0.15.1.1.b150 lib/msgr/test_pool.rb
msgr-0.15.1.1.b146 lib/msgr/test_pool.rb
msgr-0.15.1.1.b145 lib/msgr/test_pool.rb
msgr-0.15.1.1.b144 lib/msgr/test_pool.rb
msgr-0.15.1.1.b143 lib/msgr/test_pool.rb
msgr-0.15.1.1.b141 lib/msgr/test_pool.rb
msgr-0.15.0.1.b140 lib/msgr/test_pool.rb
msgr-0.15.1 lib/msgr/test_pool.rb
msgr-0.15.0.1.b139 lib/msgr/test_pool.rb
msgr-0.15.0.1.b136 lib/msgr/test_pool.rb
msgr-0.15.0.1.b135 lib/msgr/test_pool.rb
msgr-0.15.0.1.b134 lib/msgr/test_pool.rb
msgr-0.15.0.1.b131 lib/msgr/test_pool.rb