require 'spec_helper'
require 'debci/extra_apt_sources_list'

describe Debci::ExtraAptSourcesList do
  include_context 'tmpdir'
  before(:each) do
    allow(Debci.config).to receive(:config_dir).and_return(tmpdir)
  end

  let(:extra_apt_sources_list_file) { File.join(tmpdir, 'extra_apt_sources_list.yaml') }
  let(:extra_apt_sources_list) { Debci::ExtraAptSourcesList.new(extra_apt_sources_list_file) }

  let(:user1) do
    Debci::User.create!(uid: 'foo1@bar.com'.hash % 1000, username: 'foo1@bar.com')
  end

  let(:user2) do
    Debci::User.create!(uid: 'foo2@bar.com'.hash % 1000, username: 'foo2@bar.com')
  end

  it 'is empty if there is no extra_apt_sources_list.yaml' do
    FileUtils.rm_f(extra_apt_sources_list_file)
    expect(extra_apt_sources_list.instance_variable_get(:@extra_apt_sources_list)).to be_empty
  end

  def write_extra_apt_sources_list_file(content)
    File.open(extra_apt_sources_list_file, "w") { |f| f.write(content) }
  end

  before(:each) do
    content = [
      "bullseye-security:",
      " entry: deb-src http://security.debian.org/debian-security bullseye-security main",
      "experimental:",
      " entry: deb http://deb.debian.org/debian experimental main",
      " allowed_users:",
      "  - 122132",
      "  - 4252",
      "  - #{user1.id}"
    ]
    write_extra_apt_sources_list_file(content.join("\n"))
  end

  describe '.find' do
    it 'returns Debci::ExtraAptSource instance' do
      expect(extra_apt_sources_list.find("bullseye-security").class).to eq(Debci::ExtraAptSource)
    end
  end

  describe '.allowed_extra_apt_sources' do
    it 'returns list of allowed extra_apt_sources names' do
      expect(extra_apt_sources_list.allowed_extra_apt_sources(user1)).to eq(['bullseye-security', 'experimental'])
      expect(extra_apt_sources_list.allowed_extra_apt_sources(user2)).to eq(['bullseye-security'])
    end
  end
end
