Module: RSpec::Puppet::Support

Included in:
ClassExampleGroup, DefineExampleGroup, FunctionExampleGroup, HostExampleGroup
Defined in:
lib/rspec-puppet/support.rb

Constant Summary collapse

@@cache =
{}

Instance Method Summary collapse

Instance Method Details

#build_catalog(*args) ⇒ Object



192
193
194
# File 'lib/rspec-puppet/support.rb', line 192

def build_catalog(*args)
  @@cache[args] ||= self.build_catalog_without_cache(*args)
end

#build_catalog_without_cache(nodename, facts_val, code) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/rspec-puppet/support.rb', line 161

def build_catalog_without_cache(nodename, facts_val, code)
  Puppet[:code] = code

  stub_facts! facts_val

  node_obj = Puppet::Node.new(nodename)

  node_obj.merge(facts_val)

  # trying to be compatible with 2.7 as well as 2.6
  if Puppet::Resource::Catalog.respond_to? :find
    Puppet::Resource::Catalog.find(node_obj.name, :use_node => node_obj)
  elsif Puppet.version.to_f >= 4.0
    env = Puppet::Node::Environment.create(
      environment,
      [File.join(Puppet[:environmentpath],'fixtures','modules')],
      File.join(Puppet[:environmentpath],'fixtures','manifests'))
    loader = Puppet::Environments::Static.new(env)
    Puppet.override({:environments => loader}, 'fixtures') do
      node_obj.environment = env
      Puppet::Resource::Catalog.indirection.find(node_obj.name, :use_node => node_obj)
    end
  else
    Puppet::Resource::Catalog.indirection.find(node_obj.name, :use_node => node_obj)
  end
end

#build_node(name, opts = {}) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/rspec-puppet/support.rb', line 223

def build_node(name, opts = {})
  if Puppet.version.to_f >= 4.0
    node_environment = Puppet::Node::Environment.create(
      environment,
      [File.join(Puppet[:environmentpath],'fixtures','modules')],
      File.join(Puppet[:environmentpath],'fixtures','manifests'))
  else
    node_environment = Puppet::Node::Environment.new(environment)
  end
  opts.merge!({:environment => node_environment})
  Puppet::Node.new(name, opts)
end

#class_nameObject



83
84
85
# File 'lib/rspec-puppet/support.rb', line 83

def class_name
  self.class.top_level_description.downcase
end

#environmentObject



10
11
12
# File 'lib/rspec-puppet/support.rb', line 10

def environment
  'rp_env'
end

#escape_special_chars(string) ⇒ Object



202
203
204
205
# File 'lib/rspec-puppet/support.rb', line 202

def escape_special_chars(string)
  string.gsub!(/\$/, "\\$")
  string
end

#facts_hash(node) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/rspec-puppet/support.rb', line 99

def facts_hash(node)
  facts_val = {
    'clientversion' => Puppet::PUPPETVERSION,
    'environment'   => environment,
    'hostname'      => node.split('.').first,
    'fqdn'          => node,
    'domain'        => node.split('.', 2).last,
    'clientcert'    => node
  }

  if RSpec.configuration.default_facts.any?
    facts_val.merge!(munge_facts(RSpec.configuration.default_facts))
  end

  facts_val.merge!(munge_facts(facts)) if self.respond_to?(:facts)
  facts_val
end

#import_strObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rspec-puppet/support.rb', line 35

def import_str
  if File.exists?(File.join(Puppet[:modulepath], 'manifests', 'init.pp'))
    path_to_manifest = File.join([
      Puppet[:modulepath],
      'manifests',
      class_name.split('::')[1..-1]
    ].flatten)
    import_str = [
      "import '#{Puppet[:modulepath]}/manifests/init.pp'",
      "import '#{path_to_manifest}.pp'",
      '',
    ].join("\n")
  elsif File.exists?(Puppet[:modulepath])
    import_str = "import '#{Puppet[:manifest]}'\n"
  else
    import_str = ""
  end

  import_str
end

#load_catalogue(type) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rspec-puppet/support.rb', line 14

def load_catalogue(type)
  vardir = setup_puppet

  if Puppet.version.to_f >= 4.0 or Puppet[:parser] == 'future'
    code = [pre_cond, test_manifest(type)].compact.join("\n")
  else
    code = [import_str, pre_cond, test_manifest(type)].compact.join("\n")
  end

  node_name = nodename(type)

  catalogue = build_catalog(node_name, facts_hash(node_name), code)

  test_module = class_name.split('::').first
  RSpec::Puppet::Coverage.add_filter(type.to_s, self.class.description)
  RSpec::Puppet::Coverage.add_from_catalog(catalogue, test_module)

  FileUtils.rm_rf(vardir) if File.directory?(vardir)
  catalogue
end

#munge_facts(facts) ⇒ Object



196
197
198
199
200
# File 'lib/rspec-puppet/support.rb', line 196

def munge_facts(facts)
  output = {}
  facts.keys.each { |key| output[key.to_s] = facts[key] }
  output
end

#nodename(type) ⇒ Object



74
75
76
77
78
79
80
81
# File 'lib/rspec-puppet/support.rb', line 74

def nodename(type)
  return node if self.respond_to?(:node)
  if [:class, :define, :function].include? type
    Puppet[:certname]
  else
    class_name
  end
end

#param_strObject



117
118
119
120
121
122
# File 'lib/rspec-puppet/support.rb', line 117

def param_str
  params.keys.map do |r|
    param_val = escape_special_chars(params[r].inspect)
    "#{r.to_s} => #{param_val}"
  end.join(', ')
end

#pre_condObject



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/rspec-puppet/support.rb', line 87

def pre_cond
  if self.respond_to?(:pre_condition) && !pre_condition.nil?
    if pre_condition.is_a? Array
      pre_condition.compact.join("\n")
    else
      pre_condition
    end
  else
    nil
  end
end

#rspec_compatibilityObject



236
237
238
239
240
241
242
# File 'lib/rspec-puppet/support.rb', line 236

def rspec_compatibility
  if RSpec::Version::STRING < '3'
    # RSpec 2 compatibility:
    alias_method :failure_message_for_should, :failure_message
    alias_method :failure_message_for_should_not, :failure_message_when_negated
  end
end

#scope(compiler, node_name) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/rspec-puppet/support.rb', line 207

def scope(compiler, node_name)
  if Puppet.version =~ /^2\.[67]/
    # loadall should only be necessary prior to 3.x
    # Please note, loadall needs to happen first when creating a scope, otherwise
    # you might receive undefined method `function_*' errors
    Puppet::Parser::Functions.autoloader.loadall
    scope = Puppet::Parser::Scope.new(:compiler => compiler)
  else
    scope = Puppet::Parser::Scope.new(compiler)
  end

  scope.source = Puppet::Resource::Type.new(:node, node_name)
  scope.parent = compiler.topscope
  scope
end

#setup_puppetObject



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/rspec-puppet/support.rb', line 124

def setup_puppet
  vardir = Dir.mktmpdir
  Puppet[:vardir] = vardir

  if Puppet.version.to_f >= 4.0
    settings = [
      [:environmentpath, :environmentpath],
      [:config, :config],
      [:confdir, :confdir],
      [:hiera_config, :hiera_config],
    ]
  else
    settings = [
      [:modulepath, :module_path],
      [:manifestdir, :manifest_dir],
      [:manifest, :manifest],
      [:templatedir, :template_dir],
      [:config, :config],
      [:confdir, :confdir],
      [:hiera_config, :hiera_config],
      [:parser, :parser],
    ]
  end
  settings.each do |a,b|
    value = self.respond_to?(b) ? self.send(b) : RSpec.configuration.send(b)
    begin
      Puppet[a] = value
    rescue ArgumentError
      Puppet.settings.setdefaults(:main, {a => {:default => value, :desc => a.to_s}})
    end
  end

  # This line is wrong. libdir should never be more than a single path
  Puppet[:libdir] = Dir["#{Puppet[:modulepath]}/*/lib"].entries.join(File::PATH_SEPARATOR)
  vardir
end

#stub_facts!(facts) ⇒ Object



188
189
190
# File 'lib/rspec-puppet/support.rb', line 188

def stub_facts!(facts)
  facts.each { |k, v| Facter.add(k) { setcode { v } } }
end

#subjectObject



6
7
8
# File 'lib/rspec-puppet/support.rb', line 6

def subject
  lambda { catalogue }
end

#test_manifest(type) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rspec-puppet/support.rb', line 56

def test_manifest(type)
  if type == :class
    if !self.respond_to?(:params) || params == {}
      "include #{class_name}"
    else
      "class { '#{class_name}': #{param_str} }"
    end
  elsif type == :define
    if self.respond_to? :params
      "#{class_name} { '#{title}': #{param_str} }"
    else
      "#{class_name} { '#{title}': }"
    end
  elsif type == :host
    nil
  end
end