Skip to content

Commit

Permalink
Merge pull request #294 from rodjek/sdk-369
Browse files Browse the repository at this point in the history
(PDK-369) Improve error context for pdk test unit failures
  • Loading branch information
DavidS committed Sep 13, 2017
2 parents 52f5ecf + ba96a75 commit 6a045e7
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 1 deletion.
33 changes: 32 additions & 1 deletion lib/pdk/report/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,20 @@ def to_text
location = nil if location.empty?

# TODO: maybe add trace
[severity, source, location, message].compact.join(': ')
header = [severity, source, location, message].compact.join(': ')
if source == 'rspec'
result = [header, " #{test}"]
context = context_lines
unless context.nil?
result << ' Failure/Error:'
result.concat(context)
result << "\n"
end

result.compact.join("\n")
else
header
end
end

# Renders the event as a JUnit XML testcase.
Expand Down Expand Up @@ -302,6 +315,24 @@ def sanitise_trace(value)
(line =~ %r{/gems/}) || (line =~ %r{bin/rspec:})
end
end

# Extract contextual information for the event from the file that it
# references.
#
# @param max_num_lines [Integer] The maximum number of lines to return.
#
# @return [Array] Array of lines from the file, centred on the line
# number of the event.
def context_lines(max_num_lines = 5)
return if file.nil? || line.nil?

file_content = File.read(file).split("\n")
delta = (max_num_lines - 1) / 2
min = [0, (line - 1) - delta].max
max = [(line - 1) + delta, file_content.length].min

file_content[min..max].map { |r| " #{r}" }
end
end
end
end
44 changes: 44 additions & 0 deletions spec/unit/pdk/report/event_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,50 @@
expect(text_event).to match(%r{testfile\.rb:123:456})
end
end

context 'it includes a snippet of the file for rspec events' do
let(:data) do
{
line: 4,
source: 'rspec',
message: 'test message',
severity: 'failure',
test: 'spec description',
state: :failure,
}
end

let(:file_content) do
[
'line 1',
'line 2',
'line 3',
'line 4',
'line 5',
].join("\n")
end

let(:expected_text) do
<<-END.gsub(%r{^ {12}}, '')
failure: rspec: testfile.rb:4: test message
spec description
Failure/Error:
line 2
line 3
line 4
line 5
END
end

before(:each) do
allow(File).to receive(:read).with('testfile.rb').and_return(file_content)
end

it 'renders the event with context' do
expect(text_event).to eq(expected_text)
end
end
end

context 'and a severity is provided' do
Expand Down

0 comments on commit 6a045e7

Please sign in to comment.