# -*- coding:binary -*-
require 'spec_helper'

RSpec.describe Msf::Exploit::Git::Packfile do

  let(:git_objects) do
    blob_data = Rex::Text.rand_text_alpha(5..12)
    blob_object = Msf::Exploit::Git::GitObject.build_blob_object(blob_data)

    tree_data =
    {
      mode: '100644',
      file_name: "#{Rex::Text.rand_text_alpha(5..10)}.txt",
      sha1: blob_object.sha1
    }
    tree_object = Msf::Exploit::Git::GitObject.build_tree_object(tree_data)

    commit_obj = Msf::Exploit::Git::GitObject.build_commit_object(tree_sha1: tree_object.sha1)
  end

  let(:test_packfile) do
    Msf::Exploit::Git::Packfile.new('2', git_objects)
  end

  describe '::read_packfile' do
    context 'when invalid data is supplied' do
      it 'should return nil' do
        objs = Msf::Exploit::Git::Packfile.read_packfile(nil)
        expect(objs).to eql(nil)

        objs = Msf::Exploit::Git::Packfile.read_packfile('')
        expect(objs).to eql(nil)

        data = Rex::Text.rand_text_alpha(1..3)
        objs = Msf::Exploit::Git::Packfile.read_packfile(data)
        expect(objs).to eql(nil)
      end
    end

    context 'when a valid packfile is supplied' do
      it 'should return an array of GitObjects' do
        test_objects = test_packfile.git_objects
        objs = Msf::Exploit::Git::Packfile.read_packfile(test_packfile.data)
        expect(objs.length).to eql(test_objects.length)

        objs.each_with_index do |obj, index|
          expect(obj.type).to eql(test_objects[index].type)
          expect(obj.content).to eql(test_objects[index].content)
        end
      end
    end
  end
end
