2021-01-22 01:31:18 +00:00
|
|
|
require "../../../spec_helper"
|
|
|
|
|
|
|
|
module Ameba::Rule::Performance
|
|
|
|
subject = AnyInsteadOfEmpty.new
|
|
|
|
|
|
|
|
describe AnyInsteadOfEmpty do
|
|
|
|
it "passes if there is no potential performance improvements" do
|
2021-11-16 21:30:33 +00:00
|
|
|
expect_no_issues subject, <<-CRYSTAL
|
2021-01-22 01:31:18 +00:00
|
|
|
[1, 2, 3].any?(&.zero?)
|
|
|
|
[1, 2, 3].any?(String)
|
|
|
|
[1, 2, 3].any?(1..3)
|
|
|
|
[1, 2, 3].any? { |e| e > 1 }
|
2021-11-16 21:30:33 +00:00
|
|
|
CRYSTAL
|
2021-01-22 01:31:18 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
it "reports if there is any? call without a block nor argument" do
|
2021-11-16 21:30:33 +00:00
|
|
|
source = expect_issue subject, <<-CRYSTAL
|
2021-01-22 01:31:18 +00:00
|
|
|
[1, 2, 3].any?
|
2021-11-16 21:30:33 +00:00
|
|
|
# ^^^^^^^^^^^^ error: Use `!{...}.empty?` instead of `{...}.any?`
|
|
|
|
CRYSTAL
|
|
|
|
|
|
|
|
expect_correction source, <<-CRYSTAL
|
|
|
|
![1, 2, 3].empty?
|
|
|
|
CRYSTAL
|
2021-01-22 01:31:18 +00:00
|
|
|
end
|
|
|
|
|
2021-04-15 14:26:49 +00:00
|
|
|
it "does not report if source is a spec" do
|
2021-11-16 21:30:33 +00:00
|
|
|
expect_no_issues subject, <<-CRYSTAL, "source_spec.cr"
|
2021-04-15 14:26:49 +00:00
|
|
|
[1, 2, 3].any?
|
2021-11-16 21:30:33 +00:00
|
|
|
CRYSTAL
|
2021-04-15 14:26:49 +00:00
|
|
|
end
|
|
|
|
|
2021-01-22 01:31:18 +00:00
|
|
|
context "macro" do
|
|
|
|
it "reports in macro scope" do
|
2021-11-16 21:30:33 +00:00
|
|
|
source = expect_issue subject, <<-CRYSTAL
|
2021-01-22 01:31:18 +00:00
|
|
|
{{ [1, 2, 3].any? }}
|
2021-11-16 21:30:33 +00:00
|
|
|
# ^^^^^^^^^^^^^^ error: Use `!{...}.empty?` instead of `{...}.any?`
|
|
|
|
CRYSTAL
|
|
|
|
|
|
|
|
expect_correction source, <<-CRYSTAL
|
|
|
|
{{ ![1, 2, 3].empty? }}
|
|
|
|
CRYSTAL
|
2021-01-22 01:31:18 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
it "reports rule, pos and message" do
|
|
|
|
source = Source.new path: "source.cr", code: %(
|
|
|
|
[1, 2, 3].any?
|
|
|
|
)
|
|
|
|
subject.catch(source).should_not be_valid
|
|
|
|
issue = source.issues.first
|
|
|
|
|
|
|
|
issue.rule.should_not be_nil
|
2021-11-16 21:30:33 +00:00
|
|
|
issue.location.to_s.should eq "source.cr:1:1"
|
|
|
|
issue.end_location.to_s.should eq "source.cr:1:14"
|
2021-01-22 01:31:18 +00:00
|
|
|
issue.message.should eq "Use `!{...}.empty?` instead of `{...}.any?`"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|