require "spec_helper"
require 'spec_mock_server'
require 'debci/feeds'

describe Debci::Feeds do
  include Rack::Test::Methods

  class Feeds < Debci::Feeds
    set :raise_errors, true
    set :show_exceptions, false
  end

  def app
    mock_server('/data/feeds', Feeds)
  end

  it 'displays an empty feed without error' do
    Debci::Package.create!(name: 'ruby-defaults')
    get '/data/feeds/r/ruby-defaults.xml'
    expect(last_response.status).to eq(200)
    expect(last_response.headers['Content-Type']).to eq('application/xml')
  end

  it 'returns 404 on non-existing package' do
    get '/data/feeds/m/missing-package.xml'
    expect(last_response.status).to eq(404)
  end

  it 'validates prefix' do
    Debci::Package.create!(name: 'ruby-defaults')
    get '/data/feeds/x/ruby-defaults.xml' # NOTE: the non-matching prefix
    expect(last_response.status).to eq(404)
  end

  it 'displays package news' do
    package = Debci::Package.create!(name: 'ruby-defaults')
    arch = 'arm64'
    user = Debci::User.create!(username: 'theuser')
    time = Time.now
    previous_status = nil
    ["pass", "fail"].each do |result|
      time -= 1.day
      package.jobs.create!(
        package: package,
        suite: 'unstable',
        arch: arch,
        requestor: user,
        date: time,
        duration_seconds: 42,
        version: '1.0-1',
        status: result,
        previous_status: previous_status,
      )
      previous_status = result
    end
    get '/data/feeds/r/ruby-defaults.xml'
    expect(last_response.status).to eq(200)
    expect(last_response.body).to match("<entry>")
  end
end
