require 'lib/executors/stack_executor/chef_node_name_builder'
class Devops::Executor::StackExecutor
  RSpec.describe ChefNodeNameBuilder do
    # test with real response to ensure it is processed correctly
    let(:server_info) do
      {
        "name"=>"stack-achuchkalov-aws-test-1455976199-master01",
        "id"=>"i-fac32c7e",
        "key_name"=>"achuchkalov",
        "private_ip"=>"172.31.11.30",
        "public_ip"=>"52.90.250.51",
        "tags" => {
          "Name"=>"master01",
          "aws:cloudformation:logical-id"=>"EC2Instance1",
          "aws:cloudformation:stack-name"=>"stack-achuchkalov-aws-test-1455976199",
          "StackTemplate"=>"1inst",
          "aws:cloudformation:stack-id" => "arn:aws:cloudformation:us-east-1:736558555923:stack/stack-achuchkalov-aws-test-1455976199/d5f3ca60-d7d8-11e5-9ba1-50d5cd24fac6",
          "cid:deployEnv"=>"test",
          "cid:project"=>"aws",
          "cid:user"=>"root",
          "cid:priority"=>0
        }
      }
    end
    let(:node_name_builder) {
      ChefNodeNameBuilder.new(
        provider_server_info: server_info,
        project_id: 'proj',
        env_id: 'dev'
      )
    }
    let(:build_node_name) { node_name_builder.build_node_name!({}) }

    def set_mask(mask)
      server_info['tags']['cid:node-name-mask'] = mask
    end

    describe '#build_node_name' do
      it 'uses default mask (":project-:env-:instanceid")' do
        expect(build_node_name).to eq 'proj-dev-i-fac32c7e'
      end

      it 'substitutes :project, :env, :instanceid and :instancename' do
        set_mask(':project/:env/:instanceid/:instancename')
        expect(build_node_name).to eq 'proj/dev/i-fac32c7e/master01'
      end

      it 'substitutes :time' do
        set_mask(':project-:time')
        expect(build_node_name).to match /proj-\d+/
      end

      describe 'substitutes incrementers variables :increment-groupname: with numbers depending on @incrementers_values param' do
        it 'starts with 01 for empty hash' do
          set_mask('node-:increment-slave:')
          expect(node_name_builder.build_node_name!({})).to eq 'node-01'
        end

        it "continues with next values if hash isn't empty" do
          set_mask('node-:increment-slave:')
          expect(node_name_builder.build_node_name!({'slave' => nil})).to eq 'node-01'
          expect(node_name_builder.build_node_name!({'slave' => 1})).to eq 'node-02'
          expect(node_name_builder.build_node_name!({'slave' => 50})).to eq 'node-51'
        end

        it 'could substitute different incrementers at once' do
          set_mask('node-:increment-slave:-:increment-master:')
          expect(node_name_builder.build_node_name!({'slave' => 1, 'master' => 3})).to eq 'node-02-04'
        end
      end

    end
  end
end