Skip to content

Commit

Permalink
(maint) Raise error when template content is empty or nil
Browse files Browse the repository at this point in the history
  * Throws and error if the content is nil.  This fixes a problem
    when a template cannot be rendered correctly due to some filesytem
    issue.

    This was originally seen when config_defaults.yml had a
      delte: true set for any of the files.

    The error message previously thrown was confusing so this is meant
    to throw a better error message.
  • Loading branch information
logicminds authored and rodjek committed Oct 30, 2019
1 parent 57271d9 commit 5267b8b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/pdk/util/filesystem.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ module PDK
module Util
module Filesystem
def write_file(path, content)
raise ArgumentError unless path.is_a?(String) || path.respond_to?(:to_path)
raise ArgumentError, _('content must be a String') unless content.is_a?(String)
raise ArgumentError, _('path must be a String or Pathname') unless path.is_a?(String) || path.respond_to?(:to_path)

# Harmonize newlines across platforms.
content = content.encode(universal_newline: true)
Expand Down
47 changes: 47 additions & 0 deletions spec/unit/pdk/util/filesystem_spec.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'spec_helper'
require 'pdk/util/filesystem'
require 'stringio'

describe PDK::Util::Filesystem do
describe '.read_file' do
Expand Down Expand Up @@ -46,4 +47,50 @@
end
end
end

describe '.write_file' do
subject(:write_file) { described_class.write_file(path, content) }

let(:dummy_file) { StringIO.new }
let(:path) { nil }

before(:each) do
allow(File).to receive(:open).and_call_original
allow(File).to receive(:open).with(path, 'wb').and_yield(dummy_file)
end

context 'when content is a String' do
let(:content) { 'something' }

context 'and the path is a String' do
let(:path) { File.join('path', 'to', 'my', 'file') }

it 'does not raise an error' do
expect { write_file }.not_to raise_error
end
end

context 'and the path is a Pathname' do
let(:path) { Pathname.new(File.join('path', 'to', 'my', 'file')) }

it 'does not raise an error' do
expect { write_file }.not_to raise_error
end
end

context 'and the path is neither a String nor Pathname' do
it 'raises an ArgumentError' do
expect { write_file }.to raise_error(ArgumentError, %r{String or Pathname})
end
end
end

context 'when content is not a String' do
let(:content) { nil }

it 'raises an ArgumentError' do
expect { write_file }.to raise_error(ArgumentError, %r{content must be a String})
end
end
end
end

0 comments on commit 5267b8b

Please sign in to comment.