# frozen_string_literal: true

describe Nanoc::Core::ChangesStream do
  let(:simple_stream) do
    described_class.new do |cl|
      cl.unknown
      sleep
    end
  end

  it 'returns a stream of events generated by the listener' do
    buffered_stream = SlowEnumeratorTools.buffer(simple_stream, 1)
    expect(buffered_stream.take(1).to_a).to eq([:unknown])
  end

  describe '#map' do
    it 'returns a new maped enum' do
      stream = simple_stream.map { |e| e.to_s.upcase }
      buffered_stream = SlowEnumeratorTools.buffer(stream, 1)
      expect(buffered_stream.take(1).to_a).to eq(['UNKNOWN'])
    end
  end

  describe '#to_enum' do
    it 'returns an enumerator corresponding to itself' do
      buffered_stream = SlowEnumeratorTools.buffer(simple_stream.to_enum, 1)
      expect(buffered_stream.take(1).to_a).to eq([:unknown])
    end
  end

  describe '#stop' do
    let(:simple_stream) do
      described_class.new do |cl|
        cl.to_stop { $changes_stream_stopped = true }
        sleep
      end
    end

    example do
      SlowEnumeratorTools.buffer(simple_stream, 1)
      sleep 0.1
      expect { simple_stream.stop }.to change { $changes_stream_stopped }.from(nil).to(true)
    end
  end
end
