Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support dot-notation when retrieving facts in facter_impl #46

Merged
merged 1 commit into from
Mar 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/rspec-puppet/facter_impl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ def initialize
end

def value(fact_name)
@facts[fact_name.to_s]
begin
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm so used to Ruby 2.5+ where you can write:

def
  @facts.dig(*fact_name.to_s.split('.'))
rescue TypeError
  nil
end

But this gem doesn't declare to be Ruby 2.5+ so I think your current code is fine.

@facts.dig(*fact_name.to_s.split('.'))
rescue TypeError
nil
end
end

def clear
Expand Down
24 changes: 24 additions & 0 deletions spec/unit/facter_impl_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'int_fact' => 3,
'true_fact' => true,
'false_fact' => false,
'os' => { 'name' => 'my_os', 'release' => { 'major' => '42' } }
}
end

Expand All @@ -19,6 +20,7 @@
facter_impl.add(:int_fact) { setcode { 3 } }
facter_impl.add(:true_fact) { setcode { true } }
facter_impl.add(:false_fact) { setcode { false } }
facter_impl.add(:os) { setcode { { 'name' => 'my_os', 'release' => { 'major' => '42' }} } }
end

describe 'noop methods' do
Expand Down Expand Up @@ -49,6 +51,28 @@
it 'retrieves a fact of type FalseClass' do
expect(facter_impl.value(:false_fact)).to eq(false)
end

context 'when using dot-notation' do
it 'retrieves a child fact using dot-notation' do
expect(facter_impl.value('os.name')).to eq('my_os')
end

it 'retrieves a hash child fact using dot-notation' do
expect(facter_impl.value('os.release')).to eq({ 'major' => '42' })
end

it 'retrieves a deeply nested child fact using dot-notation' do
expect(facter_impl.value('os.release.major')).to eq('42')
end

it 'returns nil if a child fact is missing' do
expect(facter_impl.value('os.release.unknown_subkey')).to eq(nil)
end

it 'returns nil if trying to lookup into a string' do
expect(facter_impl.value('os.name.foo')).to eq(nil)
end
end
end

describe '#to_hash' do
Expand Down