Skip to content

Commit

Permalink
Capture test output for Minitest reporter
Browse files Browse the repository at this point in the history
  • Loading branch information
andyw8 committed Mar 10, 2025
1 parent aba9d60 commit 4d7c5ea
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 1 deletion.
3 changes: 3 additions & 0 deletions lib/ruby_lsp/ruby_lsp_reporter_plugin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ class RubyLspReporter < ::Minitest::AbstractReporter
class << self
#: (Hash[untyped, untyped]) -> void
def minitest_plugin_init(_options)
# We wrap the default output stream so that we can capture anything written to stdout and emit it as part of
# the JSON event stream.
$> = RubyLsp::TestReporter::IOWrapper.new($stdout)
Minitest.reporter.reporters = [RubyLspReporter.new]
end
end
Expand Down
28 changes: 28 additions & 0 deletions lib/ruby_lsp/test_reporter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# frozen_string_literal: true

require "json"
require "delegate"

$stdout.binmode
$stdout.sync = true
Expand Down Expand Up @@ -59,6 +60,14 @@ def record_error(id:, message:, uri:)
send_message("error", params)
end

#: (message: String) -> void
def write_stdout(message:)
params = {
message: message,
}
send_message("write_stdout", params)
end

private

#: (method_name: String?, params: Hash[String, untyped]) -> void
Expand All @@ -67,5 +76,24 @@ def send_message(method_name, params)
$stdout.write("Content-Length: #{json_message.bytesize}\r\n\r\n#{json_message}")
end
end

class IOWrapper < SimpleDelegator
#: (Array[String]) -> void
def puts(*args)
args.each { |arg| log("#{arg}\n") }
end

#: (Array[String]) -> void
def print(*args)
args.each { |arg| log(arg.to_s) }
end

private

#: (String) -> void
def log(message)
TestReporter.write_stdout(message: message)
end
end
end
end
4 changes: 4 additions & 0 deletions test/fixtures/minitest_example.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@ def test_that_is_pending
def test_that_raises
raise "oops"
end

def test_with_output
$stdout.puts "hello from stdout"
end
end
22 changes: 21 additions & 1 deletion test/minitest_test_runner_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,28 @@ def test_minitest_output
"uri" => uri,
},
},
{
"method" => "start",
"params" => {
"id" => "SampleTest#test_with_output",
"uri" => uri,
},
},
{
"method" => "write_stdout",
"params" => {
"message" => "hello from stdout\n",
},
},
{
"method" => "pass",
"params" => {
"id" => "SampleTest#test_with_output",
"uri" => uri,
},
},
]
assert_equal(8, actual.size)
assert_equal(2 + 2 + 2 + 2 + 3, actual.size)
assert_equal(expected, actual)
end

Expand Down

0 comments on commit 4d7c5ea

Please sign in to comment.