Merge pull request #246 from FnControlOption/replacements

Allow named replacements in expect_issue
This commit is contained in:
Vitalii Elenhaupt 2021-10-25 21:40:40 +03:00 committed by GitHub
commit dafae6ca77
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 6 deletions

View File

@ -5,9 +5,12 @@ module Ameba
private def it_transforms(number, expected)
it "transforms large number #{number}" do
s = Source.new number
Rule::Style::LargeNumbers.new.catch(s).should_not be_valid
s.issues.first.message.should contain expected
rule = Rule::Style::LargeNumbers.new
expect_issue rule, <<-CRYSTAL, number: number
number = %{number}
# ^{number} error: Large numbers should be written with underscores: #{expected}
CRYSTAL
end
end
@ -118,7 +121,7 @@ module Ameba
issue = s.issues.first
issue.rule.should_not be_nil
issue.location.to_s.should eq "source.cr:1:1"
issue.end_location.should be_nil
issue.end_location.to_s.should eq "source.cr:1:7"
issue.message.should match /1_200_000/
end

View File

@ -42,7 +42,13 @@ module Ameba::Rule::Style
parsed = parse_number token.raw
if allowed?(*parsed) && (expected = underscored *parsed) != token.raw
issue_for token, MSG % expected
location = token.location
end_location = Crystal::Location.new(
location.filename,
location.line_number,
location.column_number + token.raw.size - 1
)
issue_for location, end_location, MSG % expected
end
end
end

View File

@ -53,8 +53,10 @@ module Ameba::Spec::ExpectIssue
normalize = true,
*,
file = __FILE__,
line = __LINE__)
line = __LINE__,
**replacements)
annotated_code = normalize_code(annotated_code) if normalize
annotated_code = format_issue(annotated_code, **replacements)
expected_annotations = AnnotatedSource.parse(annotated_code)
lines = expected_annotations.lines
code = lines.join('\n')
@ -105,4 +107,14 @@ module Ameba::Spec::ExpectIssue
end
AnnotatedSource.new(lines, source.issues)
end
private def format_issue(code, **replacements)
replacements.each do |keyword, value|
value = value.to_s
code = code.gsub("%{#{keyword}}", value)
code = code.gsub("^{#{keyword}}", "^" * value.size)
code = code.gsub("_{#{keyword}}", " " * value.size)
end
code
end
end