require 'spec_helper'
require 'tmpdir'

describe "test parameterized class and hiera" do
  tmpdir = Dir.mktmpdir('puppet')

  manifest = <<~EOT
  class foo (String $content = "bar") {
    file { '#{tmpdir}/foo':
      content => $content
    }
  }
  EOT
  FileUtils.mkdir_p("#{tmpdir}/modules/foo/manifests")
  File.open("#{tmpdir}/modules/foo/manifests/init.pp", 'w') { |f| f.write(manifest) }

  hiera_config = <<~EOT
  ---
  version: 5
  defaults:
    datadir: data
    data_hash: yaml_data
  hierarchy:
    - name: common
      path: common.yaml
  EOT
  File.open("#{tmpdir}/hiera.yml", 'w') { |f| f.write(hiera_config) }

  hiera_data = <<~EOT
  ---
  foo::content: qux
  EOT
  FileUtils.mkdir_p("#{tmpdir}/data")
  File.open("#{tmpdir}/data/common.yaml", 'w') { |f| f.write(hiera_data) }

  describe "test parameterized class with default parameter" do
    describe command("puppet apply --detailed-exitcodes --modulepath #{tmpdir}/modules -e \"include foo\"") do
      its(:exit_status) { should eq 2 }
      its(:stdout) { should match %r{/Stage\[main\]/Foo/File\[#{tmpdir}/foo\]/ensure: defined content as} }

      describe file("#{tmpdir}/foo") do
        its(:content) { should eq "bar" }
      end
    end
  end

  describe "test parameterized class with defined parameter" do
    describe command("puppet apply --detailed-exitcodes --modulepath #{tmpdir}/modules -e \"class { foo: content => 'baz' }\"") do
      its(:exit_status) { should eq 2 }
      its(:stdout) { should match %r{/Stage\[main\]/Foo/File\[#{tmpdir}/foo\]/content: content changed} }

      describe file("#{tmpdir}/foo") do
        its(:content) { should eq "baz" }
      end
    end
  end

  describe "test parameterized class with hiera-provided parameter" do
    describe command("puppet apply --debug --detailed-exitcodes --modulepath #{tmpdir}/modules --hiera_config #{tmpdir}/hiera.yml -e \"include foo\"") do
      its(:exit_status) { should eq 2 }
      its(:stdout) { should match %r{/Stage\[main\]/Foo/File\[#{tmpdir}/foo\]/content: content changed} }

      describe file("#{tmpdir}/foo") do
        its(:content) { should eq "qux" }
      end
    end
  end

end
