debian-mirror-gitlab/spec/rubocop/cop/performance/readlines_each_spec.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

81 lines
2.5 KiB
Ruby
Raw Permalink Normal View History

2020-04-22 19:07:51 +05:30
# frozen_string_literal: true
2022-10-11 01:57:18 +05:30
require 'rubocop_spec_helper'
2020-04-22 19:07:51 +05:30
require_relative '../../../../rubocop/cop/performance/readlines_each'
2021-03-08 18:12:59 +05:30
RSpec.describe RuboCop::Cop::Performance::ReadlinesEach do
2020-04-22 19:07:51 +05:30
let(:message) { 'Avoid `IO.readlines.each`, since it reads contents into memory in full. Use `IO.each_line` or `IO.each` instead.' }
2023-03-04 22:38:38 +05:30
shared_examples_for('class read') do |klass|
2020-04-22 19:07:51 +05:30
context "and it is called as a class method on #{klass}" do
it 'flags it as an offense' do
2021-03-11 19:13:27 +05:30
leading_readline = "#{klass}.readlines(file_path)."
padding = " " * leading_readline.length
node = "#{leading_readline}each { |line| puts line }"
2020-04-22 19:07:51 +05:30
2021-03-11 19:13:27 +05:30
expect_offense(<<~CODE, node: node)
%{node}
#{padding}^^^^ Avoid `IO.readlines.each`, since it reads contents into memory in full. [...]
CODE
2020-04-22 19:07:51 +05:30
end
end
context 'when just using readlines without each' do
it 'does not flag it as an offense' do
expect_no_offenses "contents = #{klass}.readlines(file_path)"
end
end
end
context 'when reading all lines using IO.readlines.each' do
%w(IO File).each do |klass|
2023-03-04 22:38:38 +05:30
it_behaves_like('class read', klass)
2020-04-22 19:07:51 +05:30
end
context 'and it is called as an instance method on a return value' do
it 'flags it as an offense' do
expect_offense <<~SOURCE
get_file.readlines.each { |line| puts line }
^^^^ #{message}
SOURCE
end
end
context 'and it is called as an instance method on an assigned variable' do
it 'flags it as an offense' do
expect_offense <<~SOURCE
file = File.new(path)
file.readlines.each { |line| puts line }
^^^^ #{message}
SOURCE
end
end
context 'and it is called as an instance method on a new object' do
it 'flags it as an offense' do
expect_offense <<~SOURCE
File.new(path).readlines.each { |line| puts line }
^^^^ #{message}
SOURCE
end
end
it 'autocorrects `readlines.each` to `each_line`' do
2021-03-11 19:13:27 +05:30
expect_offense(<<~CODE)
obj.readlines.each { |line| line }
^^^^ Avoid `IO.readlines.each`, since it reads contents into memory in full. [...]
CODE
expect_correction(<<~CODE)
obj.each_line { |line| line }
CODE
2020-04-22 19:07:51 +05:30
end
end
context 'when just using readlines without each' do
it 'does not flag it as an offense' do
expect_no_offenses 'contents = my_file.readlines'
end
end
end