mutineer 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +680 -0
  3. data/README.md +210 -499
  4. data/lib/mutineer/baseline.rb +1 -1
  5. data/lib/mutineer/changed_lines.rb +2 -1
  6. data/lib/mutineer/child_coverage.rb +53 -0
  7. data/lib/mutineer/cli.rb +293 -42
  8. data/lib/mutineer/concern_blocks.rb +243 -0
  9. data/lib/mutineer/config.rb +154 -8
  10. data/lib/mutineer/coverage_map.rb +265 -27
  11. data/lib/mutineer/daemon_backend.rb +244 -75
  12. data/lib/mutineer/daemon_client.rb +73 -10
  13. data/lib/mutineer/daemon_server.rb +226 -42
  14. data/lib/mutineer/external_backend.rb +159 -15
  15. data/lib/mutineer/init.rb +124 -0
  16. data/lib/mutineer/isolation.rb +78 -24
  17. data/lib/mutineer/job_plan.rb +234 -44
  18. data/lib/mutineer/kill_channel.rb +24 -14
  19. data/lib/mutineer/migrate.rb +707 -0
  20. data/lib/mutineer/minitest_integration/in_test_database_error.rb +184 -0
  21. data/lib/mutineer/minitest_integration/kill_recorder.rb +25 -17
  22. data/lib/mutineer/minitest_integration.rb +44 -14
  23. data/lib/mutineer/mutator_registry.rb +6 -2
  24. data/lib/mutineer/mutators/array_literal.rb +4 -2
  25. data/lib/mutineer/mutators/base.rb +36 -7
  26. data/lib/mutineer/mutators/call_to_receiver.rb +148 -0
  27. data/lib/mutineer/mutators/chain_link.rb +6 -6
  28. data/lib/mutineer/mutators/condition_forcing.rb +6 -3
  29. data/lib/mutineer/mutators/operand_removal.rb +4 -2
  30. data/lib/mutineer/mutators/range_literal.rb +105 -4
  31. data/lib/mutineer/mutators/return_nil.rb +1 -0
  32. data/lib/mutineer/orphan_guard.rb +84 -0
  33. data/lib/mutineer/pairing.rb +62 -1
  34. data/lib/mutineer/project.rb +302 -14
  35. data/lib/mutineer/rails_run_env.rb +73 -0
  36. data/lib/mutineer/rails_worker_db.rb +1596 -57
  37. data/lib/mutineer/redaction.rb +199 -0
  38. data/lib/mutineer/reporter.rb +173 -31
  39. data/lib/mutineer/result.rb +52 -15
  40. data/lib/mutineer/runner.rb +148 -28
  41. data/lib/mutineer/statement_lines.rb +24 -11
  42. data/lib/mutineer/subject.rb +30 -4
  43. data/lib/mutineer/test_runners/minitest.rb +2 -1
  44. data/lib/mutineer/test_runners/rspec.rb +15 -3
  45. data/lib/mutineer/test_runners.rb +5 -2
  46. data/lib/mutineer/triage.rb +111 -0
  47. data/lib/mutineer/version.rb +1 -1
  48. data/lib/mutineer/worker_pool.rb +2 -1
  49. data/lib/mutineer.rb +4 -0
  50. data/skills/mutineer/SKILL.md +84 -0
  51. metadata +13 -1
@@ -0,0 +1,148 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base"
4
+
5
+ module Mutineer
6
+ module Mutators
7
+ # Call-to-receiver mutator (Tier-2).
8
+ #
9
+ # Replaces the last call of a chain with its receiver, with the arguments
10
+ # and the block of that call: `user.full_name` becomes `user`, and
11
+ # `ids.uniq.sort` becomes `ids.uniq`. A chain begins at a receiver that is
12
+ # not a dotted call, as in {ChainLink}. A call in an argument or a block
13
+ # starts a chain of its own.
14
+ #
15
+ # The mutant survives when no test checks what the last call does: a strip,
16
+ # a uniq, a compact or a lookup the tests never see.
17
+ #
18
+ # The operator does not overlap with {ChainLink}. `chain_link` drops a link
19
+ # in the middle of a chain, and this operator drops the last call. A call
20
+ # that is the receiver of a dotted call, or of a call write or a call
21
+ # target, is a link, so it gets no mutant here. The two operators give the
22
+ # same source only when the last call repeats the link before it, as in
23
+ # `node.name.name`. When both edits start on the same line, the job plan
24
+ # runs one copy, the `chain_link` one (#275).
25
+ #
26
+ # Calls in {SKIPPED} are never replaced; each one counts as declined. The
27
+ # list is shorter than {ChainLink::SKIPPED}: on the last call, a conversion
28
+ # such as `to_s` or `to_i` decides the type of the value that the
29
+ # expression returns, so `m[1].to_i` becomes `m[1]`. `Foo.new` becomes the
30
+ # class, and almost any use of the class raises.
31
+ #
32
+ # A call is not replaced when its name is an operator (`a.+(1)`), or a
33
+ # setter (`a.b = 1`). A call with no dot (`a + b`, `a[0]`) is not replaced.
34
+ class CallToReceiver < Base
35
+ # Matches the name of a call written as a word, not as an operator.
36
+ WORD_NAME = /\A[[:alpha:]_]/
37
+
38
+ # Method names whose last call is never replaced. A name is here when
39
+ # its mutant is most often equivalent, or when almost any test that runs
40
+ # the line kills it. `freeze` and `itself` return the receiver. `dup`
41
+ # and `clone` return a copy, so the mutant shows when code later changes
42
+ # the copy or the original, or compares the result with the original by
43
+ # identity. Dropping `to_set` most often leaves an Array, which answers
44
+ # `include?` and `empty?` as a Set does (it keeps duplicates, so `size`
45
+ # and `each` can differ). `new` leaves the class in place of an
46
+ # instance, which almost any test that runs the line kills.
47
+ SKIPPED = %i[new dup clone freeze itself to_set].freeze
48
+
49
+ # Resets the per-subject record of calls that are links.
50
+ #
51
+ # @param subject [Mutineer::Subject] subject whose body is visited.
52
+ # @param source [String] full source text for byte-based slicing.
53
+ # @return [Array<Mutineer::Mutation>] collected mutations.
54
+ def mutations_for(subject, source)
55
+ @links = {}.compare_by_identity
56
+ super
57
+ end
58
+
59
+ # Visits a call. A dotted call that is not a link is the last call of its
60
+ # chain.
61
+ #
62
+ # @param node [Prism::CallNode] call node to inspect.
63
+ # @return [void]
64
+ def visit_call_node(node)
65
+ mark(node)
66
+ replace(node) if dotted?(node) && !@links.key?(node)
67
+ super
68
+ end
69
+
70
+ # Visits `a.b.c += 1`. Its receiver is a link.
71
+ #
72
+ # @param node [Prism::CallOperatorWriteNode] node to inspect.
73
+ # @return [void]
74
+ def visit_call_operator_write_node(node)
75
+ mark(node)
76
+ super
77
+ end
78
+
79
+ # Visits `a.b.c ||= 1`. Its receiver is a link.
80
+ #
81
+ # @param node [Prism::CallOrWriteNode] node to inspect.
82
+ # @return [void]
83
+ def visit_call_or_write_node(node)
84
+ mark(node)
85
+ super
86
+ end
87
+
88
+ # Visits `a.b.c &&= 1`. Its receiver is a link.
89
+ #
90
+ # @param node [Prism::CallAndWriteNode] node to inspect.
91
+ # @return [void]
92
+ def visit_call_and_write_node(node)
93
+ mark(node)
94
+ super
95
+ end
96
+
97
+ # Visits a call used as an assignment target, as in `a.b.c, d = 1, 2`.
98
+ # Its receiver is a link.
99
+ #
100
+ # @param node [Prism::CallTargetNode] node to inspect.
101
+ # @return [void]
102
+ def visit_call_target_node(node)
103
+ mark(node)
104
+ super
105
+ end
106
+
107
+ private
108
+
109
+ # Records the receiver of a node as a link when the node is a dotted call
110
+ # or a call write or target. The receiver of a call with no dot is not a
111
+ # link. It is the last call of a chain of its own.
112
+ #
113
+ # @param node [Prism::Node] node that responds to `receiver`.
114
+ # @return [void]
115
+ def mark(node)
116
+ @links[node.receiver] = true if dotted?(node) || !node.is_a?(Prism::CallNode)
117
+ end
118
+
119
+ # Emits the replacement of a call by its receiver, unless the name is an
120
+ # operator, a setter, or in {SKIPPED}.
121
+ #
122
+ # @param node [Prism::CallNode] the dotted call to replace.
123
+ # @return [void]
124
+ def replace(node)
125
+ name = node.name.to_s
126
+ return unless name.match?(WORD_NAME)
127
+ return if name.end_with?("=")
128
+ return decline if SKIPPED.include?(node.name)
129
+
130
+ receiver = node.receiver.location
131
+ @mutations << Mutation.new(
132
+ start_offset: node.location.start_offset,
133
+ end_offset: node.location.end_offset,
134
+ replacement: @source.byteslice(receiver.start_offset, receiver.end_offset - receiver.start_offset),
135
+ operator: :call_to_receiver
136
+ )
137
+ end
138
+
139
+ # Returns whether a node is a call through `.`, `&.` or `::`.
140
+ #
141
+ # @param node [Prism::Node, nil] node to inspect.
142
+ # @return [Boolean] true for a call node with a call operator.
143
+ def dotted?(node)
144
+ node.is_a?(Prism::CallNode) && !node.call_operator_loc.nil?
145
+ end
146
+ end
147
+ end
148
+ end
@@ -16,16 +16,16 @@ module Mutineer
16
16
  # The mutant survives when no test tells the chain apart from the same chain
17
17
  # without that step: a scope, a filter or a lookup the tests never see.
18
18
  #
19
- # Links in {SKIPPED} are never dropped. On a value that already has the
20
- # target type or needs no copy, a conversion (`name.to_s.strip`) or a copy
21
- # (`list.dup.sort`) is a no-op, so dropping it most often makes an
22
- # equivalent mutant. Dropping `new` sends the next call to the class, which
19
+ # Links in {SKIPPED} are never dropped; each one counts as declined. On a
20
+ # value that already has the target type or needs no copy, a conversion
21
+ # (`name.to_s.strip`) or a copy (`list.dup.sort`) is a no-op, so dropping
22
+ # it most often makes an equivalent mutant. Dropping `new` sends the next call to the class, which
23
23
  # raises (killed by any test that runs the line) or reaches a class method
24
24
  # that builds the instance itself (equivalent); neither says anything about
25
25
  # the tests.
26
26
  class ChainLink < Base
27
27
  # Method names whose link is never dropped: core conversions and copies,
28
- # plus `new`.
28
+ # plus `new`. {CallToReceiver} has its own shorter list for the last call.
29
29
  SKIPPED = %i[
30
30
  to_s to_str to_sym to_i to_int to_f to_r to_c to_a to_ary to_h to_hash to_proc to_set
31
31
  dup clone freeze itself
@@ -100,7 +100,7 @@ module Mutineer
100
100
  link = top.receiver
101
101
  while dotted?(link)
102
102
  @links[link] = true
103
- drop(link) unless SKIPPED.include?(link.name)
103
+ SKIPPED.include?(link.name) ? decline : drop(link)
104
104
  link = link.receiver
105
105
  end
106
106
  end
@@ -22,7 +22,8 @@ module Mutineer
22
22
  # as the `nil` that `statement_removal` or `return_nil` puts in place of the
23
23
  # whole conditional. It is still made: dropping it would make the mutants
24
24
  # of one operator depend on which other operators run, and on what the user
25
- # suppressed for them. The two then get the same verdict.
25
+ # suppressed for them. The two then get the same verdict. Their text
26
+ # differs, so the job plan's drop of a repeated edit (#275) keeps both.
26
27
  #
27
28
  # `condition_negation` wraps the condition in `!( ... )`, which neither
28
29
  # forced value is.
@@ -53,13 +54,15 @@ module Mutineer
53
54
  private
54
55
 
55
56
  # Emits the forced condition unless the condition is a literal or holds a
56
- # heredoc, whose body would stay behind as code.
57
+ # heredoc, whose body would stay behind as code. The heredoc skip counts
58
+ # as declined; the literal skip does not.
57
59
  #
58
60
  # @param node [Prism::IfNode, Prism::UnlessNode] the conditional.
59
61
  # @return [void]
60
62
  def force(node)
61
63
  predicate = node.predicate
62
- return if LITERALS.include?(unwrap(predicate).class) || heredoc?(predicate)
64
+ return if LITERALS.include?(unwrap(predicate).class)
65
+ return decline if heredoc?(predicate)
63
66
 
64
67
  loc = predicate.location
65
68
  @mutations << Mutation.new(
@@ -37,13 +37,15 @@ module Mutineer
37
37
 
38
38
  # Emits one mutation that keeps the left operand, then one that keeps
39
39
  # the right operand. The order is fixed, because the two mutants share
40
- # a token and their occurrence ordinals tell them apart.
40
+ # a token and their occurrence ordinals tell them apart. A removed
41
+ # operand that holds a heredoc counts as declined; a kept jump does not.
41
42
  #
42
43
  # @param node [Prism::AndNode, Prism::OrNode] connector node.
43
44
  # @return [void]
44
45
  def emit(node)
45
46
  [[node.left, node.right], [node.right, node.left]].each do |kept, removed|
46
- next if JUMPS.any? { |type| kept.is_a?(type) } || heredoc?(removed)
47
+ next if JUMPS.any? { |type| kept.is_a?(type) }
48
+ next decline if heredoc?(removed)
47
49
 
48
50
  @mutations << Mutation.new(
49
51
  start_offset: node.location.start_offset,
@@ -10,24 +10,125 @@ module Mutineer
10
10
  # `..` -> `...` mutant survives when no test checks the last element.
11
11
  # Flip-flops are FlipFlopNode, not RangeNode, so this mutator skips them.
12
12
  #
13
- # Endless ranges (`1..`, `1..nil`) are skipped. `(1..)` and `(1...)` give
14
- # the same result for slicing, `include?`, `===`, `size` and patterns, so
15
- # the mutant is equivalent and no normal test can kill it.
13
+ # An endless range (`1..`, `1..nil`) is skipped only when it is a direct
14
+ # index argument of a call in {SLICE_CALLS} or of an index write
15
+ # (`a[1..] += x`). There `(1..)` and `(1...)` select the same elements, so
16
+ # the mutant is equivalent, and each skipped range counts as declined.
17
+ # Every other endless range is swapped, because the two ranges differ on
18
+ # `==`, `hash`, `exclude_end?` and `to_s`, so a test can kill it. This
19
+ # includes the value of `h[:k] = 1..` and a call on a class, such as
20
+ # `Array[1..]`, which builds a value and does not slice.
16
21
  class RangeLiteral < Base
17
22
  # Maps each range operator to its opposite.
18
23
  SWAPS = { ".." => "...", "..." => ".." }.freeze
19
24
 
25
+ # Calls whose direct endless-range index arguments are not mutated. They
26
+ # select the same elements for `(1..)` and `(1...)`. The check uses the
27
+ # name, and a class receiver is not skipped. The assigned value of `[]=`
28
+ # is not an index, so it is mutated.
29
+ SLICE_CALLS = %i[[] []= slice slice! byteslice bytesplice values_at].freeze
30
+
31
+ # Resets the per-subject record of endless ranges that are slice arguments.
32
+ #
33
+ # @param subject [Mutineer::Subject] subject whose body is visited.
34
+ # @param source [String] full source text for byte-based slicing.
35
+ # @return [Array<Mutineer::Mutation>] collected mutations.
36
+ def mutations_for(subject, source)
37
+ @slice_args = {}.compare_by_identity
38
+ super
39
+ end
40
+
41
+ # Visits a call. Records the range arguments of a call in {SLICE_CALLS},
42
+ # unless the receiver is a class.
43
+ #
44
+ # @param node [Prism::CallNode] call node to inspect.
45
+ # @return [void]
46
+ def visit_call_node(node)
47
+ record_slice_args(node) if SLICE_CALLS.include?(node.name)
48
+ super
49
+ end
50
+
51
+ # Visits `a[1..] += x`. Its index arguments are slice arguments.
52
+ #
53
+ # @param node [Prism::IndexOperatorWriteNode] node to inspect.
54
+ # @return [void]
55
+ def visit_index_operator_write_node(node)
56
+ record_slice_args(node)
57
+ super
58
+ end
59
+
60
+ # Visits `a[1..] ||= x`. Its index arguments are slice arguments.
61
+ #
62
+ # @param node [Prism::IndexOrWriteNode] node to inspect.
63
+ # @return [void]
64
+ def visit_index_or_write_node(node)
65
+ record_slice_args(node)
66
+ super
67
+ end
68
+
69
+ # Visits `a[1..] &&= x`. Its index arguments are slice arguments.
70
+ #
71
+ # @param node [Prism::IndexAndWriteNode] node to inspect.
72
+ # @return [void]
73
+ def visit_index_and_write_node(node)
74
+ record_slice_args(node)
75
+ super
76
+ end
77
+
78
+ # Visits an index used as an assignment target, as in `a[1..], b = x, y`.
79
+ # Its index arguments are slice arguments.
80
+ #
81
+ # @param node [Prism::IndexTargetNode] node to inspect.
82
+ # @return [void]
83
+ def visit_index_target_node(node)
84
+ record_slice_args(node)
85
+ super
86
+ end
87
+
20
88
  # Visits range nodes and emits range mutations.
21
89
  #
22
90
  # @param node [Prism::RangeNode] range node to inspect.
23
91
  # @return [void]
24
92
  def visit_range_node(node)
25
- emit(node) unless endless?(node)
93
+ if endless?(node) && @slice_args.key?(node)
94
+ decline
95
+ else
96
+ emit(node)
97
+ end
26
98
  super # nested ranges ((1..2)...(3..4)) each get their own mutation
27
99
  end
28
100
 
29
101
  private
30
102
 
103
+ # Records each range that is a direct argument of the node. For a `[]=`
104
+ # call the last argument is the assigned value, not an index, so it is
105
+ # left out. Nothing is recorded when the receiver is a class, as in
106
+ # `Array[1..]` or `Registry[1..] ||= x`.
107
+ #
108
+ # @param node [Prism::Node] call or index node that responds to `arguments`.
109
+ # @return [void]
110
+ def record_slice_args(node)
111
+ return if class_receiver?(node)
112
+
113
+ args = node.arguments&.arguments || []
114
+ args = args[0...-1] if node.is_a?(Prism::CallNode) && node.name == :[]=
115
+ args.each { |arg| @slice_args[arg] = true if arg.is_a?(Prism::RangeNode) }
116
+ end
117
+
118
+ # Whether the receiver of a call or index write names a class or module, as in
119
+ # `Array[1..]` or `Foo::Bar[1..]`. Such a call builds a value, so it is not
120
+ # a slice. A constant in capitals only, as in `ARGV[1..]`, holds a value
121
+ # that is sliced, so it does not count.
122
+ #
123
+ # @param node [Prism::Node] call or index node that responds to `receiver`.
124
+ # @return [Boolean]
125
+ def class_receiver?(node)
126
+ receiver = node.receiver
127
+ return false unless receiver.is_a?(Prism::ConstantReadNode) || receiver.is_a?(Prism::ConstantPathNode)
128
+
129
+ receiver.name.to_s.match?(/[a-z]/)
130
+ end
131
+
31
132
  # Whether the range has no end: `1..` or `1..nil`.
32
133
  #
33
134
  # @param node [Prism::RangeNode] range node to inspect.
@@ -16,6 +16,7 @@ module Mutineer
16
16
  def mutations_for(subject, source)
17
17
  @source = source
18
18
  @mutations = []
19
+ @declined = 0
19
20
  @body = subject.def_node.body
20
21
  if @body
21
22
  @body.accept(self) # rule 1 (explicit return nodes in this body)
@@ -10,6 +10,21 @@ module Mutineer
10
10
  module OrphanGuard
11
11
  # Seconds between checks. A forked child gets no signal on parent death.
12
12
  POLL = 0.5
13
+ # `Tempfile.create([".mutineer_daemon", ".rb"])` names the file
14
+ # `.mutineer_daemon<YYYYMMDD>-<pid>-<rand>.rb` (without the dot before #253).
15
+ # An in-process `.mutineer_mutant` file has the same shape (#295). The pid
16
+ # is the child that is loading the mutant. An undotted name is a leftover
17
+ # of a version before 1.7.0, so its pid is not read: a reused pid must not
18
+ # keep a file that stops the next boot. A held file lock still protects it.
19
+ TEMP_PID = /\A\.mutineer_(?:daemon|mutant)\d{8}-(\d+)-/
20
+ # Basename glob for the mutant files of both modes. Tempfile puts hyphens in
21
+ # the name, so it is not a constant name. The leading dot hides a new file
22
+ # from Zeitwerk (#253); a file an older version left behind has none, so the
23
+ # glob matches both. Each boot sweep removes an orphan of either mode, so an
24
+ # old file of the other mode does not stop the boot (#287). The date and
25
+ # hyphen after the prefix keep a project's own file, such as
26
+ # `mutineer_mutant_helper.rb`, out of the sweep.
27
+ TEMP_BASENAME = "{.,}mutineer_{mutant,daemon}#{"[0-9]" * 8}-*.rb"
13
28
 
14
29
  # Starts the watchdog in the current (child) process.
15
30
  #
@@ -24,5 +39,74 @@ module Mutineer
24
39
  Process.kill(:KILL, Process.getpgrp == Process.pid ? 0 : Process.pid)
25
40
  end
26
41
  end
42
+
43
+ # True when a mutant file still belongs to a live process. A boot
44
+ # sweep must leave it alone. The database lock is taken later, so the
45
+ # sweep is the step that used to delete another run's file.
46
+ #
47
+ # The creating pid is in the file name. A process that still holds the
48
+ # file lock counts too, even when that pid is already gone. A dead pid
49
+ # and a free lock is an orphan a killed child left behind.
50
+ #
51
+ # @param path [String] absolute path of a `.mutineer_daemon*.rb` or
52
+ # `.mutineer_mutant*.rb` file.
53
+ # @return [Boolean]
54
+ def self.mutant_file_in_use?(path)
55
+ creator_alive?(path) || locked_by_another?(path)
56
+ end
57
+
58
+ # True when the pid embedded in a mutant file name is still running.
59
+ # Pid 0 is this process group, so it is never treated as an owner.
60
+ #
61
+ # @param path [String]
62
+ # @return [Boolean]
63
+ def self.creator_alive?(path)
64
+ pid_text = File.basename(path)[TEMP_PID, 1]
65
+ return false unless pid_text
66
+
67
+ pid = Integer(pid_text, 10)
68
+ return false if pid <= 0
69
+
70
+ Process.kill(0, pid)
71
+ !zombie?(pid)
72
+ rescue Errno::ESRCH, Errno::EINVAL, RangeError
73
+ false
74
+ rescue SystemCallError
75
+ true
76
+ end
77
+
78
+ # True when `pid` has exited but nobody reaped it. A container whose pid 1
79
+ # does not reap orphans keeps a dead mutant child as a zombie for good, and
80
+ # `Process.kill(0)` still finds it (#250). Linux only: elsewhere there is no
81
+ # `/proc`, so a zombie still counts as running.
82
+ #
83
+ # @param pid [Integer]
84
+ # @return [Boolean]
85
+ def self.zombie?(pid)
86
+ stat = File.read("/proc/#{pid}/stat")
87
+ # The name before the state is in parentheses and may hold ") " itself.
88
+ # An empty read (the process exited mid-read) has no ")": not a zombie.
89
+ close = stat.rindex(")")
90
+ !close.nil? && stat[close + 2] == "Z"
91
+ rescue SystemCallError
92
+ false
93
+ end
94
+
95
+ # True when another process holds an exclusive lock on `path`. A lock the
96
+ # kernel rejects as unsupported is not ownership: the pid check still applies.
97
+ # A file we cannot inspect is left in place.
98
+ #
99
+ # @param path [String]
100
+ # @return [Boolean]
101
+ def self.locked_by_another?(path)
102
+ File.open(path, File::RDONLY) do |file|
103
+ file.flock(File::LOCK_EX | File::LOCK_NB) == false
104
+ end
105
+ rescue Errno::ENOENT, Errno::ENOTSUP, Errno::EOPNOTSUPP
106
+ false
107
+ rescue SystemCallError
108
+ true
109
+ end
110
+ private_class_method :creator_alive?, :zombie?, :locked_by_another?
27
111
  end
28
112
  end
@@ -4,7 +4,7 @@ require_relative "project_path"
4
4
 
5
5
  module Mutineer
6
6
  # Source -> test pairing by path convention (#11). Pure stdlib path logic:
7
- # no Rails, no class loading, no process. Two jobs:
7
+ # no Rails, no class loading, no process. Three jobs:
8
8
  # * expand_sources — a directory argument becomes its sorted **/*.rb files;
9
9
  # a file inside the root becomes its root-relative path.
10
10
  # * infer_tests — a source's test files by convention (app/ and lib/
@@ -13,6 +13,9 @@ module Mutineer
13
13
  # namespaced subdirectories. The first EXISTING exact
14
14
  # candidate stays first. Split Minitest files join a
15
15
  # Minitest match. A matched spec is left as that one file.
16
+ # * test_given_as_source? — whether a positional argument is a test file
17
+ # by these same names, given as a source by mistake
18
+ # after `--test` (#293).
16
19
  #
17
20
  # Independently unit-testable: every method is pure in/out over the
18
21
  # filesystem, so the pairing contract is exercised with plain fixtures, no
@@ -144,6 +147,64 @@ module Mutineer
144
147
  prefer == "rspec" ? rspec + minitest : minitest + rspec
145
148
  end
146
149
 
150
+ # Basenames that pair as tests in {candidates}: `*_test.rb`, `*_spec.rb`
151
+ # and Minitest's `test_*.rb`, but not its `test_helper.rb` support file.
152
+ TEST_NAME = /\A(?!test_helper\.rb\z)(?:.+_(?:test|spec)|test_.+)\.rb\z/
153
+
154
+ # Whether the `run` guard rejects a positional argument as a test file
155
+ # given as a source (#293). Segments are read from the path relative to
156
+ # the root, so a `test/` folder above the project never counts. A
157
+ # `*_test.rb` / `*_spec.rb` path is flagged when it has a `test/` or
158
+ # `spec/` segment (the guard's original rule), or when it sits in the same
159
+ # directory as a given test, which catches root-level tests. A
160
+ # `test_*.rb` path is flagged only under the
161
+ # project's top-level `test/` or `spec/`, because real sources use the
162
+ # prefix (`lib/mutineer/test_runners.rb`, `lib/foo/test/test_app.rb`). A
163
+ # source whose own test (`<stem>_test.rb`, `test_<stem>.rb`,
164
+ # `<stem>_spec.rb`, or a split `<stem>_*_test.rb` not claimed by a longer
165
+ # source on disk) sits beside it in the test set is not flagged. Paths
166
+ # compare relative to the root, as in
167
+ # {expand_sources} (the root's real path counts too, for macOS `/var` vs
168
+ # `/private/var`), so `./a_test.rb` and `a_test.rb` match. No file content
169
+ # is read.
170
+ #
171
+ # @param path [String] positional argument as typed.
172
+ # @param project_root [String] repository root for relative expansion.
173
+ # @param tests [Array<String>] the explicit test files.
174
+ # @return [Boolean] true when the argument looks like a misplaced test.
175
+ def test_given_as_source?(path, project_root:, tests:)
176
+ name = File.basename(path)
177
+ return false unless name.match?(TEST_NAME)
178
+
179
+ root = File.expand_path(project_root)
180
+ roots = [root, ProjectPath.root_real(root)].uniq
181
+ relative = lambda do |p|
182
+ abs = File.expand_path(p, root)
183
+ root_relative(abs, roots) || abs
184
+ end
185
+ rel = relative.call(path)
186
+ # Outside the root, read segments from a relative path as typed
187
+ # (`../test/b_test.rb`) and not from an absolute one, so a `test/`
188
+ # folder above the root never counts.
189
+ segments = root_relative(File.expand_path(path, root), roots)
190
+ segments ||= path.start_with?(File::SEPARATOR) ? "" : path
191
+ return segments.match?(%r{\A(test|spec)/}) unless name.match?(/_(test|spec)\.rb\z/)
192
+ return true if segments.match?(%r{(\A|/)(test|spec)/})
193
+
194
+ dir = File.dirname(rel)
195
+ beside = Array(tests).map(&relative)
196
+ .select { |t| File.dirname(t) == dir }
197
+ .map { |t| File.basename(t) }
198
+ stem = File.basename(name, ".rb")
199
+ own = ["test_#{stem}.rb", "#{stem}_spec.rb"]
200
+ base = rel.delete_suffix(".rb")
201
+ return false if beside.any? do |t|
202
+ own.include?(t) || (longer_owns_entry?(t, stem) && !claimed_by_longer_source?(root, base, t))
203
+ end
204
+
205
+ beside.any?
206
+ end
207
+
147
208
  # `<basename>_*_test.rb` files in each mirrored test directory (#87). The
148
209
  # exact `<basename>_test.rb` name is not included. `lib/` sources also look
149
210
  # under `test/lib/`. Names are matched as text, not as a glob, so a basename