diff --git a/acceptance/tests/facter_flush.rb b/acceptance/tests/facter_flush.rb new file mode 100644 index 0000000000..3946ddc2f1 --- /dev/null +++ b/acceptance/tests/facter_flush.rb @@ -0,0 +1,52 @@ +test_name 'facter should flush fact values' do + tag 'risk:high' + + fact_content1 = <<-EOM + require 'facter' + + Facter.add(:fact1) do + 'this should be flushed' + end + + Facter.flush + + puts "Fact1: \#\{Facter.value(:fact1)\}" + EOM + + fact_content2 = <<-EOM + require 'facter' + + Facter.add(:fact2) do + on_flush do + puts 'before flush' + end + end + + Facter.flush + EOM + + agents.each do |agent| + fact_dir = agent.tmpdir('test_scripts') + script_path1 = File.join(fact_dir, 'flush_test1.rb') + script_path2 = File.join(fact_dir, 'flush_test2.rb') + create_remote_file(agent, script_path1, fact_content1) + create_remote_file(agent, script_path2, fact_content2) + + teardown do + agent.rm_rf(script_path1) + agent.rm_rf(script_path2) + end + + step 'fact value has been flushed' do + on(agent, "#{ruby_command(agent)} #{script_path1}") do |ruby_result| + assert_equal('Fact1: ', ruby_result.stdout.chomp) + end + end + + step 'prints on_flush block gets called' do + on(agent, "#{ruby_command(agent)} #{script_path2}") do |ruby_result| + assert_equal('before flush', ruby_result.stdout.chomp) + end + end + end +end diff --git a/lib/facter.rb b/lib/facter.rb index 16455356d8..3923ee5874 100644 --- a/lib/facter.rb +++ b/lib/facter.rb @@ -227,6 +227,18 @@ def reset nil end + # Flushes cached values for all facts. This does not cause code to be + # reloaded; it only clears the cached results. + # + # @return [void] + # + # @api public + def flush + LegacyFacter.flush + SessionCache.invalidate_all_caches + nil + end + # Loads all facts # # @return [nil] diff --git a/spec/facter/facter_spec.rb b/spec/facter/facter_spec.rb index 5f12946294..db588d6be8 100644 --- a/spec/facter/facter_spec.rb +++ b/spec/facter/facter_spec.rb @@ -403,6 +403,24 @@ def mock_collection(method, os_name = nil, error = nil) end end + describe '#flush' do + it 'sends call to LegacyFacter' do + allow(LegacyFacter).to receive(:flush) + + Facter.flush + + expect(LegacyFacter).to have_received(:flush).once + end + + it 'invalidates core cache' do + allow(Facter::SessionCache).to receive(:invalidate_all_caches) + + Facter.flush + + expect(Facter::SessionCache).to have_received(:invalidate_all_caches) + end + end + describe '#search' do it 'sends call to Facter::Options' do allow(Facter::Options).to receive(:[]=)