require 'debci/log'

describe Debci::Log do
  let(:log) do
    Debci::Log.new(log_file).tap(&:parse)
  end
  let(:log_file) { File.join(__dir__, 'log_spec', sample) }

  context 'fake backend log (uncompressed)' do
    let(:sample) { 'foobar.fake.log' }
    it 'has two sections' do
      expect(log.sections.size).to eq(2)
    end
    it 'has output lines' do
      expect(log.sections.first.subsections.last.output.size).to be > 0
    end
    it 'failed' do
      expect(log.sections[1].test?).to eq(true)
      expect(log.sections[1].result).to eq("fail")
    end
    it 'has an object representation' do
      expect(log.inspect).to be_a(String)
    end
  end

  context 'real, but simple log' do
    let(:sample) { 'ruby-localhost.lxc.log.gz' }

    it 'has sections' do
      expect(log.sections.size).to eq(3)
    end

    context 'the preparation section' do
      let(:preparation) { log.sections[0] }

      it 'has 3 subsections' do
        expect(preparation.subsections.size).to eq(3)
        expect(preparation.subsections.map(&:name)).to eq(
          [
            "start run",
            "test bed setup",
            "apt-source",
          ]
        )
      end

      it 'is NOT marked as a test' do
        expect(preparation.test?).to eq(false)
      end
    end

    context 'the test section' do
      let(:test) { log.sections[1] }
      it 'has a PASS result' do
        expect(test.name).to eq("test gem2deb-test-runner")
        expect(test.result).to eq("pass")
      end
      it 'is marked as a test' do
        expect(test.test?).to eq(true)
      end
      it 'has subsections' do
        expect(test.subsections.map(&:name)).to eq(
          [
            "preparing testbed",
            "test run",
            "test results",
          ]
        )
      end
    end
  end

  context 'real and lager log' do
    let(:sample) { 'auto-apt-proxy.lxc.log.gz' }
    it 'has sections' do
      expect(log.sections.size).to eq(12)
    end
  end

  context 'a non-autopkgtest log' do
    let(:sample) { 'not-autopkgtest.log' }
    it 'has a single section with all contents' do
      expect(log.sections.size).to eq(1)
      expect(log.sections[0].output).to eq(["line 1\n", "line 2\n"])
    end
  end

  context "handling non-UTF-8 logs" do
    let(:sample) { 'nonutf8.fake.log' }
    it "doesn't crash" do
      expect(log.sections.size).to be > 0
    end
  end

  context 'handling a installability failure log' do
    let(:sample) { 'mimeo-lxc.log.gz' }
    it 'marks the installation section as failed' do
      expect(log.sections[1].result).to eq("fail")
    end
  end

  context 'handling pg-squeeze failure' do
    let(:sample) { 'pg-squeeze.lxc.log.gz' }
    it 'marks concurrency test as a failure' do
      concurrency = log.sections[2]
      expect(concurrency.name).to eq("test concurrency")
      expect(concurrency.result).to eq("fail")
    end
  end
end
