rubocop-dev_doc 0.17.0 → 0.19.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 (48) hide show
  1. checksums.yaml +4 -4
  2. data/config/default.yml +461 -62
  3. data/config/obsoletion.yml +7 -3
  4. data/lib/dev_doc/i18n/pseudo_locale.rb +1 -1
  5. data/lib/dev_doc/i18n/tasks.rb +68 -0
  6. data/lib/dev_doc/railtie.rb +19 -0
  7. data/lib/dev_doc/test/lints/cross_tenant_canary_check.rb +1 -1
  8. data/lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb +8 -3
  9. data/lib/dev_doc/test/lints/http_driven_controller_tests.rb +4 -0
  10. data/lib/dev_doc/test/lints/no_file_excludes.rb +1 -1
  11. data/lib/dev_doc/test/pseudo_i18n_crawler.rb +9 -0
  12. data/lib/rubocop/cop/dev_doc/auth/adjacent_justification.rb +44 -7
  13. data/lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb +2 -2
  14. data/lib/rubocop/cop/dev_doc/auth/login_only_policy_justification.rb +1 -1
  15. data/lib/rubocop/cop/dev_doc/auth/unscoped_find_justification.rb +2 -2
  16. data/lib/rubocop/cop/dev_doc/bundler/conflicting_gem.rb +74 -0
  17. data/lib/rubocop/cop/dev_doc/exception_class_list.rb +32 -0
  18. data/lib/rubocop/cop/dev_doc/i18n/hardcoded_text.rb +243 -0
  19. data/lib/rubocop/cop/dev_doc/i18n/localizable_props.rb +69 -19
  20. data/lib/rubocop/cop/dev_doc/i18n/require_translation.rb +13 -17
  21. data/lib/rubocop/cop/dev_doc/i18n/text_shape.rb +94 -0
  22. data/lib/rubocop/cop/dev_doc/i18n/translation_key_prefix.rb +1 -1
  23. data/lib/rubocop/cop/dev_doc/migration/legacy_migration.rb +26 -0
  24. data/lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb +5 -15
  25. data/lib/rubocop/cop/dev_doc/migration/require_reference_index.rb +115 -0
  26. data/lib/rubocop/cop/dev_doc/rails/avoid_bypassing_validation.rb +81 -26
  27. data/lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb +1 -1
  28. data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
  29. data/lib/rubocop/cop/dev_doc/rails/no_errors_add_in_controller.rb +177 -0
  30. data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +236 -0
  31. data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
  32. data/lib/rubocop/cop/dev_doc/style/in_memory_association_find.rb +162 -0
  33. data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +279 -0
  34. data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
  35. data/lib/rubocop/cop/dev_doc/style/prefer_allowlist_symbol_param.rb +193 -0
  36. data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
  37. data/lib/rubocop/cop/dev_doc/style/use_g_log.rb +133 -0
  38. data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
  39. data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
  40. data/lib/rubocop/cop/dev_doc/test/prefer_find_sole_by.rb +146 -0
  41. data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
  42. data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
  43. data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
  44. data/lib/rubocop/cop/dev_doc/test/test_name_special_characters.rb +108 -0
  45. data/lib/rubocop/cop/dev_doc/view/prefer_prop_over_name.rb +11 -1
  46. data/lib/rubocop/dev_doc/version.rb +1 -1
  47. metadata +24 -4
  48. data/lib/rubocop/cop/dev_doc/i18n/report_text.rb +0 -76
@@ -0,0 +1,216 @@
1
+ require_relative 'justification_header'
2
+ require_relative 'test_file_placement'
3
+
4
+ module RuboCop
5
+ module Cop
6
+ module DevDoc
7
+ module Test
8
+ # Every test under a justification header must call a method its
9
+ # `Covers:` line lists.
10
+ #
11
+ # A justification header licenses a whole FILE at the keyboard, but
12
+ # its impossibility claim is usually about one BEHAVIOUR. The
13
+ # `Covers:` line pins the file to that claim: it names the methods
14
+ # the claim covers (`method`, `Class#method`, `Class.method` or a
15
+ # constant name, comma-separated), and every test in the file must
16
+ # call one of them. The list may wrap onto the next comment line
17
+ # only while it ends with a trailing comma — prose after a complete
18
+ # list is justification text, never entries.
19
+ #
20
+ # ## Rationale
21
+ # The shape that slipped through an approved review: a header
22
+ # justifying one method sat in an open unit file, a later test of a
23
+ # different, HTTP-reachable method was added under it, and every
24
+ # safeguard stayed silent — the placement cop is satisfied by the
25
+ # header that already exists, and the reviewer rule in the testing
26
+ # best practice triggers only when a diff edits the header itself.
27
+ # `Covers:` makes the licence explicit and moves the check to the
28
+ # keyboard: a test of an unlisted method offends here, and the only
29
+ # way to quiet the offense is to edit `Covers:` — a header edit,
30
+ # the one diff shape the reviewer rule already treats as "this
31
+ # claim needs tracing".
32
+ #
33
+ # ## Breadth
34
+ # An entry is as wide as the method it names: `valid?`, `save!` or
35
+ # `perform` on a model re-licenses most of a file. The cop cannot
36
+ # judge breadth; review judges each `Covers:` entry as it judges
37
+ # the impossibility claim itself (the testing best-practice
38
+ # reviewer rule covers this). A header whose claim covers the whole
39
+ # file lists its methods — a cron job lists `perform`, a
40
+ # rake-backed command lists its public commands. There is
41
+ # deliberately no wildcard entry.
42
+ #
43
+ # ## Exception
44
+ # None beyond extending `Covers:` with a new entry justified in the
45
+ # header; an inline disable is not the intended path. A test that
46
+ # exercises an unlisted method usually wants to be a request test —
47
+ # the escape hatch in DevDoc/Test/AvoidUnitTest lists the patterns
48
+ # (inject a failure at a chokepoint the real request hits, assert
49
+ # the observable through the real path) that make seemingly
50
+ # unit-only behaviour reachable end-to-end.
51
+ #
52
+ # NOTE: entries match on METHOD NAME — the part after the last `#`
53
+ # or `.` of each entry; receiver types are not statically knowable,
54
+ # so a `Class#`/`Class.` prefix is documentation for the reviewer,
55
+ # not a discriminator. An entry may instead name a CONSTANT (a
56
+ # drift guard over a constant matches the reference to it), and a
57
+ # literal `send`/`public_send` dispatch counts as the method it
58
+ # names. A header can also go stale: a new HTTP caller of a covered
59
+ # method re-opens what the claim licensed — no cop catches that;
60
+ # the wiring line's claim is what review checks when it drifts.
61
+ # And a header whose subject is a FILE rather than a method or
62
+ # constant (a schedule-table or config-lint guard) cannot be
63
+ # matched by any entry: name the method the test reads the file
64
+ # through, or move the check to a build-time lint.
65
+ #
66
+ # @example
67
+ # # bad — the header's claim covers merge_profiles!, but the test
68
+ # # drives create_with_defaults!, which a request reaches:
69
+ # # deliberate exception: merge_profiles! has no HTTP write path.
70
+ # # Wiring: member_merges_test drives the request write paths.
71
+ # # Covers: Member#merge_profiles!
72
+ # class MemberTest < Glib::LastResortUnitTest
73
+ # test 'create rolls back on a duplicate handle' do
74
+ # assert_raises(RecordInvalid) { member.create_with_defaults! }
75
+ # end
76
+ # end
77
+ #
78
+ # # good — the test drives the covered method:
79
+ # # deliberate exception: merge_profiles! has no HTTP write path.
80
+ # # Wiring: member_merges_test drives the request write paths.
81
+ # # Covers: Member#merge_profiles!
82
+ # class MemberTest < Glib::LastResortUnitTest
83
+ # test 'merge is idempotent' do
84
+ # 2.times { member.merge_profiles!(other) }
85
+ # end
86
+ # end
87
+ class JustificationCovers < Base
88
+ include JustificationHeader
89
+ include TestFilePlacement
90
+
91
+ MSG_MISSING = 'Justification header lacks a "%<phrase>s" line naming the methods its ' \
92
+ 'claim covers. Each test in the file must call one of them; a test of ' \
93
+ 'anything else wants a request test (see DevDoc/Test/AvoidUnitTest), or ' \
94
+ 'a header that justifies it.'.freeze
95
+
96
+ MSG_UNCOVERED = 'This test calls none of the header\'s `Covers:` methods (%<covers>s). ' \
97
+ 'Write it as a request test (see the escape hatch in ' \
98
+ 'DevDoc/Test/AvoidUnitTest), or extend `Covers:` and justify the new ' \
99
+ 'entry in the header.'.freeze
100
+
101
+ # A `perform` entry also matches the job-invocation family job tests use.
102
+ PERFORM_FAMILY = %w[perform_now perform_later perform_enqueued_jobs].freeze
103
+
104
+ # A literal `obj.send(:private_thing)` dispatches to private_thing —
105
+ # the call set counts the dispatched name, not just `send`.
106
+ DISPATCH_METHODS = %w[send public_send __send__].freeze
107
+
108
+ def on_new_investigation
109
+ # Cop instances are reused across files within a run; the
110
+ # same-file helper index is per investigation.
111
+ @same_file_defs = nil
112
+ return if processed_source.blank?
113
+ return unless justification_header_required?
114
+ # A missing header is RequireUnitTestJustification's to report;
115
+ # this cop never double-reports it.
116
+ return unless leading_comments_contain?(marker_phrase)
117
+
118
+ covers = covers_entries
119
+ if covers.empty?
120
+ add_offense(offense_range, message: format(MSG_MISSING, phrase: covers_phrase))
121
+ else
122
+ check_test_definitions(covers)
123
+ end
124
+ end
125
+
126
+ private
127
+
128
+ def check_test_definitions(covers)
129
+ accepted = covers + (covers.include?('perform') ? PERFORM_FAMILY : [])
130
+ each_test_definition do |anchor, body|
131
+ next if calls_covered?(body, accepted)
132
+
133
+ add_offense(anchor, message: format(MSG_UNCOVERED, covers: covers.join(', ')))
134
+ end
135
+ end
136
+
137
+ # `test '...' do` blocks and `def test_*` methods, each with the
138
+ # range an offense anchors on and the body whose calls count.
139
+ def each_test_definition(&)
140
+ return unless processed_source.ast
141
+
142
+ each_test_block(&)
143
+ each_test_method(&)
144
+ end
145
+
146
+ def each_test_block
147
+ processed_source.ast.each_node(:block, :numblock) do |node|
148
+ next unless node.send_node.method?(:test)
149
+
150
+ yield node.send_node.loc.selector, node.body
151
+ end
152
+ end
153
+
154
+ def each_test_method
155
+ processed_source.ast.each_node(:def) do |node|
156
+ next unless node.method_name.to_s.start_with?('test_')
157
+
158
+ yield node.loc.name, node.body
159
+ end
160
+ end
161
+
162
+ def calls_covered?(body, accepted)
163
+ calls_of(body, Set.new).any? { |name| accepted.include?(name) }
164
+ end
165
+
166
+ # The names a body references: every send/csend's method (a literal
167
+ # `send`/`public_send` argument counts as the method it dispatches
168
+ # to), every constant's name (an entry may name a constant the
169
+ # header's claim licenses), plus the bodies of same-file `def`s it
170
+ # calls, transitively. setup/teardown are never part of a test's
171
+ # body, so their fixture calls never count toward a test.
172
+ def calls_of(node, names, walked = Set.new)
173
+ return names unless node
174
+
175
+ node.each_node(:send, :csend, :const) do |child|
176
+ if child.const_type?
177
+ names << child.children.last.to_s
178
+ else
179
+ collect_call(child, names, walked)
180
+ end
181
+ end
182
+ names
183
+ end
184
+
185
+ def collect_call(call, names, walked)
186
+ name = call.method_name.to_s
187
+ names << name
188
+ collect_dispatched_name(call, names) if DISPATCH_METHODS.include?(name)
189
+
190
+ helper = same_file_defs[name]
191
+ return if helper.nil? || walked.include?(name)
192
+
193
+ walked << name
194
+ calls_of(helper.body, names, walked)
195
+ end
196
+
197
+ def collect_dispatched_name(call, names)
198
+ arg = call.first_argument
199
+ return unless arg && (arg.sym_type? || arg.str_type?)
200
+
201
+ names << arg.value.to_s
202
+ end
203
+
204
+ def same_file_defs
205
+ @same_file_defs ||= begin
206
+ defs = {}
207
+ root = processed_source.ast
208
+ root&.each_node(:def) { |defn| defs[defn.method_name.to_s] ||= defn }
209
+ defs
210
+ end
211
+ end
212
+ end
213
+ end
214
+ end
215
+ end
216
+ end
@@ -7,8 +7,9 @@ module RuboCop
7
7
  # first class/module) that contain the marker phrase (why a controller
8
8
  # test can't cover this) AND a wiring line (which request test still
9
9
  # covers the HTTP path its subject participates in — or why no runtime
10
- # HTTP path exists). Host cops must provide `offense_range` and
11
- # `cop_config`.
10
+ # HTTP path exists). The `Covers:` line (which methods the header's
11
+ # claim licenses) is parsed here too. Host cops must provide
12
+ # `cop_config`; `offense_range` is provided here.
12
13
  module JustificationHeader
13
14
  MSG_JUSTIFY = 'Unit-test file without a justification header. Controller tests catch the ' \
14
15
  'wiring bugs unit tests miss, so first assume a controller test IS possible ' \
@@ -54,9 +55,8 @@ module RuboCop
54
55
  end
55
56
 
56
57
  def leading_comments_contain?(phrase)
57
- processed_source.comments.any? do |comment|
58
- comment.location.line < first_definition_line &&
59
- comment.text.downcase.include?(phrase.downcase)
58
+ leading_comments.any? do |comment|
59
+ comment.text.downcase.include?(phrase.downcase)
60
60
  end
61
61
  end
62
62
 
@@ -70,9 +70,90 @@ module RuboCop
70
70
  (definition || root).first_line
71
71
  end
72
72
 
73
+ # The header's `Covers:` entries as matched names: the part after
74
+ # the last `#`, `.` or `::` of each comma-separated entry (a
75
+ # method entry matches its method name; a constant entry its
76
+ # constant's short name). The list wraps onto the next comment
77
+ # line only while it ends with a trailing comma (see
78
+ # fold_continuations). Empty when the header has no `Covers:`
79
+ # line at all.
80
+ def covers_entries
81
+ body = covers_comment_body
82
+ return [] if body.empty?
83
+
84
+ body.split(',').map { |entry| entry.strip.split(/::|[#.]/).last.to_s.strip }.reject(&:empty?)
85
+ end
86
+
87
+ # The text of the `Covers:` line plus its continuations, joined.
88
+ def covers_comment_body
89
+ comments = leading_comments
90
+ start = covers_comment_index(comments)
91
+ return '' if start.nil?
92
+
93
+ covers_comment = comments[start]
94
+ remainder = strip_comment_marker(covers_comment)[covers_phrase.length..].to_s
95
+ fold_continuations(comments[(start + 1)..], remainder, covers_comment.location.line + 1)
96
+ end
97
+
98
+ def covers_comment_index(comments)
99
+ comments.index { |comment| covers_line?(comment) }
100
+ end
101
+
102
+ # A continuation joins the list only while the accumulated text
103
+ # ends with a trailing comma (the list is syntactically
104
+ # incomplete) AND the line is the next physical comment line; a
105
+ # blank comment line or another header label ends it. Prose after
106
+ # a complete list is never folded in — it is justification text,
107
+ # not entries.
108
+ def fold_continuations(comments, text, next_line)
109
+ comments.each do |comment|
110
+ break unless text.rstrip.end_with?(',')
111
+ break if comment.location.line != next_line
112
+
113
+ line = strip_comment_marker(comment)
114
+ break if line.strip.empty? || labeled_line?(line)
115
+
116
+ text += " #{line}"
117
+ next_line += 1
118
+ end
119
+ text
120
+ end
121
+
122
+ # The header window: comments before the first class/module, the
123
+ # same window leading_comments_contain? matches in.
124
+ def leading_comments
125
+ processed_source.comments.select { |comment| comment.location.line < first_definition_line }
126
+ end
127
+
128
+ def covers_line?(comment)
129
+ strip_comment_marker(comment).downcase.start_with?(covers_phrase.downcase)
130
+ end
131
+
132
+ def strip_comment_marker(comment)
133
+ comment.text.sub(/\A#\s*/, '')
134
+ end
135
+
136
+ # Another header label (`Wiring:`, a second `Covers:`) ends a
137
+ # continuation: its content belongs to that line, not to Covers.
138
+ # A namespaced constant (`Registry::SEGMENT_MAP`) is NOT a label
139
+ # — the negative lookahead keeps `Registry:` from matching.
140
+ def labeled_line?(text)
141
+ text.match?(/\A[A-Za-z]\w*:(?!:)/)
142
+ end
143
+
73
144
  def marker_phrase = cop_config.fetch('MarkerPhrase', 'deliberate exception')
74
145
 
75
146
  def wiring_phrase = cop_config.fetch('WiringPhrase', 'wiring:').to_s
147
+
148
+ def covers_phrase = cop_config.fetch('CoversPhrase', 'covers:')
149
+
150
+ # The one-line range a file-level offense anchors on: the first
151
+ # line of the AST (a require, when present) or of the first
152
+ # comment. Provided here so every header cop anchors identically.
153
+ def offense_range
154
+ range = processed_source.ast&.source_range || processed_source.comments.first&.source_range
155
+ range.with(end_pos: range.begin_pos + [range.source_line.length, 1].max)
156
+ end
76
157
  end
77
158
  end
78
159
  end
@@ -0,0 +1,146 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Test
5
+ # In test files, a `find_by` / `find_by!` on a bare model class must be
6
+ # `find_sole_by`, so a lookup that matches more than one row fails
7
+ # loudly instead of silently picking one.
8
+ #
9
+ # ## Rationale
10
+ # `Post.find_by(title: 'Hello')` returns the FIRST matching row, and
11
+ # with no `ORDER BY` "first" means whichever row the database returns
12
+ # first — which can differ between runs, between seeds, and between
13
+ # machines. When the attribute is not unique across the whole table,
14
+ # the test binds to a different record on a different day and fails
15
+ # far from the cause: the wrong fixture's association is `nil`, and the
16
+ # symptom is something like
17
+ # `ActionController::UrlGenerationError: ... missing required keys: [:id]`
18
+ # in a test whose diff never touched routing. The failure reproduces
19
+ # only under the seed that happened to expose the ordering, so it reads
20
+ # as a flake.
21
+ #
22
+ # Uniqueness is a property of the DATA, not of the attribute name. An
23
+ # `email` is unique per user but repeats across a tenant-scoped
24
+ # membership table (one row per organization the person belongs to);
25
+ # a `slug` looks like a natural key and still repeats per country. The
26
+ # only way to know is to read the fixture file — and `find_sole_by`
27
+ # does that check for you on every run: it raises
28
+ # `ActiveRecord::SoleRecordExceeded` when more than one row matches
29
+ # (and `RecordNotFound` when none does, like `find_by!`). A test that
30
+ # assumed uniqueness now asserts it.
31
+ #
32
+ # This cop catches the shape that shipped: the bare-class lookup, where
33
+ # the scope is the whole table. Scoping the lookup through the parent
34
+ # association is the other remedy, and it silences the cop because the
35
+ # receiver is no longer a constant — but the assumption only shrinks
36
+ # from "unique in the table" to "unique within the parent";
37
+ # `find_sole_by` on the association asserts that too.
38
+ #
39
+ # ## Remedy
40
+ #
41
+ # ❌ — silently picks one of several matching rows
42
+ # member = Member.find_by(email: 'admin@example.com')
43
+ # member = Member.find_by!(email: 'admin@example.com')
44
+ #
45
+ # ✔️ — raises if the match is not exactly one row
46
+ # member = Member.find_sole_by(email: 'admin@example.com')
47
+ #
48
+ # ✔️ — scoped through the parent (and still asserted unique within it)
49
+ # member = organizations(:acme).members.find_sole_by(email: 'admin@example.com')
50
+ #
51
+ # ✔️ — a fixture accessor is the canonical way to name a known row
52
+ # member = members(:acme_admin)
53
+ #
54
+ # ✔️ — a test that expects NO row asserts absence, not a nil return
55
+ # assert_not Member.exists?(email: 'gone@example.com')
56
+ #
57
+ # ## Autocorrect
58
+ # `find_by!` → `find_sole_by` is autocorrected: both raise when nothing
59
+ # matches, and the only behaviour that changes is the ambiguous case,
60
+ # which now fails instead of passing by luck. A test that starts
61
+ # failing after the correction is the cop finding the bug — fix the
62
+ # lookup (scope it or pick a unique attribute), not the assertion.
63
+ #
64
+ # `find_by` (no bang) is flagged but NOT autocorrected: it returns `nil`
65
+ # when nothing matches, and a test may rely on that
66
+ # (`assert_nil Post.find_by(title: 'deleted')`). Rewrite by hand:
67
+ # `find_sole_by` where the row is expected to exist, `exists?` where it
68
+ # is expected not to.
69
+ #
70
+ # ## What is NOT flagged
71
+ # - Lookups by primary key alone — `Post.find_by(id: some_id)` cannot
72
+ # match twice, and is the idiom for "nil once deleted".
73
+ # - Lookups whose receiver is not the bare class — an association, a
74
+ # fixture accessor, a scope chain (`Post.published.find_by(...)`), a
75
+ # local. Scoping IS the fix this cop pushes toward; the chain case is
76
+ # deliberately out of scope until observed. (`self.class.find_by`
77
+ # inside a test helper IS the bare class, and is flagged.)
78
+ # - Anything outside `test/` and `spec/` (`Include` in the config) —
79
+ # production code returning the first match is a separate concern.
80
+ #
81
+ # NOTE: `find_sole_by` exists from Rails 7.0. On an older consumer the
82
+ # autocorrect produces a `NoMethodError`; disable the cop there.
83
+ #
84
+ # @example
85
+ # # bad
86
+ # member = Member.find_by(email: 'admin@example.com')
87
+ # member = Member.find_by!(email: 'admin@example.com')
88
+ #
89
+ # # good
90
+ # member = Member.find_sole_by(email: 'admin@example.com')
91
+ # member = organizations(:acme).members.find_sole_by(email: 'admin@example.com')
92
+ # member = members(:acme_admin)
93
+ #
94
+ # # good — primary key cannot match twice
95
+ # assert_nil Member.find_by(id: removed_id)
96
+ class PreferFindSoleBy < Base
97
+ extend AutoCorrector
98
+
99
+ MSG_BANG = '`%<receiver>s.find_by!` returns whichever matching row the database yields ' \
100
+ 'first — if the attribute is not unique across the table the test binds to a ' \
101
+ 'different record per run. Use `find_sole_by`, which raises when the match ' \
102
+ 'is not exactly one row.'.freeze
103
+ MSG_PLAIN = '`%<receiver>s.find_by` returns whichever matching row the database yields ' \
104
+ 'first — if the attribute is not unique across the table the test binds to ' \
105
+ 'a different record per run. Use `find_sole_by` (raises unless exactly one ' \
106
+ 'row matches); if the test expects NO row, assert `exists?` instead.'.freeze
107
+
108
+ RESTRICT_ON_SEND = %i[find_by find_by!].freeze
109
+
110
+ # The bare class: a constant, or `self.class` inside a test helper.
111
+ # @!method bare_class?(node)
112
+ def_node_matcher :bare_class?, <<~PATTERN
113
+ {const (send self :class)}
114
+ PATTERN
115
+
116
+ # `Post.find_by(id: x)`: the primary key alone cannot match twice.
117
+ # @!method primary_key_only?(node)
118
+ def_node_matcher :primary_key_only?, <<~PATTERN
119
+ ({send csend} _ _ (hash (pair (sym :id) _)))
120
+ PATTERN
121
+
122
+ def on_send(node)
123
+ return unless node.receiver && bare_class?(node.receiver)
124
+ return if primary_key_only?(node)
125
+
126
+ if node.method?(:find_by!)
127
+ add_offense(node.loc.selector, message: message_for(node, MSG_BANG)) do |corrector|
128
+ corrector.replace(node.loc.selector, 'find_sole_by')
129
+ end
130
+ else
131
+ add_offense(node.loc.selector, message: message_for(node, MSG_PLAIN))
132
+ end
133
+ end
134
+ alias on_csend on_send
135
+
136
+ private
137
+
138
+ def message_for(node, template)
139
+ receiver = node.receiver.const_type? ? node.receiver.const_name : 'self.class'
140
+ format(template, receiver: receiver)
141
+ end
142
+ end
143
+ end
144
+ end
145
+ end
146
+ end
@@ -0,0 +1,154 @@
1
+ require_relative 'test_file_placement'
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module DevDoc
6
+ module Test
7
+ # A test class under test/jobs must invoke the job it is parked
8
+ # next to: its own body, or the body of a same-file ancestor
9
+ # class, contains a send from the entry-point set (`perform`,
10
+ # `perform_now`, `perform_later`, `perform_enqueued_jobs`).
11
+ #
12
+ # ## Rationale
13
+ # test/jobs is the inbound-edge directory: the job IS the
14
+ # boundary, and a job test that never dispatches it tests nothing
15
+ # the directory promises. The observed evasion (fictional names):
16
+ # a service-flow test moved by file only —
17
+ # `SyncOrdersFromVendor.new(row, client: FakeClient.new([...])).call`
18
+ # — under the integration base, ~18 cases in one consumer file.
19
+ # The job's dispatch, guards and follow-up enqueues never ran, the
20
+ # whole Test pack stayed quiet, and other files' justification
21
+ # headers still carried `Wiring:` lines pointing at the file as
22
+ # their cover. Suffix-based unit-class detection
23
+ # (DevDoc/Test/NoUnitIdiomsInIntegrationTests) cannot catch it — a
24
+ # verb-phrase service name is not a unit suffix — and extending
25
+ # that cop's Include into test/jobs was measured and rejected:
26
+ # over the 32-file consumer corpus (five projects) the suffix rule
27
+ # found 0 true hits while the pack's other idiom rules would fire
28
+ # ~70 times on legitimate outbound-edge fakes (stub/Mock machinery
29
+ # in 5 files, one holding 52 stub sends; direct mailer sends in
30
+ # 4). Requiring the entry point instead catches the whole file
31
+ # regardless of how the service is named.
32
+ #
33
+ # The signal is per `*Test` class with same-file ancestry, because
34
+ # that is how honest corpora are shaped: one consumer holds a
35
+ # shared in-file base whose helper drives the job (`run_review`
36
+ # calling `ReviewJob.new.perform(row.id)`) with ~20 subclasses
37
+ # whose own bodies call only the helper — body-only checking
38
+ # would flag every one of them. Only `*Test`-named classes are
39
+ # checked, so in-file scaffolding bases and fake doubles never
40
+ # flag themselves. The rule is base-agnostic: any base is
41
+ # legitimate in this directory; the entry-point contract is the
42
+ # directory's, not the base's.
43
+ #
44
+ # NOTE: Residuals. (a) An enqueue-routing test whose trigger is
45
+ # not a job send (a request, a service call) inside
46
+ # `assert_enqueued_with` never invokes the job — such a test takes
47
+ # an inline disable with a rationale. (b) A performing helper in
48
+ # an included test-helper MODULE is invisible to same-file
49
+ # ancestry; that shape takes an inline disable too. (c) Service
50
+ # instantiation inside an honest perform-driving job test, suffix
51
+ # or not, is not flagged — review's to catch. (d) The cop makes
52
+ # no semantic is-really-testing-the-job judgement: presence of an
53
+ # entry-point send is the whole test, and a bare `perform_later`
54
+ # with no drain satisfies without ever running the job.
55
+ # (e) Ancestry matches const names as spelled — `class
56
+ # Prs::PostTest < Prs::FlowTestCase` does not link to `module Prs;
57
+ # class FlowTestCase` in the same file. Spell both sides the same
58
+ # way, or take an inline disable.
59
+ #
60
+ # @example
61
+ # # bad — test/jobs/sync_orders_job_test.rb
62
+ # class SyncOrdersJobTest < Glib::IntegrationTest
63
+ # test 'vendor timeout falls back' do
64
+ # row = orders(:one)
65
+ # SyncOrdersFromVendor.new(row, client: FakeClient.new([...])).call
66
+ # assert row.reload.synced?
67
+ # end
68
+ # end
69
+ #
70
+ # # good — the job is the entry point, the far side is faked
71
+ # class SyncOrdersJobTest < Glib::IntegrationTest
72
+ # test 'vendor timeout falls back' do
73
+ # row = orders(:one)
74
+ # SyncOrdersJob.perform_now(row, client: fake_client(timeout: true))
75
+ # assert row.reload.synced?
76
+ # end
77
+ # end
78
+ class RequireJobInvocationInJobTests < Base
79
+ include TestFilePlacement
80
+
81
+ MSG = 'This test class never invokes the job. A test under test/jobs is a boundary test — ' \
82
+ 'drive the entry point (`perform`, `perform_now`, `perform_later`, ' \
83
+ '`perform_enqueued_jobs`) with the far side faked and assert what is observable; ' \
84
+ 'a service-flow test that never dispatches the job belongs where the service is ' \
85
+ 'the boundary.'.freeze
86
+
87
+ # The entry-point set lives in code, not config: config lists are
88
+ # droppable, code baselines are not (see
89
+ # NoUnitIdiomsInIntegrationTests::DEFAULT_UNIT_CLASS_SUFFIXES for
90
+ # the incident that taught this).
91
+ ENTRY_POINT_SENDS = %i[perform perform_now perform_later perform_enqueued_jobs].freeze
92
+
93
+ def on_new_investigation
94
+ return if processed_source.blank?
95
+ # In-module guard on purpose: the config Include says the same,
96
+ # but the cop must stay correct even when run with a forced
97
+ # config.
98
+ return unless test_subdirectory == 'jobs'
99
+
100
+ classes_by_name = {}
101
+ processed_source.ast.each_node(:class) do |class_node|
102
+ (classes_by_name[class_node.identifier.const_name] ||= []) << class_node
103
+ end
104
+
105
+ each_test_class do |class_node, _parent|
106
+ next if invokes_job?(class_node, classes_by_name)
107
+
108
+ add_offense(class_node.loc.name)
109
+ end
110
+ end
111
+
112
+ private
113
+
114
+ # Satisfied by an entry-point send anywhere in the class's own
115
+ # body, or in the body of an ancestor class defined in the same
116
+ # file: a shared in-file base whose helper drives the job is the
117
+ # class's driver as much as its own test blocks are. Ancestors
118
+ # resolve by const name against the file's class nodes; a parent
119
+ # defined elsewhere (or none) ends the chain. `visited` keeps the
120
+ # walk finite under reopened class names.
121
+ def invokes_job?(class_node, classes_by_name)
122
+ performs_by_name?(class_node.identifier.const_name, classes_by_name, {})
123
+ end
124
+
125
+ def performs_by_name?(name, classes_by_name, visited)
126
+ return false if visited[name]
127
+
128
+ visited[name] = true
129
+ nodes = classes_by_name[name]
130
+ return false unless nodes
131
+
132
+ nodes.any? { |node| performs_entry_point?(node.body) } ||
133
+ nodes.any? { |node| same_file_parent_performs?(node, classes_by_name, visited) }
134
+ end
135
+
136
+ def same_file_parent_performs?(node, classes_by_name, visited)
137
+ parent = node.parent_class&.const_name
138
+ return false unless parent
139
+
140
+ performs_by_name?(parent, classes_by_name, visited)
141
+ end
142
+
143
+ def performs_entry_point?(body)
144
+ return false unless body
145
+
146
+ body.each_node(:send, :csend).any? do |send|
147
+ ENTRY_POINT_SENDS.include?(send.method_name)
148
+ end
149
+ end
150
+ end
151
+ end
152
+ end
153
+ end
154
+ end