Skip to content

Commit

Permalink
File handles: Make spec more reliable, and satisfy Rubocop
Browse files Browse the repository at this point in the history
  • Loading branch information
haslo committed Nov 23, 2018
1 parent c90c2e7 commit 2680130
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
4 changes: 1 addition & 3 deletions lib/prawn/images.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,7 @@ def verify_and_read_image(io_or_path)
# String or Pathname
io_or_path = Pathname.new(io_or_path)
raise ArgumentError, "#{io_or_path} not found" unless io_or_path.file?
File.open(io_or_path, 'rb') do |file_io|
file_io.read
end
File.binread(io_or_path)
end

def image_position(w, h, options)
Expand Down
30 changes: 21 additions & 9 deletions spec/prawn/images_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,32 +47,44 @@
file = File.open(filename, 'rb')
_info = pdf.image(file)

expect(file).not_to be_closed
expect(file).to_not be_closed
end

it 'accepts Pathname objects' do
info = pdf.image(Pathname.new(filename))
expect(info.height).to eq(453)
end

it 'closes opened files again after getting Pathname objects (lsof version)' do
if system('lsof -v > /dev/null 2&>1') && system('grep --version > /dev/null 2&>1')
it 'closes opened files again after getting Pathname objects' do
# lsof version
system_has_lsof = system('lsof -v > /dev/null 2>&1')
system_has_grep = system('grep --version > /dev/null 2>&1')
if system_has_lsof && system_has_grep
# linux and macOS will actually run this spec
gc_was_disabled = GC.disable # make sure GC doesn't remove File instance and close file

open_files_before = `lsof -c ruby | grep "#{filename}"`
_info = pdf.image(Pathname.new(filename))
expect(`lsof -c ruby | grep "#{filename}"`).to eq(open_files_before)

GC.enable unless gc_was_disabled
else
# can't test this on every OS
expect(true).to be_truthy
expect(system_has_lsof && system_has_grep).to be_falsy
end
end

it 'closes opened files again after getting Pathname objects (file double version)' do
file_double = double('file double')
expect(file_double).to receive(:read).and_return(File.new(filename).read)
expect(File).to receive(:open).and_yield(file_double)
context 'with File message spy' do
before do
file_path = Pathname.new(filename)
file_content = File.new(filename, 'rb').read
allow(File).to receive(:binread).with(file_path).and_return(file_content)
end

_info = pdf.image(Pathname.new(filename))
it 'closes opened files again after getting Pathname objects' do
_info = pdf.image(Pathname.new(filename))
expect(File).to have_received(:binread)
end
end

context 'setting the length of the bytestream' do
Expand Down

0 comments on commit 2680130

Please sign in to comment.