Module: Mbeditor::TestRunnerService

Defined in:
app/services/mbeditor/test_runner_service.rb

Overview

Runs a Ruby test file (Minitest or RSpec) and parses the output into a structured result suitable for the editor UI.

Follows the same process-group kill pattern used by the lint endpoint to enforce a configurable timeout.

Class Method Summary collapse

Class Method Details

.build_command(repo_path, test_path, framework, custom_command, line: nil) ⇒ Object

Builds the argv for a run. When line is given the run is narrowed to the single test at that line; the filter syntax follows the detected framework, not the runner binary, so custom commands still get filtering.



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
# File 'app/services/mbeditor/test_runner_service.rb', line 105

def build_command(repo_path, test_path, framework, custom_command, line: nil)
  full_path = File.join(repo_path, test_path)
  line = nil unless line.is_a?(Integer) && line.positive?

  if custom_command.present?
    tokens = Shellwords.split(custom_command)
    return tokens + [full_path] unless line

    # rspec understands path:line; the minitest runners need a name filter.
    return tokens + ["#{full_path}:#{line}"] if framework.to_sym == :rspec

    return tokens + [full_path] + minitest_name_filter(full_path, line)
  end

  case framework.to_sym
  when :rspec
    bin = File.join(repo_path, "bin", "rspec")
    cmd = File.exist?(bin) ? [bin] : ["bundle", "exec", "rspec"]
    target = line ? "#{full_path}:#{line}" : full_path
    cmd + ["--format", "json", target]
  when :minitest
    bin = File.join(repo_path, "bin", "rails")
    if File.exist?(bin)
      # `bin/rails test path:line` (Rails >= 6); the gemspec floor is 7.1.
      target = line ? "#{full_path}:#{line}" : full_path
      [bin, "test", "--verbose", target]
    else
      ["bundle", "exec", "ruby", "-Itest", full_path, "--verbose"] +
        (line ? minitest_name_filter(full_path, line) : [])
    end
  else
    ["bundle", "exec", "ruby", "-Itest", full_path]
  end
end

.detect_framework(repo_path, test_path) ⇒ Object



91
92
93
94
95
96
97
98
99
100
# File 'app/services/mbeditor/test_runner_service.rb', line 91

def detect_framework(repo_path, test_path)
  return :rspec if test_path.end_with?("_spec.rb")
  return :minitest if test_path.end_with?("_test.rb")

  # Check project-level hints
  return :rspec if File.exist?(File.join(repo_path, ".rspec"))
  return :rspec if File.exist?(File.join(repo_path, "spec"))

  :minitest if File.exist?(File.join(repo_path, "test"))
end

.empty_summaryObject



297
298
299
# File 'app/services/mbeditor/test_runner_service.rb', line 297

def empty_summary
  { total: 0, passed: 0, failed: 0, errored: 0, skipped: 0, duration: nil }
end

.error_result(message) ⇒ Object



301
302
303
304
305
306
307
308
309
# File 'app/services/mbeditor/test_runner_service.rb', line 301

def error_result(message)
  {
    ok: false,
    error: message,
    summary: empty_summary,
    tests: [],
    raw: ""
  }
end

.execute_with_timeout(repo_path, cmd, timeout) ⇒ Object



174
175
176
177
# File 'app/services/mbeditor/test_runner_service.rb', line 174

def execute_with_timeout(repo_path, cmd, timeout)
  result = ProcessRunner.call(cmd, timeout: timeout, chdir: repo_path)
  result[:stdout] + result[:stderr]
end

.minitest_name_filter(full_path, line) ⇒ Object

-n /\Atest_name\z/ for the plain minitest runner. Returns [] when no enclosing test can be identified, so the run degrades to the whole file.



142
143
144
145
146
147
# File 'app/services/mbeditor/test_runner_service.rb', line 142

def minitest_name_filter(full_path, line)
  name = test_name_at_line(full_path, line)
  return [] unless name

  ["-n", "/\\A#{Regexp.escape(name)}\\z/"]
end

.parse_minitest_output(raw) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'app/services/mbeditor/test_runner_service.rb', line 219

def parse_minitest_output(raw)
  lines = raw.lines

  # First pass: collect per-test results from verbose output.
  # Verbose format (--verbose): "ClassName#test_name = N.NNN s = [./F/E/S]"
  verbose_results = {}
  lines.each do |line|
    m = line.match(/\A([\w:]+#\w+)\s+=\s+[\d.]+\s+s\s+=\s+([.FES])\s*\z/)
    next unless m

    status = case m[2]
             when "." then "pass"
             when "F" then "fail"
             when "E" then "error"
             when "S" then "skip"
             end
    verbose_results[m[1]] = { name: m[1], status: status, line: nil, message: nil }
  end

  # Second pass: parse failure/error blocks for messages and line numbers.
  # Format: "  1) Failure:\nTestName#method [file:line]:\nmessage"
  failure_entries = []
  lines.each_with_index do |line, idx|
    next unless line.match?(/^\s+\d+\)\s+(Failure|Error):/)

    name_line = lines[idx + 1]
    next unless name_line

    name = name_line.strip.split(" [").first.chomp(":")
    line_num = name_line[/:(\d+)\]/, 1]&.to_i
    msg_lines = []
    (idx + 2...lines.length).each do |j|
      break if lines[j].strip.empty? || lines[j].match?(/^\s+\d+\)\s+/)
      msg_lines << lines[j].strip
    end

    entry = {
      name: name,
      status: line.include?("Error") ? "error" : "fail",
      line: line_num,
      message: msg_lines.join("\n")
    }

    if verbose_results.key?(name)
      verbose_results[name][:line]    = line_num
      verbose_results[name][:message] = msg_lines.join("\n")
    else
      failure_entries << entry
    end
  end

  # Build final tests list: verbose entries first (sorted by name for stability),
  # then any failure entries not already covered by verbose output.
  tests = verbose_results.values + failure_entries

  summary = empty_summary

  # Parse summary line: "X runs, Y assertions, Z failures, W errors, V skips"
  # or "X tests, Y assertions, Z failures, W errors, V skips"
  summary_line = lines.find { |l| l.match?(/\d+ (runs|tests), \d+ assertions/) }
  if summary_line
    nums = summary_line.scan(/\d+/).map(&:to_i)
    summary[:total]   = nums[0] || 0
    summary[:failed]  = nums[2] || 0
    summary[:errored] = nums[3] || 0
    summary[:skipped] = nums[4] || 0
    summary[:passed]  = summary[:total] - summary[:failed] - summary[:errored] - summary[:skipped]
  end

  # Parse timing: "Finished in 0.123456s"
  time_line = lines.find { |l| l.match?(/Finished in [\d.]+s/) }
  if time_line
    summary[:duration] = time_line[/([\d.]+)s/, 1]&.to_f&.round(3)
  end

  [tests, summary]
end

.parse_output(raw, framework) ⇒ Object



179
180
181
182
183
184
185
186
187
188
# File 'app/services/mbeditor/test_runner_service.rb', line 179

def parse_output(raw, framework)
  case framework.to_sym
  when :rspec
    parse_rspec_output(raw)
  when :minitest
    parse_minitest_output(raw)
  else
    [[], empty_summary]
  end
end

.parse_rspec_output(raw) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'app/services/mbeditor/test_runner_service.rb', line 190

def parse_rspec_output(raw)
  # RSpec with --format json embeds JSON in the output
  json_match = raw.match(/(\{.*"summary_line".*\})/m)
  if json_match
    data = JSON.parse(json_match[1])
    summary = {
      total: data.dig("summary", "example_count") || 0,
      passed: (data.dig("summary", "example_count") || 0) - (data.dig("summary", "failure_count") || 0) - (data.dig("summary", "pending_count") || 0),
      failed: data.dig("summary", "failure_count") || 0,
      errored: 0,
      skipped: data.dig("summary", "pending_count") || 0,
      duration: data.dig("summary", "duration")&.round(3)
    }
    tests = (data["examples"] || []).map do |ex|
      {
        name: ex["full_description"] || ex["description"],
        status: ex["status"] == "passed" ? "pass" : (ex["status"] == "pending" ? "skip" : "fail"),
        line: ex.dig("line_number"),
        message: ex.dig("exception", "message")
      }
    end
    [tests, summary]
  else
    parse_minitest_output(raw) # fallback to text parsing
  end
rescue JSON::ParserError
  parse_minitest_output(raw)
end

.resolve_test_file(repo_path, relative_path) ⇒ Object

Given a source file path, resolve it to its matching test/spec file. If the file is already a test/spec file, return it as-is.



45
46
47
48
49
50
# File 'app/services/mbeditor/test_runner_service.rb', line 45

def resolve_test_file(repo_path, relative_path)
  return relative_path if test_file?(relative_path)

  candidates = test_file_candidates(relative_path)
  candidates.find { |c| File.exist?(File.join(repo_path, c)) }
end

.run(repo_path, test_path, framework: nil, command: nil, timeout: 60, line: nil) ⇒ Object

Run the test file at test_path inside repo_path. Returns a Hash:

{
ok:       true/false,
summary:  { total:, passed:, failed:, errored:, skipped:, duration: },
tests:    [{ name:, status:, line:, message: }],
raw:      String   # full stdout+stderr for fallback display
}


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/services/mbeditor/test_runner_service.rb', line 23

def run(repo_path, test_path, framework: nil, command: nil, timeout: 60, line: nil)
  framework = detect_framework(repo_path, test_path) if framework.nil?
  return error_result("Could not detect test framework") unless framework

  cmd = build_command(repo_path, test_path, framework, command, line: line)
  raw = execute_with_timeout(repo_path, cmd, timeout)
  tests, summary = parse_output(raw, framework)
  {
    ok: true,
    framework: framework.to_s,
    summary: summary,
    tests: tests,
    raw: raw
  }
rescue ProcessRunner::TimeoutError
  error_result("Test run timed out after #{timeout} seconds")
rescue StandardError => e
  error_result(e.message)
end

.test_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
56
57
# File 'app/services/mbeditor/test_runner_service.rb', line 52

def test_file?(path)
  path.match?(%r{(^|/)test/.*_test\.rb$}) ||
    path.match?(%r{(^|/)spec/.*_spec\.rb$}) ||
    path.end_with?("_test.rb") ||
    path.end_with?("_spec.rb")
end

.test_file_candidates(relative_path) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'app/services/mbeditor/test_runner_service.rb', line 59

def test_file_candidates(relative_path)
  return [] unless relative_path.end_with?(".rb")

  basename = File.basename(relative_path, ".rb")
  dir_parts = relative_path.split("/")

  candidates = []

  # app/models/user.rb -> test/models/user_test.rb
  if dir_parts[0] == "app" && dir_parts.length > 1
    sub_path = dir_parts[1..].join("/")
    sub_dir = File.dirname(sub_path)
    candidates << File.join("test", sub_dir, "#{basename}_test.rb")
    candidates << File.join("spec", sub_dir, "#{basename}_spec.rb")
  end

  # lib/foo.rb -> test/lib/foo_test.rb or test/foo_test.rb
  if dir_parts[0] == "lib"
    sub_path = dir_parts[1..].join("/")
    sub_dir = File.dirname(sub_path)
    candidates << File.join("test", "lib", sub_dir, "#{basename}_test.rb")
    candidates << File.join("test", sub_dir, "#{basename}_test.rb")
    candidates << File.join("spec", "lib", sub_dir, "#{basename}_spec.rb")
  end

  # Fallback: test/<basename>_test.rb
  candidates << File.join("test", "#{basename}_test.rb")
  candidates << File.join("spec", "#{basename}_spec.rb")

  candidates.uniq
end

.test_name_at_line(full_path, line) ⇒ Object

Name of the test enclosing (or immediately preceding) line. Handles both def test_foo and Rails' test "foo bar" do macro, whose generated method name is "test_foo_bar".



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'app/services/mbeditor/test_runner_service.rb', line 152

def test_name_at_line(full_path, line)
  return nil unless File.file?(full_path)
  return nil if File.size(full_path) > FileOperationService::MAX_FILE_SIZE_BYTES

  lines = File.readlines(full_path, encoding: "UTF-8", invalid: :replace, undef: :replace)
  index = [line - 1, lines.length - 1].min
  return nil if index.negative?

  index.downto(0) do |i|
    text = lines[i]
    if (m = text.match(/^\s*def\s+(test_\w+[?!]?)/))
      return m[1]
    end
    if (m = text.match(/^\s*test\s+(["'])(.+?)\1\s+do\b/))
      return "test_#{m[2].strip.gsub(/\s+/, '_')}"
    end
  end
  nil
rescue StandardError
  nil
end