require 'test_helper'

class WeeklyProviderStatsWorkerTest < ActiveSupport::TestCase
  def setup
    @provider = FactoryGirl.create(:provider_account)
    @worker = WeeklyProviderStatsWorker.new
  end

  def test_csv
    assert csv = @worker.generate_csv

    stats = CSV.parse(csv)
    assert_equal 2, stats.size
  end

  def test_csv_with_error
    TrafficService.expects(:build).raises(Account::BuyerMethods::ApplicationNotFound)

    assert csv = @worker.generate_csv

    assert_match "\n\n", csv, "contains new line"
  end

  def test_perform
    assert @worker.perform
    email = ActionMailer::Base.deliveries.last
    assert email
  end

  def test_email
    assert email = @worker.email
    assert_equal 1, email.attachments.size

    assert part = email.attachments.first
    assert_equal 'application/zip; filename=provider_stats.csv.zip', part.content_type
  end

  def test_attachment
    assert attachment = @worker.attachment

    stream = StringIO.new(attachment)

    ::Zip::InputStream.open(stream) do |zip|
      assert entry = zip.get_next_entry
      assert_equal 'provider_stats.csv', entry.name
      assert_equal @worker.generate_csv, zip.read
    end
  end

  def test_row_for_provider
    assert row = @worker.row_for_provider(@provider)
    assert_equal @worker.headers.size, row.size
  end

end
