require_relative '../spec_helper'

describe GeoEngineer::Resources::AwsNetworkAclRule do
  common_resource_tests(described_class, described_class.type_from_class_name)
  describe "#_fetch_remote_resources" do
    let(:ec2) { AwsClients.ec2 }
    before do
      stub = ec2.stub_data(
        :describe_network_acls,
        {
          network_acls: [
            {
              network_acl_id: 'name1',
              vpc_id: "1",
              tags: [{ key: 'Name', value: 'one' }],
              entries: [
                {
                  cidr_block: "0.0.0.0/0",
                  egress: true,
                  protocol: "-1",
                  rule_action: "deny",
                  rule_number: 1
                }
              ]
            },
            {
              network_acl_id: 'name2',
              vpc_id: "1",
              tags: [{ key: 'Name', value: 'two' }],
              entries: [
                {
                  cidr_block: "0.0.0.0/0",
                  egress: true,
                  protocol: "-1",
                  rule_action: "deny",
                  rule_number: 2
                }
              ]
            }
          ]
        }
      )
      ec2.stub_responses(:describe_network_acls, stub)
    end

    after do
      ec2.stub_responses(:describe_network_acls, [])
    end

    it 'should create list of hashes from returned AWS SDK' do
      remote_resources = GeoEngineer::Resources::AwsNetworkAclRule._fetch_remote_resources(nil)
      expect(remote_resources.length).to eq(2)
    end
  end

  describe "#_terraform_id" do
    let(:subject) do
      GeoEngineer::Resources::AwsNetworkAclRule.new('aws_network_acl_rule', 'test') {
        cidr_block "0.0.0.0/0"
        egress true
        network_acl_id "acl-22820044"
        protocol "all"
        rule_action "allow"
        rule_number "100"
      }
    end

    it "matches one generated by terraform" do
      expect(subject._geo_id).to eq("nacl-883681663")
    end
  end

  describe '::_number_for_protocol' do
    context "when protocol is nil" do
      it "returns nil" do
        expect(described_class._number_for_protocol(nil)).to eq(nil)
      end
    end

    context "when protocol is already a integer" do
      it "returns that integer if it is a valid protocol number" do
        expect(described_class._number_for_protocol(-1)).to eq(-1)
      end

      it "returns nil if it is not a valid protocol number" do
        expect(described_class._number_for_protocol(-2)).to eq(nil)
      end
    end

    context "when protocol is string" do
      it "returns the corresponding number for valid protocols" do
        expect(described_class._number_for_protocol("all")).to eq(-1)
      end

      it "returns nil for unrecognized protocols" do
        expect(described_class._number_for_protocol(-2)).to eq(nil)
      end
    end
  end
end
