if ENV["COVERAGE"] != "no"
  begin
    require 'simplecov'
    RSpec.configure do |config|
      unless config.files_to_run.one?
        SimpleCov.start do
          minimum_coverage(93)
          track_files('lib/**/*.rb')
          add_filter(/migrations/)
          add_filter(/spec/)
        end
      end
    end
  rescue LoadError
    $stderr.puts "W: simplecov not installed, not checking test coverage"
  end
end

require 'fileutils'
require 'rack/test'
require 'tmpdir'
require 'yaml'
ENV['DATABASE_URL'] ||= 'sqlite3::memory:'
require 'debci/db'
require 'debci/job'

require 'database_cleaner'
require 'omniauth'
DatabaseCleaner.allow_remote_database_url = true
DatabaseCleaner.strategy = :transaction

Debci.config.backend = 'fake'
Debci.config.quiet = true
Debci::DB.migrate

RSpec.shared_context 'tmpdir' do
  let(:arch) { `dpkg --print-architecture`.strip }
  let(:tmpdir) { Dir.mktmpdir("debci-tests-") }
  after(:each) { FileUtils.rm_rf(tmpdir) }
end

RSpec.shared_context 'no-rabbitmq' do
  before(:each) do
    allow_any_instance_of(Debci::Job).to receive(:enqueue)
  end
end

RSpec.configure do |config|
  config.include_context 'tmpdir'
  config.before(:each) do
    allow(Debci).to receive(:warn)
    allow_any_instance_of(Debci::Config).to receive(:arch_list).and_return([`dpkg --print-architecture`.strip])
    allow_any_instance_of(Debci::Config).to receive(:suite_list).and_return(['unstable', 'testing'])
    allow_any_instance_of(Debci::Config).to receive(:data_basedir).and_return(File.join(tmpdir, '/data'))
    allow_any_instance_of(Debci::Config).to receive(:html_dir).and_return(File.join(tmpdir, '/data/.html'))
  end
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
end

OmniAuth.config.test_mode = true

# module for logging in in tests. Note that for using this, the test scenario
# needs to have the self service app mounted at /user, besides the app being
# tested.
module WebAppHelper
  include Rack::Test::Methods

  def login(username, uid = nil)
    uid ||= username.hash % 1000
    OmniAuth.config.mock_auth[:gitlab] = OmniAuth::AuthHash.new({
      provider: 'gitlab',
      uid: uid,
      info: OmniAuth::AuthHash::InfoHash.new({ username: username })
    })
    get '/user/auth/gitlab/callback'
  end
end
