Class: PDQTest::Puppet

Inherits:
Object
  • Object
show all
Defined in:
lib/pdqtest/puppet.rb

Constant Summary collapse

METADATA =
'metadata.json'
MODULE_DIR =
'/etc/puppetlabs/code/modules'
MAGIC_MARKER =
'@PDQTest'
MAGIC_MARKER_RE =
/#\s*#{MAGIC_MARKER}/
BATS_TESTS =
'./spec/acceptance'
SETUP_SUFFIX =
'__setup.sh'
BEFORE_SUFFIX =
'__before.bats'
AFTER_SUFFIX =
'.bats'
EXAMPLES_DIR =
'./examples'
MANIFESTS_DIR =
'./manifests'
CLASS_RE =
/^class /
FIXTURES =
'fixtures.yml'
TMP_PUPPETFILE =
'.Puppetfile.pdqtest'
@@bats_executed =
[]
@@setup_executed =
[]
@@skip_second_run =
false

Class Method Summary collapse

Class Method Details

.bats_test(container, example, suffix) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/pdqtest/puppet.rb', line 169

def self.bats_test(container, example, suffix)
  testcase = BATS_TESTS + '/' + test_basename(example) + suffix
  if File.exists?(testcase)
    Escort::Logger.output.puts "*** bats test **** bats #{PDQTest::Instance::TEST_DIR}/#{testcase}"
    res = PDQTest::Docker.exec(container, "bats #{PDQTest::Instance::TEST_DIR}/#{testcase}")
    status = PDQTest::Docker.exec_status(res)
    PDQTest::Docker.log_out(res)
    @@bats_executed << testcase
  else
    Escort::Logger.error.error "no #{suffix} tests for #{example} (should be at #{testcase})"
    status = true
  end

  status
end

.class2filename(c) ⇒ Object



78
79
80
81
82
83
84
85
86
# File 'lib/pdqtest/puppet.rb', line 78

def self.class2filename(c)
  if c == module_name
    f = "#{MANIFESTS_DIR}/init.pp"
  else
    f = c.gsub(module_name, MANIFESTS_DIR).gsub('::', File::SEPARATOR) + '.pp'
  end

  f
end

.filename2class(f) ⇒ Object



88
89
90
91
92
93
94
95
96
# File 'lib/pdqtest/puppet.rb', line 88

def self.filename2class(f)
  if f == "#{MANIFESTS_DIR}/init.pp"
    c = module_name
  else
    c = f.gsub(MANIFESTS_DIR, "#{module_name}").gsub(File::SEPARATOR, '::').gsub('.pp','')
  end

  c
end

.find_classesObject

find the available classes in this module



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/pdqtest/puppet.rb', line 142

def self.find_classes()
  mod_name = module_name
  classes = []
  if Dir.exists?(MANIFESTS_DIR)
    Find.find(MANIFESTS_DIR) do |m|
      if m =~ /\.pp$/
        # check the file contains a valid class
        if ! File.readlines(m).grep(CLASS_RE).empty?
          # Class detected, work out class name and add to list of found classes
          classes << filename2class(m)
        else
          Escort::Logger.output.puts "no puppet class found in #{m}"
        end
      end
    end
  end

  classes
end

.find_examplesObject



98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/pdqtest/puppet.rb', line 98

def self.find_examples()
  examples = []
  if Dir.exists?(EXAMPLES_DIR)
    Find.find(EXAMPLES_DIR) do |e|
      if ! File.directory?(e) and ! File.readlines(e).grep(MAGIC_MARKER_RE).empty?
        examples << e
      end
    end
  end
  Escort::Logger.output.puts "examples to run" + examples.to_s
  examples
end

.get_bats_executedObject



40
41
42
# File 'lib/pdqtest/puppet.rb', line 40

def self.get_bats_executed
  @@bats_executed
end

.get_setup_executedObject



44
45
46
# File 'lib/pdqtest/puppet.rb', line 44

def self.get_setup_executed
  @@setup_executed
end

.git_fixturesObject

process fixtures->repositories->* from fixtures.yml if present to generate an array of commands to run ON THE DOCKER VM to checkout the required modules from git



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/pdqtest/puppet.rb', line 114

def self.git_fixtures()
  refresh_cmd = []
  if File.exists?(FIXTURES)
    fixtures = YAML.load_file(FIXTURES)
    if fixtures.has_key?('repositories')
      fixtures['repositories'].each { |fixture, opts|
        target = "spec/fixtures/modules/#{fixture}"
        if opts.instance_of?(String)
          source = opts
          ref    = 'master'
        elsif opts.instance_of?(Hash)
          source = opts['repo']
          if opts.has_key? 'ref'
            ref = opts['ref']
          else
            ref = 'master'
          end
        end

        refresh_cmd << "git_refresh refresh --target-dir #{target} --source-url #{source} --ref #{ref}"
      }
    end
  end

  refresh_cmd
end

.infoObject



316
317
318
319
# File 'lib/pdqtest/puppet.rb', line 316

def self.info
  Escort::Logger.output.puts "Parsed module name: #{module_name}"
  Escort::Logger.output.puts "Link module command: #{link_module}"
end

.install_modulesObject

extract a Puppetfile from metadata.json and install modules using r10k



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/pdqtest/puppet.rb', line 322

def self.install_modules()
  json = JSON.parse(File.read())
  puppetfile = []
  if json.has_key?("dependencies")
    json["dependencies"].each { |dependency|
      line = "mod '#{dependency['name']}'"
      if dependency.has_key?("version_requirement")
        # R10K supports specifc named version or 'latest', not the rich versions defined in metadata. To make this
        # work we will drop any version that specifies a range and just install the latest
        if dependency['version_requirement'].match?(/^\d/)
          line += ", '#{dependency['version_requirement']}'"
        end
      end
      puppetfile << line
    }
  end

  File.open(TMP_PUPPETFILE, "w") do |f|
    f.puts(puppetfile)
  end

  PDQTest::Emoji.emoji_message("🐌", "I'm downloading The Internet, please hold...")

  cmd = "bundle exec r10k puppetfile install --verbose --moduledir ./spec/fixtures/modules --puppetfile #{TMP_PUPPETFILE}"
  status = system(cmd)

  if ! status
    Escort::Logger.error.error "Failed to run the R10K command: #{cmd}"
  end

  status
end

Link all modules - this also saves re-downloading in the acceptance test environment. Of course it means that you must have already run ‘make` to download the modules on your host computer



68
69
70
# File 'lib/pdqtest/puppet.rb', line 68

def self.link_deps
  "test -e #{MODULE_DIR} || mkdir -p #{MODULE_DIR} && ln -s #{PDQTest::Instance::TEST_DIR}/spec/fixtures/modules/* #{MODULE_DIR}"
end

link /etc/facter/facts.d to /testcase/spec/merge_facts to allow additional facts supplied by user to work automatically



74
75
76
# File 'lib/pdqtest/puppet.rb', line 74

def self.link_merge_facts
  "mkdir -p /etc/facter/ && ln -s #{PDQTest::Instance::TEST_DIR}/spec/merge_facts /etc/facter/facts.d"
end


61
62
63
# File 'lib/pdqtest/puppet.rb', line 61

def self.link_module
  "test -e #{MODULE_DIR} || mkdir -p #{MODULE_DIR} && ln -s #{PDQTest::Instance::TEST_DIR} #{MODULE_DIR}/#{module_name}"
end

.module_metadataObject



48
49
50
51
# File 'lib/pdqtest/puppet.rb', line 48

def self.
  file = File.read(Dir.pwd + File::SEPARATOR + )
  JSON.parse(file)
end

.module_nameObject



53
54
55
# File 'lib/pdqtest/puppet.rb', line 53

def self.module_name
  ['name'].split(/[\/-]/)[1]
end

.os_supportObject



57
58
59
# File 'lib/pdqtest/puppet.rb', line 57

def self.os_support
  ['operatingsystem_support'] || []
end

.puppet_apply(example) ⇒ Object



312
313
314
# File 'lib/pdqtest/puppet.rb', line 312

def self.puppet_apply(example)
  "cd #{PDQTest::Instance::TEST_DIR} && puppet apply --detailed-exitcodes #{example}"
end

.reset_bats_executedObject



32
33
34
# File 'lib/pdqtest/puppet.rb', line 32

def self.reset_bats_executed
  @@bats_executed = []
end

.reset_setup_executedObject



36
37
38
# File 'lib/pdqtest/puppet.rb', line 36

def self.reset_setup_executed
  @@setup_executed = []
end

.run(container, example = nil) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/pdqtest/puppet.rb', line 252

def self.run(container, example=nil)
  # we must always have ./spec/fixtures/modules because we need to create a
  # symlink back to the main module inside here...
  # (spec/fixtures/modules/foo -> /testcase)
  if ! Dir.exists?('spec/fixtures/modules')
    Escort::Logger.output.puts
      "creating empty spec/fixtures/modules, if you module fails to run due "
      "to missing dependencies run `make` or `pdqtest all` to retrieve them"
    FileUtils.mkdir_p('spec/fixtures/modules')
  end

  status = true
  Escort::Logger.output.puts "...linking dependencies"
  cmd = link_deps
  res = PDQTest::Docker.exec(container, cmd)
  status &= PDQTest::Docker.exec_status(res)
  if status
    Escort::Logger.output.puts "...linking testcase (this module)"
    cmd = link_module
    res = PDQTest::Docker.exec(container, cmd)
    status &= PDQTest::Docker.exec_status(res)
    if status
      Escort::Logger.output.puts "...linking spec/merge_facts"
      cmd = link_merge_facts
      res = PDQTest::Docker.exec(container, cmd)
      status &= PDQTest::Docker.exec_status(res)
      if status
        Escort::Logger.output.puts "...run tests"
        if example
          status &= run_example(container, example)
          if ! status
            Escort::Logger.error.error "Example #{example} failed!"
          end
        else
          find_examples.each { |e|
            if status
              status &= run_example(container, e)
              if ! status
                Escort::Logger.error.error "Example #{e} failed! - skipping rest of tests"
              end
            end
          }
        end
      else
        PDQTest::Docker.log_all(res)
        Escort::Logger.error.error "Error linking ./spec/merge_facts directory, see previous error, command was: #{cmd}"
      end
    else
      PDQTest::Docker.log_all(res)
      Escort::Logger.error.error "Error linking testcase (this) module, see previous error, command was: #{cmd}"
    end
  else
    PDQTest::Docker.log_all(res)
    Escort::Logger.error.error "Error linking module, see previous error, command was: #{cmd}"
  end

  PDQTest::Emoji.partial_status(status, 'Puppet')
  status
end

.run_example(container, example) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/pdqtest/puppet.rb', line 203

def self.run_example(container, example)
  if ! example.start_with?('./')
    # must prepend ./ to the example or we will not match the correct regexp
    # in test_basename
    example = "./#{example}"
  end
  Escort::Logger.output.puts "testing #{example}"
  status = false

  if setup_test(container, example)

    # see if we should run a bats test before running puppet
    if bats_test(container, example, BEFORE_SUFFIX)

      # run puppet apply - 1st run
      res = PDQTest::Docker.exec(container, puppet_apply(example))
      PDQTest::Docker.log_out(res)
      if PDQTest::Docker.exec_status(res, true) # allow 2 as exit status

        if @@skip_second_run
          Escort::Logger.output.puts "Skipping idempotency check as you requested..."

          # check the system right now since puppet ran OK once
          status = bats_test(container, example, AFTER_SUFFIX)
        else
          # run puppet apply - 2nd run (check for idempotencey/no more changes)
          res = PDQTest::Docker.exec(container, puppet_apply(example))
          PDQTest::Docker.log_out(res)

          # run the bats test if nothing failed yet
          if PDQTest::Docker.exec_status(res) # only allow 0 as exit status
            status = bats_test(container, example, AFTER_SUFFIX)
          else
            Escort::Logger.error.error "Not idempotent: #{example}"
          end
        end
      else
        Escort::Logger.error.error "First puppet run of #{example} failed"
      end
    else
      Escort::Logger.error.error "Bats tests to run before #{example} failed"
    end
  else
    Escort::Logger.error.error "Setup script for #{example} failed"
  end

  status
end

.setup_test(container, example) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/pdqtest/puppet.rb', line 185

def self.setup_test(container, example)
  setup = BATS_TESTS + '/' + test_basename(example) + SETUP_SUFFIX
  if File.exists?(setup)
    Escort::Logger.output.puts "Setting up test for #{example}"
    script = File.read(setup)
    res = PDQTest::Docker.exec(container, script)
    status = PDQTest::Docker.exec_status(res)
    PDQTest::Docker.log_out(res)

    @@setup_executed << setup
  else
    Escort::Logger.output.puts "no setup file for #{example} (should be in #{setup})"
    status = true
  end

  status
end

.skip_second_run(skip_second_run) ⇒ Object



28
29
30
# File 'lib/pdqtest/puppet.rb', line 28

def self.skip_second_run(skip_second_run)
  @@skip_second_run = skip_second_run
end

.test_basename(t) ⇒ Object



162
163
164
165
166
167
# File 'lib/pdqtest/puppet.rb', line 162

def self.test_basename(t)
  # remove examples/ and .pp
  # eg ./examples/apache/mod/mod_php.pp --> apache/mod/mod_php

  t.gsub(EXAMPLES_DIR + '/','').gsub('.pp','')
end