require 'spec_helper'
require 'spec_mock_server'
require 'debci/experiment_test'
require 'debci/web/experiments'

describe Debci::Web::Experiments do
  include WebAppHelper

  def app
    mock_server('/experiments', Debci::Web::Experiments)
  end

  let(:user) { Debci::User.create!(username: "foo@bar.com") }

  let(:experiment) do
    Debci::Experiment.create!(
      title: 'my experiment',
      suite: 'unstable',
      arch: 'arm64',
      package_selector: { "name" => "foobar" },
      test_parameters: { "trigger" => "test" },
      owner: user,
    )
  end

  let(:package) { Debci::Package.create!(name: 'foobar') }

  def new_job(data)
    Debci::Job.new(
      requestor: user,
      suite: 'testing',
      arch: 'arm64',
      package: package,
      **data,
    )
  end

  before(:each) do
    fake_login(user.username)
  end

  it 'lists experiments' do
    title = experiment.title
    get "/experiments/"
    expect(last_response.status).to eq(200)
    expect(last_response.body).to match(title)
  end

  it 'displays a single experiment' do
    id = experiment.id
    get "/experiments/#{id}/"
    expect(last_response.status).to eq(200)
    expect(last_response.body).to match(experiment.title)
  end

  it 'lists links to regression logs' do
    job1 = new_job(status: 'pass').tap(&:save!)
    job2 = new_job(status: 'fail').tap(&:save!)
    test = Debci::ExperimentTest.create!(experiment: experiment, control_job: job1, test_job: job2)
    test.save!
    id = experiment.id

    get "/experiments/#{id}/regression-logs/"
    expect(last_response.headers['Content-Type']).to eq('text/plain')
    expect(last_response.body).to match(%r{/#{job2.run_id}/$})
  end
end
