require "spec_helper"
require 'debci/config'

describe Debci::Config do
  let(:config) { Debci::Config.new }

  KEYS = Debci::Config.members
  TEST_KEYS = {
    autopkgtest_variants: "git:/path/to/autopkgtest git2:/srv/autopkgtest",
  }.freeze

  before(:each) do
    output = KEYS.map do |k|
      value = TEST_KEYS.fetch(k, "value-of-#{k}")
      "#{k}=#{value}"
    end
    @io = StringIO.new("#{output.join("\n")}\n")
    cmd = ['debci', 'config', *KEYS.map(&:to_s)]
    expect(IO).to receive(:popen).with(cmd).and_yield(@io)
  end

  KEYS.each do |key|
    if key =~ /_list$/
      it "knows about #{key}" do
        expect(config.send(key)).to be_a(Array)
      end
    elsif [:quiet, :amqp_ssl, :public_browsing].include?(key)
      it "knows about #{key}" do
        expect(config.send(key)).to_not be_a(String)
      end
    elsif [:data_retention_days, :disk_storage_limit, :failing_packages_per_page, :status_visible_days, :slow_tests_duration_minutes].include?(key)
      it "knows about #{key}" do
        expect(config.send(key)).to be_a(Integer)
      end
    elsif key == :autopkgtest_variants
      it 'known about autopkgtest_variants' do
        expect(config.autopkgtest_variants).to be_a(Hash)
      end
    else
      it "knows about #{key}" do
        expect(config.send(key)).to be_a(String)
      end
    end
    it "strips newlines off #{key}" do
      expect(config.send(key)).to_not end_with("\n")
    end
  end

  it 'reads entry set to empty string in config file as nil' do
    @io.reopen("url_base=https://ci.debian.net\ndistro_name=\n")
    expect(config.distro_name).to be_nil
    expect(config.url_base).to eq('https://ci.debian.net')
  end

  it 'splits at the first equal sign only' do
    url = 'sqlite3:/path/to/db.sqlite3?timeout=5000'
    @io.reopen("database_url=#{url}\n")
    expect(config.database_url).to eq(url)
  end

  it 'reads autopkgtest_variants' do
    expect(config.autopkgtest_variants).to eq({
      'git' => '/path/to/autopkgtest',
      'git2' => '/srv/autopkgtest',
    })
  end

  context 'selecting autopkgtest' do
    it 'default to the system autopkgtest' do
      expect(config.autopkgtest_program).to eq('autopkgtest')
    end

    it 'selects a different autopkgtest' do
      config.autopkgtest = 'git'
      expect(config.autopkgtest_program).to eq('/path/to/autopkgtest')
    end
  end
end
