Class: PDK::Test::Unit

Inherits:
Object
  • Object
show all
Defined in:
lib/pdk/tests/unit.rb

Class Method Summary collapse

Class Method Details

.cmd(tests, opts = {}) ⇒ Object



6
7
8
9
10
# File 'lib/pdk/tests/unit.rb', line 6

def self.cmd(tests, opts = {})
  rake_args = opts[:parallel] ? 'parallel_spec_standalone' : 'spec_standalone'
  rake_args += "[#{tests}]" unless tests.nil? || tests.empty?
  rake_args
end

.cmd_with_args(task) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/pdk/tests/unit.rb', line 18

def self.cmd_with_args(task)
  require 'pdk/util/ruby_version'

  argv = [rake_bin, task]
  argv.unshift(File.join(PDK::Util::RubyVersion.bin_path, 'ruby.exe')) if Gem.win_platform?
  argv
end

.interactive_rake(task, environment) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/pdk/tests/unit.rb', line 38

def self.interactive_rake(task, environment)
  require 'pdk/cli/exec/interactive_command'

  command = PDK::CLI::Exec::InteractiveCommand.new(*cmd_with_args(task)).tap do |c|
    c.context = :module
    c.environment = environment
  end

  command.execute!
end

.invoke(report, options = {}) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/pdk/tests/unit.rb', line 83

def self.invoke(report, options = {})
  require 'pdk/util'
  require 'pdk/util/bundler'

  PDK::Util::Bundler.ensure_binstubs!('rake', 'rspec-core')

  setup

  tests = options[:tests]

  environment = { 'CI_SPEC_OPTIONS' => '--format j' }
  environment['PUPPET_GEM_VERSION'] = options[:puppet] if options[:puppet]
  spinner_msg = options[:parallel] ? _('Running unit tests in parallel.') : _('Running unit tests.')

  if options[:interactive]
    environment['CI_SPEC_OPTIONS'] = if options[:verbose]
                                       '--format documentation'
                                     else
                                       '--format progress'
                                     end
    result = interactive_rake(cmd(tests, options), environment)
    return result[:exit_code]
  end

  result = rake(cmd(tests, options), spinner_msg, environment)

  json_result = if options[:parallel]
                  PDK::Util.find_all_json_in(result[:stdout])
                else
                  PDK::Util.find_first_json_in(result[:stdout])
                end

  if parallel_with_no_tests?(options[:parallel], json_result, result)
    json_result = [{ 'messages' => ['No examples found.'] }]
    result[:exit_code] = 0
  end

  raise PDK::CLI::FatalError, _('Unit test output did not contain a valid JSON result: %{output}') % { output: result[:stdout] } if json_result.nil? || json_result.empty?

  json_result = merge_json_results(json_result) if options[:parallel]

  parse_output(report, json_result, result[:duration])

  result[:exit_code]
ensure
  tear_down if options[:'clean-fixtures']
end

.list(options = {}) ⇒ Object

Returns array of { :id, :full_description }.

Returns:

  • array of { :id, :full_description }

Raises:



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
# File 'lib/pdk/tests/unit.rb', line 217

def self.list(options = {})
  require 'pdk/util'
  require 'pdk/util/bundler'

  PDK::Util::Bundler.ensure_binstubs!('rake')

  environment = {}
  environment['PUPPET_GEM_VERSION'] = options[:puppet] if options[:puppet]

  output = rake('spec_list_json', _('Finding unit tests.'), environment)

  rspec_json = PDK::Util.find_first_json_in(output[:stdout])
  raise PDK::CLI::FatalError, _('Failed to find valid JSON in output from rspec: %{output}' % { output: output[:stdout] }) unless rspec_json
  if rspec_json['examples'].empty?
    rspec_message = rspec_json['messages'][0]
    return [] if rspec_message == 'No examples found.'

    raise PDK::CLI::FatalError, _('Unable to enumerate examples. rspec reported: %{message}' % { message: rspec_message })
  else
    examples = []
    rspec_json['examples'].each do |example|
      examples << { file_path: example['file_path'], id: example['id'], full_description: example['full_description'] }
    end
    examples
  end
end

.merge_json_results(json_data) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/pdk/tests/unit.rb', line 180

def self.merge_json_results(json_data)
  merged_json_result = {}

  # Merge messages
  message_set = Set.new
  json_data.each do |json|
    next unless json['messages']
    message_set |= json['messages']
  end
  merged_json_result['messages'] = message_set.to_a

  # Merge examples
  all_examples = []
  json_data.each do |json|
    next unless json['examples']
    all_examples.concat json['examples']
  end
  merged_json_result['examples'] = all_examples

  # Merge summaries
  summary_hash = {
    'example_count' => 0,
    'failure_count' => 0,
    'pending_count' => 0,
  }
  json_data.each do |json|
    next unless json['summary']
    summary_hash['example_count'] += json['summary']['example_count']
    summary_hash['failure_count'] += json['summary']['failure_count']
    summary_hash['pending_count'] += json['summary']['pending_count']
  end
  merged_json_result['summary'] = summary_hash

  merged_json_result
end

.parallel_with_no_tests?(ran_in_parallel, json_result, result) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
52
53
# File 'lib/pdk/tests/unit.rb', line 49

def self.parallel_with_no_tests?(ran_in_parallel, json_result, result)
  ran_in_parallel && json_result.empty? &&
    ((!result[:exit_code].zero? && result[:stderr].strip =~ %r{Pass files or folders to run$}) ||
     result[:stderr].strip =~ %r{No files for parallel_spec to run against$})
end

.parse_output(report, json_data, duration) ⇒ Object



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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/pdk/tests/unit.rb', line 131

def self.parse_output(report, json_data, duration)
  # Output messages to stderr.
  json_data['messages'] && json_data['messages'].each { |msg| $stderr.puts msg }

  example_results = {
    # Only possibilities are passed, failed, pending:
    # https://github.com/rspec/rspec-core/blob/master/lib/rspec/core/example.rb#L548
    'passed' => [],
    'failed' => [],
    'pending' => [],
  }

  json_data['examples'] && json_data['examples'].each do |ex|
    example_results[ex['status']] << ex if example_results.key?(ex['status'])
  end

  example_results.each do |result, examples|
    # Translate rspec example results to JUnit XML testcase results
    state = case result
            when 'passed' then :passed
            when 'failed' then :failure
            when 'pending' then :skipped
            end

    examples.each do |ex|
      report.add_event(
        source: 'rspec',
        state: state,
        file: ex['file_path'],
        line: ex['line_number'],
        test: ex['full_description'],
        severity: ex['status'],
        message: ex['pending_message'] || (ex['exception'] && ex['exception']['message']) || nil,
        trace: (ex['exception'] && ex['exception']['backtrace']) || nil,
      )
    end
  end

  return unless json_data['summary']

  # TODO: standardize summary output
  $stderr.puts '  ' << _('Evaluated %{total} tests in %{duration} seconds: %{failures} failures, %{pending} pending.') % {
    total: json_data['summary']['example_count'],
    duration: duration,
    failures: json_data['summary']['failure_count'],
    pending: json_data['summary']['pending_count'],
  }
end


55
56
57
58
59
60
61
# File 'lib/pdk/tests/unit.rb', line 55

def self.print_failure(result, exception)
  $stderr.puts ''
  result[:stdout].each_line { |line| $stderr.puts line.rstrip } unless result[:stdout].nil?
  result[:stderr].each_line { |line| $stderr.puts line.rstrip } unless result[:stderr].nil?
  $stderr.puts ''
  raise PDK::CLI::FatalError, exception
end

.rake(task, spinner_text, environment = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pdk/tests/unit.rb', line 26

def self.rake(task, spinner_text, environment = {})
  require 'pdk/cli/exec/command'

  command = PDK::CLI::Exec::Command.new(*cmd_with_args(task)).tap do |c|
    c.context = :module
    c.add_spinner(spinner_text) if spinner_text
    c.environment = environment
  end

  command.execute!
end

.rake_binObject



12
13
14
15
16
# File 'lib/pdk/tests/unit.rb', line 12

def self.rake_bin
  require 'pdk/util'

  @rake ||= File.join(PDK::Util.module_root, 'bin', 'rake')
end

.setupObject



72
73
74
75
76
77
78
79
80
81
# File 'lib/pdk/tests/unit.rb', line 72

def self.setup
  result = rake('spec_prep', _('Preparing to run the unit tests.'))

  return if result[:exit_code].zero?

  tear_down

  PDK.logger.error(_('The spec_prep rake task failed with the following error(s):'))
  print_failure(result, _('Failed to prepare to run the unit tests.'))
end

.tear_downObject



63
64
65
66
67
68
69
70
# File 'lib/pdk/tests/unit.rb', line 63

def self.tear_down
  result = rake('spec_clean', _('Cleaning up after running unit tests.'))

  return if result[:exit_code].zero?

  PDK.logger.error(_('The spec_clean rake task failed with the following error(s):'))
  print_failure(result, _('Failed to clean up after running unit tests'))
end