Class: MutationTester::MutationRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/mutation_tester/mutation_runner.rb

Constant Summary collapse

CANARY_SOURCE =
"raise 'mutation_tester canary: the workspace copy of this source was not executed'\n".freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_file, spec_file, original_content, config) ⇒ MutationRunner

Returns a new instance of MutationRunner.



31
32
33
34
35
36
37
# File 'lib/mutation_tester/mutation_runner.rb', line 31

def initialize(source_file, spec_file, original_content, config)
  @source_file = File.expand_path(source_file)
  @spec_file = File.expand_path(spec_file)
  @original_content = original_content
  @config = config
  @use_bundle_exec = TestCommand.use_bundle_exec?(@source_file)
end

Class Method Details

.backup_path_for(source_file) ⇒ Object



39
40
41
# File 'lib/mutation_tester/mutation_runner.rb', line 39

def self.backup_path_for(source_file)
  "#{File.expand_path(source_file)}.mutation_backup"
end

.recover_in_place_backup(source_file) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/mutation_tester/mutation_runner.rb', line 43

def self.recover_in_place_backup(source_file)
  backup = backup_path_for(source_file)
  return false unless File.exist?(backup)

  File.write(File.expand_path(source_file), File.read(backup))
  File.delete(backup)
  true
end

Instance Method Details

#cleanup_shadow_workspacesObject



230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/mutation_tester/mutation_runner.rb', line 230

def cleanup_shadow_workspaces
  root = @shadow_run_root
  return unless root

  begin
    FileUtils.remove_entry(root) if File.directory?(root)
  rescue SystemCallError
    nil
  end
  @shadow_run_root = nil
  @worker_shadow_root = nil
end

#detect_test_framework(spec_path) ⇒ Object



388
389
390
# File 'lib/mutation_tester/mutation_runner.rb', line 388

def detect_test_framework(spec_path)
  FrameworkDetector.detect(spec_path)
end

#discoverable_project_rootObject



301
302
303
304
305
# File 'lib/mutation_tester/mutation_runner.rb', line 301

def discoverable_project_root
  find_project_root
rescue MutationTester::Error
  nil
end

#find_project_rootObject



307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/mutation_tester/mutation_runner.rb', line 307

def find_project_root
  current = File.dirname(File.expand_path(@source_file))
  loop do
    return current if File.exist?(File.join(current, 'Gemfile')) || File.exist?(File.join(current, '.git'))

    parent = File.dirname(current)

    if parent == current || parent == Dir.home || parent == '/'
      raise MutationTester::Error, "Could not find project root (looking for Gemfile or .git). Stopped at #{parent}"
    end

    current = parent
  end
end

#in_memory_first?Boolean

Returns:

  • (Boolean)


65
66
67
68
69
# File 'lib/mutation_tester/mutation_runner.rb', line 65

def in_memory_first?
  return false if @config.worker_env_var

  %i[in_memory auto].include?(@config.runner)
end

#run(mutations, &progress_callback) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/mutation_tester/mutation_runner.rb', line 52

def run(mutations, &progress_callback)
  announce_worker_env_in_memory_opt_out
  if in_memory_first? && @config.parallel_processes > 1
    run_in_memory_parallel(mutations, &progress_callback)
  elsif in_memory_first?
    run_in_memory_series(mutations, &progress_callback)
  elsif @config.parallel_processes == 1
    run_in_place_series(mutations, &progress_callback)
  else
    run_in_shadow_parallel(mutations, &progress_callback)
  end
end

#run_in_memory_parallel(mutations, &progress_callback) ⇒ Object



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
130
131
132
133
134
135
# File 'lib/mutation_tester/mutation_runner.rb', line 99

def run_in_memory_parallel(mutations, &progress_callback)
  blocker = prepare_in_memory_execution
  return fall_back_to_parallel_file_based(blocker, mutations, &progress_callback) if blocker

  pool = ForkRunner.prepare_in_memory_pool([@config.parallel_processes, mutations.size].min, @in_memory_runner)
  if pool.compact.empty?
    return fall_back_to_parallel_file_based('the preloaded worker pool could not be cloned', mutations, &progress_callback)
  end

  warn "[MutationTester] In-memory execution selected (parallel, #{pool.size} preloaded workers, zero file writes per mutant)."
  announce_load_time_routing(mutations)
  total = mutations.size
  completed_count = 0
  collected = []
  project_root = discoverable_project_root
  reserve_fallback_shadow_root

  report_progress = lambda do |_item, _index, result|
    completed_count += 1
    collected << result
    if progress_callback && (completed_count.even? || completed_count == total)
      progress_callback.call(nil, completed_count)
    end
    raise Parallel::Break if stop_early?(result)
  end

  mapped = with_parallel_interrupt_silenced do
    Parallel.map(mutations, in_processes: pool.size, finish: report_progress) do |mutation|
      run_single_mutation(mutation, :in_memory, project_root)
    end
  end
  mapped || collected
ensure
  ForkRunner.shutdown_in_memory_pool
  shutdown_in_memory_worker
  cleanup_shadow_workspaces
end

#run_in_memory_series(mutations, &progress_callback) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/mutation_tester/mutation_runner.rb', line 71

def run_in_memory_series(mutations, &progress_callback)
  blocker = prepare_in_memory_execution
  return fall_back_to_file_based(blocker, mutations, &progress_callback) if blocker

  warn '[MutationTester] In-memory execution selected (serial, zero file writes per mutant).'
  announce_load_time_routing(mutations)
  results = []
  begin
    mutations.each_with_index do |mutation, index|
      unless @in_memory_runner&.ready?
        return results + fall_back_to_file_based(
          'the in-memory worker terminated unexpectedly',
          mutations.drop(index), completed: index, &progress_callback
        )
      end

      result = run_single_mutation(mutation, :in_memory)
      progress_callback.call(mutation, index + 1) if progress_callback
      results << result
      break if stop_early?(result)
    end
  ensure
    shutdown_in_memory_worker
    cleanup_shadow_workspaces
  end
  results
end

#run_in_place_series(mutations, &progress_callback) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/mutation_tester/mutation_runner.rb', line 164

def run_in_place_series(mutations, &progress_callback)
  write_in_place_backup
  results = []
  mutations.each_with_index do |mutation, index|
    result = run_single_mutation(mutation, :in_place)
    progress_callback.call(mutation, index + 1) if progress_callback
    results << result
    break if stop_early?(result)
  end
  results
ensure
  restore_and_clear_in_place_backup
end

#run_in_shadow_parallel(mutations, &progress_callback) ⇒ Object



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
# File 'lib/mutation_tester/mutation_runner.rb', line 137

def run_in_shadow_parallel(mutations, &progress_callback)
  total = mutations.size
  completed_count = 0
  collected = []
  project_root = find_project_root
  shadow_run_root
  prepare_worker_preloads(total)

  report_progress = lambda do |_item, _index, result|
    completed_count += 1
    collected << result
    if progress_callback && (completed_count.even? || completed_count == total)
      progress_callback.call(nil, completed_count)
    end
    raise Parallel::Break if stop_early?(result)
  end

  mapped = with_parallel_interrupt_silenced do
    Parallel.map(mutations, in_processes: @config.parallel_processes, finish: report_progress) do |mutation|
      run_single_mutation(mutation, :shadow, project_root)
    end
  end
  mapped || collected
ensure
  cleanup_shadow_workspaces
end

#run_mutation_in_memory(mutation, result, project_root = nil) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/mutation_tester/mutation_runner.rb', line 341

def run_mutation_in_memory(mutation, result, project_root = nil)
  runner = active_in_memory_runner
  return in_memory_worker_fallback(mutation, result, project_root, 'the in-memory worker is unavailable') unless runner&.ready?

  outcome = runner.execute_in_memory(
    source: mutation[:code],
    path: @source_file,
    timeout: @config.effective_timeout,
    chdir: Dir.pwd
  )

  if outcome.status == 'error'
    in_memory_apply_fallback(mutation, result, project_root, outcome.message || 'in-memory application failed')
  else
    apply_outcome(result, TestCommand::Result.new(outcome.status == 'pass', outcome.status == 'timeout'))
  end
rescue MutationTester::Error => e
  return in_memory_worker_fallback(mutation, result, project_root, e.message) if project_root

  mark_error(result, e)
rescue StandardError => e
  mark_error(result, e)
end

#run_mutation_in_place(mutation, result) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/mutation_tester/mutation_runner.rb', line 322

def run_mutation_in_place(mutation, result)

  File.write(@source_file, mutation[:code])

  outcome, phase = run_two_phase(mutation) do |example_filters|
    run_specs_in_place(@spec_file, example_filters: example_filters)
  end
  apply_outcome(result, outcome, phase)
rescue StandardError, Interrupt => e
  mark_error(result, e)
  raise e if e.is_a?(Interrupt)
ensure
  File.write(@source_file, @original_content)
end

#run_mutation_in_shadow(mutation, result, project_root) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/mutation_tester/mutation_runner.rb', line 207

def run_mutation_in_shadow(mutation, result, project_root)
  shadow_root = worker_shadow_root(project_root)

  relative_source = Pathname.new(@source_file).relative_path_from(Pathname.new(project_root)).to_s
  shadow_source = File.join(shadow_root, relative_source)
  relative_spec = Pathname.new(@spec_file).relative_path_from(Pathname.new(project_root)).to_s
  shadow_spec = File.join(shadow_root, relative_spec)

  begin
    File.unlink(shadow_source) if File.symlink?(shadow_source)
    File.write(shadow_source, mutation[:code])

    outcome, phase = run_two_phase(mutation) do |example_filters|
      run_specs_in_shadow(shadow_spec, shadow_root, project_root, example_filters: example_filters)
    end
    apply_outcome(result, outcome, phase)
  ensure
    restore_shadow_source(shadow_source, result)
  end
rescue => e
  mark_error(result, e)
end

#run_single_mutation(mutation, strategy, project_root = nil) ⇒ Object



178
179
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
# File 'lib/mutation_tester/mutation_runner.rb', line 178

def run_single_mutation(mutation, strategy, project_root = nil)
  {
    id: mutation[:id],
    type: mutation[:type],
    line: mutation[:line],
    file_path: @source_file,
    original: mutation[:original],
    mutated: mutation[:mutated],
    source_line: mutation[:source_line],
    mutated_line: mutation[:mutated_line],
    killed: false,
    timeout: false,
    status: :survived,
    description: mutation[:description]
  }.tap do |result|
    if unparseable?(mutation[:code])
      mark_stillborn(result)
    elsif strategy == :in_memory && mutation[:in_memory_safe] == false
      run_mutation_load_time(mutation, result, project_root)
    elsif strategy == :in_memory
      run_mutation_in_memory(mutation, result, project_root)
    elsif strategy == :in_place
      run_mutation_in_place(mutation, result)
    else
      run_mutation_in_shadow(mutation, result, project_root)
    end
  end
end

#run_specs_in_place(spec_file, example_filters: []) ⇒ Object



337
338
339
# File 'lib/mutation_tester/mutation_runner.rb', line 337

def run_specs_in_place(spec_file, example_filters: [])
  test_command(spec_file, example_filters: example_filters).run(timeout: @config.effective_timeout)
end

#run_specs_in_shadow(spec_file, working_dir, project_root, example_filters: []) ⇒ Object



296
297
298
299
# File 'lib/mutation_tester/mutation_runner.rb', line 296

def run_specs_in_shadow(spec_file, working_dir, project_root, example_filters: [])
  test_command(spec_file, example_filters: example_filters)
    .run(timeout: @config.effective_timeout, chdir: working_dir, mirror_of: project_root)
end

#run_two_phase(mutation) ⇒ Object



365
366
367
368
369
370
371
372
373
# File 'lib/mutation_tester/mutation_runner.rb', line 365

def run_two_phase(mutation)
  filters = subset_filters(mutation)
  unless filters.empty?
    subset_outcome = yield(filters)
    return [subset_outcome, :subset] unless subset_outcome.passed?
  end

  [yield([]), :full]
end

#shadow_baseline_passes?Boolean

Returns:

  • (Boolean)


243
244
245
# File 'lib/mutation_tester/mutation_runner.rb', line 243

def shadow_baseline_passes?
  shadow_workspace_check == :ok
end

#shadow_copy_project(source, dest) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/mutation_tester/mutation_runner.rb', line 274

def shadow_copy_project(source, dest)
  if source == '/' || source.match?(%r{^/(usr|bin|sbin|etc|var|opt)$})
    raise MutationTester::Error, "Refusing to shadow copy system directory: #{source}"
  end

  Dir.glob("#{source}/*", File::FNM_DOTMATCH).each do |path|
    next if ['.', '..', '.git', 'tmp', 'log', 'coverage', 'node_modules'].include?(File.basename(path))

    basename = File.basename(path)
    target = File.join(dest, basename)

    if File.directory?(path) && !File.symlink?(path)
      FileUtils.mkdir_p(target)
      shadow_copy_project(path, target)
    elsif File.extname(path) == '.rb'
      FileUtils.copy_file(path, target)
    else
      File.symlink(path, target)
    end
  end
end

#shadow_workspace_checkObject



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/mutation_tester/mutation_runner.rb', line 247

def shadow_workspace_check
  project_root = find_project_root

  Dir.mktmpdir do |temp_dir|
    shadow_root = File.join(temp_dir, 'shadow')
    FileUtils.mkdir_p(shadow_root)
    shadow_copy_project(project_root, shadow_root)

    relative_source = Pathname.new(@source_file).relative_path_from(Pathname.new(project_root)).to_s
    shadow_source = File.join(shadow_root, relative_source)
    relative_spec = Pathname.new(@spec_file).relative_path_from(Pathname.new(project_root)).to_s
    shadow_spec = File.join(shadow_root, relative_spec)

    File.unlink(shadow_source)
    File.write(shadow_source, @original_content)
    return :baseline unless run_specs_in_shadow(shadow_spec, shadow_root, project_root).passed?

    File.write(shadow_source, CANARY_SOURCE)
    return :canary if run_specs_in_shadow(shadow_spec, shadow_root, project_root).passed?

    :ok
  end
rescue => e
  warn("[MutationTester] Shadow sanity check could not prepare the shadow workspace: #{e.message}")
  :baseline
end

#subset_filters(mutation) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/mutation_tester/mutation_runner.rb', line 375

def subset_filters(mutation)
  return [] unless @config.test_selection
  return [] unless detect_test_framework(@spec_file) == :rspec

  method_name = mutation[:method_name].to_s
  return [] if method_name.empty?

  content = spec_content
  ["##{method_name}", ".#{method_name}"].select do |token|
    content.match?(/['"]#{Regexp.escape(token)}/)
  end
end