Module: Mutineer::JobPlan
- Defined in:
- lib/mutineer/job_plan.rb
Overview
The job vocabulary every backend shares: which mutants run, which are
ignored, which lines --since keeps, which tests cover a mutant, and the
source and test directories a run touches. Runner, DaemonBackend and
CLI each require this file, so job selection cannot drift between them
(score parity), and the require graph has no cycles (#75). Never require
runner.rb, daemon_backend.rb or cli.rb from here: each requires this file.
Class Method Summary collapse
-
.abort_if_unclean!(coverage_map, framework: nil) ⇒ void
Aborts the run when coverage capture saw a red unmutated suite.
-
.apply_unpaired_since!(counts, jobs, ignored, source_map, files, config) ⇒ void
private
Replaces pending unpaired counts with the jobs
--sincekeeps. -
.clean_failure_detail(coverage_map, files) ⇒ String
private
Joins capped failure reports for the unclean files (#360).
-
.clean_timeout_message(timeouts) ⇒ String
private
Says which clean checks hit their deadline and how to raise it.
-
.collect_jobs(config, operator_classes) ⇒ Array(Array, Array<Result>, Hash<String,String>, Hash{Symbol => Hash})
Collect every (subject, mutation, id) up front so a backend can run them.
-
.coverage_selection(source_file, mutation, subject, source, coverage_map) ⇒ Array(Symbol, Object)
Coverage-based test selection, shared by the in-process (Runner.run) and daemon paths so both narrow identically (score parity).
-
.filter_since(jobs, source_map, config, changed: nil) ⇒ Object
--since: keep only jobs whose mutation lands on a line changed since the git ref.
-
.hook_mutant(mutated, mutation, subject, source, reach_path: nil, reach_key: nil) ⇒ Array(String, Hash{Symbol => Object})
The reload mutant text for a def in a concern's
includedorprependedblock (#297): the mutated file with one statement added just before the hook call,::Mutineer::ConcernBlocks.store_hook_def do <mutated def> end. -
.line_ops(entry) ⇒ Symbol, ...
The operator set for one suppress-map entry.
-
.line_reason(entry) ⇒ String?
The reason text on one suppress-map entry, when the entry stores one.
-
.load_verdict(result, source_file, mutation, subject, source, coverage_map) ⇒ Mutineer::Result
A survivor whose line ran at load becomes
ran_at_load(JobPlan.ran_at_load?); any other result comes back unchanged. -
.minitest_seed_hint ⇒ String
private
Names the configured seed, and accounts for helper overrides.
-
.narrow_copies!(extras, kept_jobs, kept_ignored) ⇒ void
private
Drops copy lists whose kept mutant
--sinceremoved (#374). -
.narrow_subjects_since!(extras, config, changed: nil) ⇒ void
private
Keeps
subjects/unmutated_subjectsfor methods whose def range intersects--sincechanged lines (#420). -
.public_unmutated(infos) ⇒ Array<Hash>
private
The reportable
{subject, file, line}rows for methods with no mutants. -
.ran_at_load?(source_file, mutation, subject, source, coverage_map) ⇒ Boolean
True when the mutant's line ran while the app booted or its class loaded, so a test can check a value the original code computed before the mutant was applied.
-
.result_keys(mutations, source, lines) ⇒ Array<Object>
One key per mutation; two mutations share a key exactly when they are on the same line and give the same mutated source (one edit), from one operator (#159) or two (#275).
-
.rspec_seed_hint ⇒ String
private
Names the seed a random RSpec order uses.
-
.scope_since(jobs, ignored_results, source_map, config, extras: nil) ⇒ Array(Array, Array<Mutineer::Result>, Integer), Array(Array, Array<Mutineer::Result>, nil)
Narrows the jobs and the suppressed (ignored) results to --since when it is set, as the dry run does, so a scoped report lists only mutants on changed lines.
-
.seed_hint_for(framework) ⇒ String
private
The not-green hint for this framework, or empty when it has no seed.
-
.selection_verdict(kind, result, reached: false) ⇒ Mutineer::Result
The verdict of a mutant whose tests JobPlan.coverage_selection chose as
:maybe: they ran its statement but may not have run the mutated code. -
.source_dirs(config) ⇒ Array<String>
The unique absolute directories holding the sources.
-
.suppress_map(source, file) ⇒ Hash{Integer => Hash}
Map each line number to
{ ops:, reason: }, using inline# mutineer:disable-line [ops]markers (RuboCop semantics: the marker sits on the same physical line as the code it silences). -
.suppressed?(operator, line, ids, disabled, ignore_set) ⇒ Boolean
True when this mutant is suppressed: its line bears a disable-line marker (bare, or scoped to its operator), OR its new or old-format id is in the config ignore list.
-
.suppression_reason(operator, line, ids, disabled, ignore_reasons) ⇒ String?
Why an ignored mutant was suppressed.
-
.sweep_orphans(dirs, glob = OrphanGuard::TEMP_BASENAME) ⇒ Array<String>
Removes stale mutant tempfiles from the given directories.
-
.test_load_roots(test_files) ⇒ Object
For each test file, the directory to add to $LOAD_PATH so its
require "test_helper"(or spec_helper) resolves: the nearest ancestor holding that helper, plus the file's own dir as a fallback. -
.unpaired_counts(config, operator_classes) ⇒ Array(Hash{String => Integer, nil}, Array<Hash>, Hash)
Counts scheduled mutants in each source pairing skipped.
-
.unpaired_path(subject_file, files, project_root) ⇒ String?
private
The unpaired path spelling that names the same file as
subject_file.
Class Method Details
.abort_if_unclean!(coverage_map, framework: nil) ⇒ void
This method returns an undefined value.
Aborts the run when coverage capture saw a red unmutated suite. Scoring those results would treat existing assertion failures as killed mutants.
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'lib/mutineer/job_plan.rb', line 222 def self.abort_if_unclean!(coverage_map, framework: nil) if coverage_map.map.empty? && coverage_map.failed_test_files.any? raise SmokeCheckError, "no test recorded coverage, and capture failed for #{coverage_map.failed_test_files.join(', ')}" end files = coverage_map.failed_clean_tests return if files.empty? # A clean check that hit its deadline is not a red suite: no test failed, # so the seed hint does not apply. timeouts = (coverage_map.clean_timeouts || {}).slice(*files) files -= timeouts.keys raise SmokeCheckError, (timeouts) if files.empty? seed_hint = seed_hint_for(framework) # The hint opens with "the unmutated suite is not green", so the files # follow it rather than repeat that sentence (#360). Failure names and # the first error follow when capture stored them. A check that timed # out next to a red file is named too, so one run reports both. also = timeouts.empty? ? "" : " Also, #{(timeouts)}" detail = clean_failure_detail(coverage_map, files) raise SmokeCheckError, "#{ExternalBackend.generic_env_hint}. Failed: #{files.join(', ')}.#{seed_hint}#{also}#{detail}" end |
.apply_unpaired_since!(counts, jobs, ignored, source_map, files, config) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Replaces pending unpaired counts with the jobs --since keeps.
One scope_since call covers every file that produced a job.
677 678 679 680 681 682 683 684 685 686 687 688 689 |
# File 'lib/mutineer/job_plan.rb', line 677 def self.apply_unpaired_since!(counts, jobs, ignored, source_map, files, config) return if files.empty? copy = config.dup copy.sources = files kept, = scope_since(jobs, ignored, source_map, copy) tally = Hash.new(0) kept.each do |subject,| key = unpaired_path(subject.file, files, config.project_root) tally[key] += 1 if key end files.each { |file| counts[file] = tally[file] } end |
.clean_failure_detail(coverage_map, files) ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Joins capped failure reports for the unclean files (#360).
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
# File 'lib/mutineer/job_plan.rb', line 270 def self.clean_failure_detail(coverage_map, files) details = coverage_map.failed_clean_details || {} parts = files.filter_map do |file| text = details[file].to_s.strip next if text.empty? "#{file}:\n#{text}" end return "" if parts.empty? text = parts.join("\n") limit = CoverageMap::CLEAN_FAILURE_DETAIL_LIMIT return "\n#{text}" if text.length <= limit "\n#{text[0, limit].rstrip}\n…" end |
.clean_timeout_message(timeouts) ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Says which clean checks hit their deadline and how to raise it. It names the longest deadline that passed: the combined check's deadline can be above --capture-timeout, so any lower value would change nothing.
254 255 256 257 258 259 260 261 262 |
# File 'lib/mutineer/job_plan.rb', line 254 def self.(timeouts) checks = timeouts.map do |rel, seconds| what = rel == "combined suite" ? "the combined clean check (the clean-check test files in one process)" : rel "#{what} timed out after #{seconds}s" end "the unmutated suite did not finish: #{checks.join('; ')}. " \ "Mutineer stopped it, so it reports no failing test. " \ "Set --capture-timeout (capture_timeout in the config) above #{timeouts.values.max}." end |
.collect_jobs(config, operator_classes) ⇒ Array(Array, Array<Result>, Hash<String,String>, Hash{Symbol => Hash})
Collect every (subject, mutation, id) up front so a backend can run them. A mutant the user marked known-equivalent (inline disable-line comment or .mutineer.yml ignore id) is classified :ignored here and NEVER run. It is removed from the killed+survived denominator so a strong file reaches 100%. The id is computed per subject (occurrence needs the full list), keyed on the file path relative to config.project_root, and carried on every job so the parent can reattach it after the run. Shared by the in-process, external, and daemon backends so job selection can never drift.
Each mutant also gets its old-format id (MutantId.legacy_for), so an ignore
entry stored before ids carried the path still suppresses it. Prints nothing:
the extras hash returns, as data, legacy_ignore_matches (each old-format
ignore entry that matched a mutant through its old-format id => one
{id:, file:, subject:} hash per matched mutant, in collection order: its
new id, its project-relative file and its subject's qualified name;
recorded even when a new id is also listed, since the old entry still
over-matches other files), id_map (every reported mutant's new id =>
its old-format id), dropped_id_map (the same for each dropped repeat of
an edit: its id is still current for mutineer migrate), copies (each
kept mutant's id => the ids dropped as repeats of that edit, in drop
order, #374) and declined
(operator name => count of candidates that operator found and did not
mutate, Mutators::Base#declined; only counts above zero, keys sorted).
The name is the MutatorRegistry::ALL key, or the class's to_s for an
operator outside the registry. --only narrows declined, and --since
does not: a declined candidate has no mutation to place on a line.
The extras also hold subjects (how many methods were discovered, each
counted once across path spellings) and unmutated_subjects (#386): one
{subject:, file:, line:} hash per method the selected operators gave no
mutation, an empty method included, sorted by file, line and name. It is
decided before suppression and repeat removal, so a method whose mutants
are all ignored is not listed. --only narrows both; --since does not.
Mutations are collected in MutatorRegistry::ALL order, whatever the
order of operator_classes. Two operators can give the same mutated
source (#275), and the copy of the registry-first operator is the one
that runs, so the kept copy and the run order do not depend on the
--operators order.
Subjects sharing a qualified name in one file (two owner-less def index
in two DSL blocks) get a per-file ordinal in discovery order, so their ids
differ; the first one's ordinal is 0 and leaves its id unchanged.
76 77 78 79 80 81 82 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 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 160 161 162 163 164 165 166 167 168 169 170 171 172 |
# File 'lib/mutineer/job_plan.rb', line 76 def self.collect_jobs(config, operator_classes) # Registry order, so a repeat across operators keeps the registry-first # copy (#275). A class outside ALL goes last; ties keep the input order. rank = MutatorRegistry::ALL.values operator_classes = operator_classes.each_with_index .sort_by { |klass, i| [rank.index(klass) || rank.size, i] } .map(&:first) source_map = {} disabled_map = {} id_paths = {} # [file, qualified_name] => { declaration offset => ordinal }: keyed by the # declaration, so the same file discovered twice (two path spellings) reuses # its ordinal instead of minting a second id for the same mutant. name_decls = Hash.new { |h, k| h[k] = {} } ignore_set = config.ignore.to_set ignore_reasons = config.ignore_reasons || {} jobs = [] ignored_results = [] legacy_ignore_matches = {} id_map = {} dropped_id_map = {} # Kept id => dropped ids. Separate from dropped_id_map, which migrate # reads as dropped id => old-format id (#374). copies = {} declined = Hash.new(0) # [id_path, def offset] => nil, or the method's entry when it got no mutation. subjects = {} Project.discover(config.sources, only: config.only).each do |subject| source = (source_map[subject.file] ||= Parser.read(subject.file)) disabled = (disabled_map[subject.file] ||= suppress_map(source, subject.file)) # A repeated operator name runs once, so its declines count once. mutations = operator_classes.uniq.flat_map do |klass| operator = klass.new found = operator.mutations_for(subject, source) declined[MutatorRegistry::ALL.key(klass) || klass.to_s] += operator.declined found end id_path = (id_paths[subject.file] ||= ProjectPath.relative(subject.file, config.project_root)) decls = name_decls[[id_path, subject.qualified_name]] loc = subject.def_node.location ordinal = (decls[loc.start_offset] ||= decls.size) # The first path spelling of a def wins; later spellings are the same method. key = [id_path, loc.start_offset] unless subjects.key?(key) # end_line is for --since narrowing (#420); the public list keeps # only subject/file/line. subjects[key] = { subject: subject.qualified_name, file: subject.file, line: loc.start_line, end_line: loc.end_line, unmutated: mutations.empty? } end ids = MutantId.for_subject(subject, source, mutations, path: id_path, subject_ordinal: ordinal) legacy_ids = MutantId.legacy_for_subject(subject, source, mutations) lines = mutations.map { |m| source.byteslice(0, m.start_offset).count("\n") + 1 } keys = result_keys(mutations, source, lines) # A repeat of an earlier edit on the same line, from any operator, is # dropped (#159, #275), separately among the run and the ignored # mutants, so an ignored copy never hides a copy that should run. The # dropped id stays current for migrate, and `copies` names it on the # kept mutant so a report can show it (#374). seen = { run: {}, ignored: {} } mutations.each_with_index do |mutation, i| id = ids[i] legacy = legacy_ids[i] ignored = suppressed?(mutation.operator, lines[i], [id, legacy], disabled, ignore_set) # An old entry still over-matches other files even when the new id is # listed too, so every old-entry match is reported for migration, # including a dropped copy's. if ignore_set.include?(legacy) (legacy_ignore_matches[legacy] ||= []) << { id: id, file: id_path, subject: subject.qualified_name } end bucket = seen[ignored ? :ignored : :run] if (kept_id = bucket[keys[i]]) dropped_id_map[id] = legacy (copies[kept_id] ||= []) << id next end bucket[keys[i]] = id id_map[id] = legacy if ignored reason = suppression_reason(mutation.operator, lines[i], [id, legacy], disabled, ignore_reasons) ignored_results << Result.ignored.with(subject: subject, mutation: mutation, id: id, reason: reason) else jobs << [subject, mutation, id] end end end declined = declined.select { |_, count| count.positive? }.sort.to_h infos = subjects.values unmutated = public_unmutated(infos) [jobs, ignored_results, source_map, { legacy_ignore_matches: legacy_ignore_matches, id_map: id_map, dropped_id_map: dropped_id_map, copies: copies, declined: declined, subjects: infos.size, unmutated_subjects: unmutated, subject_ranges: infos }] end |
.coverage_selection(source_file, mutation, subject, source, coverage_map) ⇒ Array(Symbol, Object)
Coverage-based test selection, shared by the in-process (Runner.run) and daemon
paths so both narrow identically (score parity). Returns
[:run, abs_test_paths] when some test covers the mutant's line, in the
order of CoverageMap#order_tests (paired files, then cheapest), or
[:verdict, Result] (no_coverage / uncapturable) when none do. A line
Ruby does not count (a later line of a multi-line statement) uses the
tests that ran the statement that holds it (StatementLines). When those
lines give no tests, it retries with the loose lines of the statement:
code of the statement that runs only sometimes (the right side of a
multi-line a && b, #254), and a first or last line that holds other
code (the opener of a one-line block, #289), but never the def line.
Those tests may not have run the mutant, so the answer is
[:maybe, abs_test_paths]. selection_verdict keeps a survivor that
the probe saw run, and leaves one it did not see as no_coverage (#345).
An empty selection is :ran_at_load when the mutant's line ran while the
app booted or its class loaded (ran_at_load?): no test ran it, but the
load did, so it is not a coverage gap.
An empty selection is :uncapturable (not :no_coverage) when the
mutant's enclosing method body got coverage from no successful capture but
a sibling test failed to capture: the coverage was lost, not absent. Both are
excluded from the score denominator, so this distinction is reporting-only
and never changes the daemon-vs-in-process score.
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 |
# File 'lib/mutineer/job_plan.rb', line 394 def self.coverage_selection(source_file, mutation, subject, source, coverage_map) line = source.byteslice(0, mutation.start_offset).count("\n") + 1 chosen = coverage_map.tests_for(source_file, line) kind = :run if chosen.empty? && subject # A multi-line statement has a count on one of its lines only. lines = StatementLines.for(subject.def_node, source, mutation.start_offset) chosen = lines.flat_map { |l| coverage_map.tests_for(source_file, l) }.uniq if chosen.empty? lines = StatementLines.for(subject.def_node, source, mutation.start_offset, loose: true) chosen = lines.flat_map { |l| coverage_map.tests_for(source_file, l) }.uniq kind = :maybe end end if chosen.empty? # Method BODY range, not the whole def: the def/end lines are "covered" at # class-load even when the body never runs (body_loc is the statements' span). loc = subject&.body_loc range = loc ? (loc.start_line..loc.end_line) : (line..line) return [:verdict, Result.uncapturable] if coverage_map.method_uncapturable?(source_file, range) return [:verdict, Result.ran_at_load] if ran_at_load?(source_file, mutation, subject, source, coverage_map) return [:verdict, Result.no_coverage] end # The clean checks name each test by its real path (ProjectPath.absolute). # A random RSpec order hashes that name, so a mutant run uses the same # spelling, or a symlinked root (/var on macOS) reorders the examples (#282). [kind, coverage_map.order_tests(source_file, chosen).map { |t| ProjectPath.absolute(t, coverage_map.project_root) }] end |
.filter_since(jobs, source_map, config, changed: nil) ⇒ Object
--since: keep only jobs whose mutation lands on a line changed since the git ref. Composes with coverage selection (it only narrows the job list; each surviving mutant still goes through Runner.run's coverage check). A file with no changed lines (absent from the diff) contributes no jobs. Line is computed exactly as Runner.run does, from the already-read source in source_map.
790 791 792 793 794 795 796 797 798 799 |
# File 'lib/mutineer/job_plan.rb', line 790 def self.filter_since(jobs, source_map, config, changed: nil) changed ||= ChangedLines.for(ref: config.since, files: config.sources, project_root: config.project_root) jobs.select do |subject, mutation| source = source_map[subject.file] line = source.byteslice(0, mutation.start_offset).count("\n") + 1 abs = FsPath.(subject.file, config.project_root) changed.fetch(abs, []).include?(line) end end |
.hook_mutant(mutated, mutation, subject, source, reach_path: nil, reach_key: nil) ⇒ Array(String, Hash{Symbol => Object})
The reload mutant text for a def in a concern's included or prepended
block (#297): the mutated file with one statement added just before the
hook call, ::Mutineer::ConcernBlocks.store_hook_def do <mutated def> end.
The statement sits in the same body as the hook call, so the stored def has
the block's constant scope. The child passes the hook-def values to
ConcernBlocks.load_mutant, which places the def when the load reaches
that statement (#348). Shared by Runner.run and
DaemonBackend.job_result, so both build the same text. The hook call starts
before the def, so the mutation does not move its offset. A bad insert is
not checked here: the child's load raises SyntaxError before any test
runs, so the mutant scores error.
354 355 356 357 358 359 360 |
# File 'lib/mutineer/job_plan.rb', line 354 def self.hook_mutant(mutated, mutation, subject, source, reach_path: nil, reach_key: nil) at = subject.reload_hook_call.location.start_offset stored = "::Mutineer::ConcernBlocks.store_hook_def do\n" \ "#{Isolation.mutated_def(mutation, subject, source, reach_path: reach_path, reach_key: reach_key)}\nend; " [mutated.byteslice(0...at) + stored + mutated.byteslice(at..), { line: subject.def_node.location.start_line, name: subject.name, singleton: subject.singleton }] end |
.line_ops(entry) ⇒ Symbol, ...
The operator set for one suppress-map entry. A Hash is the current shape
(ops plus reason). :all and a Set remain valid for callers that
build the map by hand.
553 554 555 |
# File 'lib/mutineer/job_plan.rb', line 553 def self.line_ops(entry) entry.is_a?(Hash) ? entry[:ops] : entry end |
.line_reason(entry) ⇒ String?
The reason text on one suppress-map entry, when the entry stores one.
561 562 563 |
# File 'lib/mutineer/job_plan.rb', line 561 def self.line_reason(entry) entry.is_a?(Hash) ? entry[:reason] : nil end |
.load_verdict(result, source_file, mutation, subject, source, coverage_map) ⇒ Mutineer::Result
A survivor whose line ran at load becomes ran_at_load (ran_at_load?);
any other result comes back unchanged. A --matrix row is kept.
506 507 508 509 510 |
# File 'lib/mutineer/job_plan.rb', line 506 def self.load_verdict(result, source_file, mutation, subject, source, coverage_map) return result unless result.survived? && ran_at_load?(source_file, mutation, subject, source, coverage_map) result.with(status: :ran_at_load) end |
.minitest_seed_hint ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Names the configured seed, and accounts for helper overrides.
309 310 311 312 313 314 315 316 |
# File 'lib/mutineer/job_plan.rb', line 309 def self.minitest_seed_hint seed = MinitestIntegration.seed " Mutineer runs Minitest with SEED=#{seed}, unless a test helper changes SEED. " \ "An order-dependent test can fail here and pass in another order. " \ "Check the listed test files with the same seed and helpers " \ "(for \"combined suite\", all of them together). " \ "Change SEED, including helper settings, to choose another order." end |
.narrow_copies!(extras, kept_jobs, kept_ignored) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Drops copy lists whose kept mutant --since removed (#374). A dropped
copy shares that mutant's line, so it leaves with the mutant.
747 748 749 750 751 752 753 754 |
# File 'lib/mutineer/job_plan.rb', line 747 def self.narrow_copies!(extras, kept_jobs, kept_ignored) copies = extras[:copies] return unless copies keep = Set.new(kept_jobs.map(&:last)) kept_ignored.each { |result| keep.add(result.id) } extras[:copies] = copies.select { |id, _list| keep.include?(id) } end |
.narrow_subjects_since!(extras, config, changed: nil) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Keeps subjects / unmutated_subjects for methods whose def range
intersects --since changed lines (#420). Drops the internal
subject_ranges key afterward.
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 |
# File 'lib/mutineer/job_plan.rb', line 766 def self.narrow_subjects_since!(extras, config, changed: nil) ranges = extras.delete(:subject_ranges) || [] return if ranges.empty? files = ranges.map { |h| h[:file] }.uniq changed ||= ChangedLines.for(ref: config.since, files: files, project_root: config.project_root) in_scope = ranges.select do |h| lines = changed.fetch(FsPath.(h[:file], config.project_root), Set.new) next false if lines.empty? (h[:line]..h[:end_line]).any? { |ln| lines.include?(ln) } end extras[:subjects] = in_scope.size extras[:unmutated_subjects] = public_unmutated(in_scope) end |
.public_unmutated(infos) ⇒ Array<Hash>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The reportable {subject, file, line} rows for methods with no mutants.
179 180 181 182 183 |
# File 'lib/mutineer/job_plan.rb', line 179 def self.public_unmutated(infos) infos.select { |h| h[:unmutated] } .map { |h| { subject: h[:subject], file: h[:file], line: h[:line] } } .sort_by { |h| [h[:file], h[:line], h[:subject]] } end |
.ran_at_load?(source_file, mutation, subject, source, coverage_map) ⇒ Boolean
True when the mutant's line ran while the app booted or its class loaded, so a test can check a value the original code computed before the mutant was applied. Shared by coverage_selection, Runner.run and the daemon backend.
Only the lines of the statement that holds the mutant count
(StatementLines), and only inside the method body. So code that runs
only sometimes (x if c, a ternary branch) never counts: its line can
count at load without it. The def line never counts: Ruby counts it
when the method is defined.
A define_method or define_singleton_method call stores its block.
Reloading the method does not run the class that already called it, such
as Greeter calling greets, so a mutant in that call or in the stored
block is the original method when the call's line ran at load (#435).
The line of each on an empty array counts without the block, so a block
that is not one of those calls stays scored (#286). Re-running the
caller's class body is #389. CI is not read here. Rails eager load,
which the test env turns on when CI is set, is what puts the line in
the load set.
A one-line or endless def keeps its body on the def line, so it uses
the method's own call count at load instead (#209), for code that runs
each time the method does (StatementLines.runs_with_method?). A block
on that def line is unchanged (#389).
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 |
# File 'lib/mutineer/job_plan.rb', line 476 def self.ran_at_load?(source_file, mutation, subject, source, coverage_map) loc = subject&.body_loc return false unless loc && coverage_map def_loc = subject.def_node.location def_line = def_loc.start_line if loc.end_line == def_line return coverage_map.method_ran_at_load?(source_file, def_line, def_loc.start_column) && StatementLines.runs_with_method?(subject.def_node, mutation.start_offset) end body = (loc.start_line..loc.end_line) ran = lambda do |lines| lines.any? { |l| l != def_line && body.cover?(l) && coverage_map.ran_at_load?(source_file, l) } end return true if ran.call(StatementLines.for(subject.def_node, source, mutation.start_offset)) ran.call(StatementLines.stored_method_lines(subject.def_node, source, mutation.start_offset)) end |
.result_keys(mutations, source, lines) ⇒ Array<Object>
One key per mutation; two mutations share a key exactly when they are on the same line and give the same mutated source (one edit), from one operator (#159) or two (#275). The caller drops a repeat after ids are assigned. Only a group of same-line mutations can repeat, so only those build a key from their text: the span from the group's earliest start to its latest end, digested. Every other mutation gets a key of its own.
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/mutineer/job_plan.rb', line 196 def self.result_keys(mutations, source, lines) keys = Array.new(mutations.size) { |i| i } mutations.each_index.group_by { |i| lines[i] }.each_value do |group| next if group.size < 2 from = group.map { |i| mutations[i].start_offset }.min to = group.map { |i| mutations[i].end_offset }.max group.each do |i| m = mutations[i] span = "#{source.byteslice(from...m.start_offset)}#{m.replacement}#{source.byteslice(m.end_offset...to)}" keys[i] = [lines[i], Digest::SHA256.digest(span)] end end keys end |
.rspec_seed_hint ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Names the seed a random RSpec order uses. A defined order is unchanged.
322 323 324 325 326 327 328 329 330 331 |
# File 'lib/mutineer/job_plan.rb', line 322 def self.rspec_seed_hint seed = TestRunners::RSpecSeed.advertised_seed " Mutineer runs a random RSpec order with seed #{seed}, unless you set a seed " \ "(--seed, --order rand:N, SPEC_OPTS, .rspec, or config.seed). " \ "RSpec reads SPEC_OPTS after the command line, so a seed there replaces " \ "--seed on the rspec command. " \ "A defined order is left as it is. " \ "An order-dependent example can fail here and pass in another order. " \ "Check the listed spec files with the same seed." end |
.scope_since(jobs, ignored_results, source_map, config, extras: nil) ⇒ Array(Array, Array<Mutineer::Result>, Integer), Array(Array, Array<Mutineer::Result>, nil)
Narrows the jobs and the suppressed (ignored) results to --since when it
is set, as the dry run does, so a scoped report lists only mutants on
changed lines. Also returns how many mutants there were before narrowing
(nil without --since), so the CLI can tell "the changes held nothing to
test" from "nothing was mutable at all". When extras is given, also
narrows subjects / unmutated_subjects to methods whose def range
intersects the diff (#420), and drops copies whose kept mutant is out
of scope (#374).
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 |
# File 'lib/mutineer/job_plan.rb', line 719 def self.scope_since(jobs, ignored_results, source_map, config, extras: nil) unless config.since extras&.delete(:subject_ranges) return [jobs, ignored_results, nil] end # One pass, so git computes the changed lines once for jobs and subjects. ignored_entries = ignored_results.map { |r| [r.subject, r.mutation, r] } range_files = extras&.fetch(:subject_ranges, [])&.map { |h| h[:file] } || [] files = (config.sources + range_files).uniq changed = ChangedLines.for(ref: config.since, files: files, project_root: config.project_root) kept = filter_since(jobs + ignored_entries, source_map, config, changed: changed) kept_ignored, kept_jobs = kept.partition { |entry| entry.last.is_a?(Result) } if extras narrow_subjects_since!(extras, config, changed: changed) narrow_copies!(extras, kept_jobs, kept_ignored.map(&:last)) end [kept_jobs, kept_ignored.map(&:last), jobs.size + ignored_results.size] end |
.seed_hint_for(framework) ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The not-green hint for this framework, or empty when it has no seed.
292 293 294 295 296 297 298 299 300 301 302 303 |
# File 'lib/mutineer/job_plan.rb', line 292 def self.seed_hint_for(framework) # `==`, not `case`: `when` uses Module#===, and a module is not an # instance of itself. runner = TestRunners.for(framework) if runner == TestRunners::Minitest minitest_seed_hint elsif runner == TestRunners::RSpec rspec_seed_hint else "" end end |
.selection_verdict(kind, result, reached: false) ⇒ Mutineer::Result
The verdict of a mutant whose tests coverage_selection chose as :maybe:
they ran its statement but may not have run the mutated code. A kill is a
real kill. A survivor the probe saw run is a real survivor and keeps its
--matrix row (#345). A survivor the probe did not see is no_coverage,
the same as any other unreached mutant, and has no --matrix row (#254).
An error or a timeout stays what it is: the mutant ran, and a failure is
reported, not hidden. A kill keeps its whole --matrix row. A result of
any other selection comes back unchanged.
439 440 441 442 443 |
# File 'lib/mutineer/job_plan.rb', line 439 def self.selection_verdict(kind, result, reached: false) return result unless kind == :maybe && result.survived? && !reached result.with(status: :no_coverage, kills: nil) end |
.source_dirs(config) ⇒ Array<String>
The unique absolute directories holding the sources. Sweep target for both orphan mechanisms (in-process mutant tempfiles and external backup files), and shipped to the daemon via DaemonBackend.boot_config so it can sweep too. Shared so the path-expansion rule cannot drift between the paths.
829 830 831 |
# File 'lib/mutineer/job_plan.rb', line 829 def self.source_dirs(config) config.sources.map { |f| File.dirname(File.(f, config.project_root)) }.uniq end |
.suppress_map(source, file) ⇒ Hash{Integer => Hash}
Map each line number to { ops:, reason: }, using inline
# mutineer:disable-line [ops] markers (RuboCop semantics: the marker
sits on the same physical line as the code it silences). ops is :all
or a set of operator symbols. reason is the text after --, or nil.
A bare marker disables every operator on that line; disable-line a, b
only the listed operators. Block-form disable/enable ranges are
intentionally not supported. Only a real # comment counts: Prism lists
the comments, so the marker text inside a string, heredoc or regex
silences nothing (#158).
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
# File 'lib/mutineer/job_plan.rb', line 525 def self.suppress_map(source, file) map = {} Parser.comments(source).grep(Prism::InlineComment).each do |comment| line = comment.location.start_line next unless (m = comment.slice.match(/#\s*mutineer:disable-line(?:\s+([\w,\s]+))?/)) ops = m[1]&.split(",")&.map(&:strip)&.reject(&:empty?) # Only spaces or commas after the marker (e.g. `disable-line -- why`) # is a bare marker, not an empty list that silences nothing. ops = nil if ops&.empty? unknown = ops.to_a.reject { |o| MutatorRegistry::ALL.key?(o) } unknown.each do |o| warn "mutineer: unknown operator #{o.inspect} in #{file}:#{line}#{Mutineer.did_you_mean(o, MutatorRegistry::ALL.keys)} " \ "(known: #{MutatorRegistry::ALL.keys.join(', ')}); write a reason after --" end reason = comment.slice[/\s--\s*(.*)\z/, 1]&.strip reason = nil if reason.nil? || reason.empty? map[line] = { ops: ops ? ops.map(&:to_sym).to_set : :all, reason: reason } end map end |
.suppressed?(operator, line, ids, disabled, ignore_set) ⇒ Boolean
True when this mutant is suppressed: its line bears a disable-line marker (bare, or scoped to its operator), OR its new or old-format id is in the config ignore list. Checked at job-build time so a suppressed mutant is never forked.
572 573 574 575 576 577 578 579 580 |
# File 'lib/mutineer/job_plan.rb', line 572 def self.suppressed?(operator, line, ids, disabled, ignore_set) return true if Array(ids).any? { |id| ignore_set.include?(id) } case line_ops(disabled[line]) when :all then true when Set then line_ops(disabled[line]).include?(operator) else false end end |
.suppression_reason(operator, line, ids, disabled, ignore_reasons) ⇒ String?
Why an ignored mutant was suppressed. An inline reason wins. Otherwise the reason is the first matching ignore id that has one. Blank text is nil.
591 592 593 594 595 596 597 598 599 600 601 602 603 |
# File 'lib/mutineer/job_plan.rb', line 591 def self.suppression_reason(operator, line, ids, disabled, ignore_reasons) entry = disabled[line] ops = line_ops(entry) line_hit = ops == :all || (ops.is_a?(Set) && ops.include?(operator)) inline = line_hit ? line_reason(entry) : nil return inline if inline.is_a?(String) && !inline.strip.empty? Array(ids).each do |candidate| text = ignore_reasons[candidate] return text if text.is_a?(String) && !text.strip.empty? end nil end |
.sweep_orphans(dirs, glob = OrphanGuard::TEMP_BASENAME) ⇒ Array<String>
Removes stale mutant tempfiles from the given directories. The default glob matches the files of both modes, so the in-process boot sweep also removes an old daemon file (#287). DaemonBackend passes its daemon-only glob when it sweeps tool-side at the end of every daemon run, empty or not. A file another process still owns is left in place: both modes record the creating pid in the name and lock the file while it loads (#295).
843 844 845 846 847 848 849 850 851 852 |
# File 'lib/mutineer/job_plan.rb', line 843 def self.sweep_orphans(dirs, glob = OrphanGuard::TEMP_BASENAME) dirs.flat_map do |dir| Dir.glob(File.join(dir, glob)).select do |path| next true if OrphanGuard.mutant_file_in_use?(path) File.unlink(path) rescue nil # rubocop:disable Style/RescueModifier false end end end |
.test_load_roots(test_files) ⇒ Object
For each test file, the directory to add to $LOAD_PATH so its
require "test_helper" (or spec_helper) resolves: the nearest ancestor
holding that helper, plus the file's own dir as a fallback.
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 |
# File 'lib/mutineer/job_plan.rb', line 804 def self.test_load_roots(test_files) test_files.flat_map do |f| dir = File.dirname(f) root = nil loop do if File.exist?(File.join(dir, "test_helper.rb")) || File.exist?(File.join(dir, "spec_helper.rb")) root = dir break end parent = File.dirname(dir) break if parent == dir dir = parent end [root, File.dirname(f)].compact end.uniq end |
.unpaired_counts(config, operator_classes) ⇒ Array(Hash{String => Integer, nil}, Array<Hash>, Hash)
Counts scheduled mutants in each source pairing skipped.
One source is parsed at a time. A source that raises records nil and
an error string. This method prints nothing. The caller prints the error.
An empty job list counts 0. --only and --since narrow the count.
They do not drop the source. Ignored mutants are not in the count.
The count is not a validity check.
The third element holds the id maps from those sources, taken before
--since narrows the count. A real run drops unpaired sources before
collect_jobs, so the unmatched-ignore check merges these maps back in
and agrees with a dry run of the same files (#377). A source that could
not be read contributes no ids.
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 |
# File 'lib/mutineer/job_plan.rb', line 623 def self.unpaired_counts(config, operator_classes) counts = {} failures = [] pending_jobs = [] pending_ignored = [] pending_map = {} pending_files = [] id_map = {} dropped_id_map = {} legacy_ignore_matches = {} config.unpaired_sources.each do |file| copy = config.dup copy.sources = [file] begin jobs, ignored, source_map, file_extras = collect_jobs(copy, operator_classes) rescue StandardError => e counts[file] = nil failures << { file: file, error: "#{e.class}: #{e.}" } next end id_map.merge!(file_extras[:id_map]) dropped_id_map.merge!(file_extras[:dropped_id_map]) file_extras[:legacy_ignore_matches].each do |old, hits| (legacy_ignore_matches[old] ||= []).concat(hits) end if jobs.empty? || !config.since counts[file] = jobs.size else pending_jobs.concat(jobs) pending_ignored.concat(ignored) pending_map.merge!(source_map) pending_files << file counts[file] = 0 end end apply_unpaired_since!(counts, pending_jobs, pending_ignored, pending_map, pending_files, config) if config.since [counts, failures, { id_map: id_map, dropped_id_map: dropped_id_map, legacy_ignore_matches: legacy_ignore_matches }] end |
.unpaired_path(subject_file, files, project_root) ⇒ String?
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The unpaired path spelling that names the same file as subject_file.
698 699 700 701 |
# File 'lib/mutineer/job_plan.rb', line 698 def self.unpaired_path(subject_file, files, project_root) absolute = File.(subject_file, project_root) files.find { |file| File.(file, project_root) == absolute } end |