Skip to content

Commit

Permalink
Defaults: protect against ArgumentError when no HOME
Browse files Browse the repository at this point in the history
  • Loading branch information
olleolleolle committed Dec 13, 2016
1 parent 59e0ed7 commit 625df48
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 6 deletions.
29 changes: 27 additions & 2 deletions lib/chef-api/defaults.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'chef-api/version'
require 'pathname'
require 'json'

module ChefAPI
Expand All @@ -24,8 +25,32 @@ def options
#
# @return [Hash]
def config
path = File.expand_path(ENV['CHEF_API_CONFIG'] || '~/.chef-api')
@config ||= File.exist?(path) ? JSON.parse(File.read(path)) : {}
path = config_path
@config ||= path.exist? ? JSON.parse(path.read) : {}
end

#
# Pathname to configuration file, or a blank Pathname.
#
# @return [Pathname] an expanded Pathname or a non-existent Pathname
def config_path
if result = chef_api_config_path
Pathname(result).expand_path
else
Pathname('')
end
end

#
# String representation of path to configuration file
#
# @return [String, nil] Path to config file, or nil
def chef_api_config_path
ENV['CHEF_API_CONFIG'] || if ENV.key?('HOME')
'~/.chef-api'
else
nil
end
end

#
Expand Down
29 changes: 25 additions & 4 deletions spec/unit/defaults_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

module ChefAPI
describe Defaults do
before(:each) do
subject.instance_variable_set(:@config, nil)
end

context 'without a config file' do
before(:each) do
allow(subject).to receive(:config).and_return(Hash.new)
Expand All @@ -16,15 +20,32 @@ module ChefAPI
end
end

context 'without a config file and no ENV vars to find it' do
around do |example|
old_conf = ENV.delete('CHEF_API_CONFIG')
old_home = ENV.delete('HOME')
example.run
ENV['CHEF_API_CONFIG'] = old_conf
ENV['HOME'] = old_home
end

it 'returns the default without errors' do
expect { subject.config }.not_to raise_error
end

it 'returns the default which is the empty hash' do
expect(subject.config).to eq({})
end
end

context 'with a config file' do
before(:each) do
subject.instance_variable_set(:@config, nil)
allow(File).to receive(:exist?).with(anything()).and_return(true)
allow(File).to receive(:read).and_return("{\n"\
config_content = "{\n"\
"\"CHEF_API_ENDPOINT\": \"test_endpoint\",\n" \
"\"CHEF_API_USER_AGENT\": \"test_user_agent\"\n" \
"}"
)
path = instance_double(Pathname, read: config_content, exist?: true)
allow(subject).to receive(:config_path).and_return(path)
end

it 'returns the overridden value for endpoint' do
Expand Down

0 comments on commit 625df48

Please sign in to comment.