repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/terminus_selector_spec.rb | spec/unit/file_serving/terminus_selector_spec.rb | require 'spec_helper'
require 'puppet/file_serving/terminus_selector'
describe Puppet::FileServing::TerminusSelector do
class TestSelector
include Puppet::FileServing::TerminusSelector
end
def create_request(key)
Puppet::Indirector::Request.new(:indirection_name, :find, key, nil, {node: 'whatever'})
end
subject { TestSelector.new }
describe "when being used to select termini" do
it "should return :file if the request key is fully qualified" do
request = create_request(File.expand_path('/foo'))
expect(subject.select(request)).to eq(:file)
end
it "should return :file_server if the request key is relative" do
request = create_request('modules/my_module/path/to_file')
expect(subject.select(request)).to eq(:file_server)
end
it "should return :file if the URI protocol is set to 'file'" do
request = create_request(Puppet::Util.path_to_uri(File.expand_path("/foo")).to_s)
expect(subject.select(request)).to eq(:file)
end
it "should return :http if the URI protocol is set to 'http'" do
request = create_request("http://www.example.com")
expect(subject.select(request)).to eq(:http)
end
it "should return :http if the URI protocol is set to 'https'" do
request = create_request("https://www.example.com")
expect(subject.select(request)).to eq(:http)
end
it "should return :http if the path starts with a double slash" do
request = create_request("https://www.example.com//index.html")
expect(subject.select(request)).to eq(:http)
end
it "should fail when a protocol other than :puppet, :http(s) or :file is used" do
request = create_request("ftp://ftp.example.com")
expect {
subject.select(request)
}.to raise_error(ArgumentError, /URI protocol 'ftp' is not currently supported for file serving/)
end
describe "and the protocol is 'puppet'" do
it "should choose :rest when a server is specified" do
request = create_request("puppet://puppetserver.example.com")
expect(subject.select(request)).to eq(:rest)
end
# This is so a given file location works when bootstrapping with no server.
it "should choose :rest when default_file_terminus is rest" do
Puppet[:server] = 'localhost'
request = create_request("puppet:///plugins")
expect(subject.select(request)).to eq(:rest)
end
it "should choose :file_server when default_file_terminus is file_server and no server is specified on the request" do
Puppet[:default_file_terminus] = 'file_server'
request = create_request("puppet:///plugins")
expect(subject.select(request)).to eq(:file_server)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount_spec.rb | spec/unit/file_serving/mount_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount'
describe Puppet::FileServing::Mount do
it "should use 'mount[$name]' as its string form" do
expect(Puppet::FileServing::Mount.new("foo").to_s).to eq("mount[foo]")
end
end
describe Puppet::FileServing::Mount, " when initializing" do
it "should fail on non-alphanumeric name" do
expect { Puppet::FileServing::Mount.new("non alpha") }.to raise_error(ArgumentError)
end
it "should allow dashes in its name" do
expect(Puppet::FileServing::Mount.new("non-alpha").name).to eq("non-alpha")
end
end
describe Puppet::FileServing::Mount, " when finding files" do
it "should fail" do
expect { Puppet::FileServing::Mount.new("test").find("foo", :one => "two") }.to raise_error(NotImplementedError)
end
end
describe Puppet::FileServing::Mount, " when searching for files" do
it "should fail" do
expect { Puppet::FileServing::Mount.new("test").search("foo", :one => "two") }.to raise_error(NotImplementedError)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/configuration_spec.rb | spec/unit/file_serving/configuration_spec.rb | require 'spec_helper'
require 'puppet/file_serving/configuration'
describe Puppet::FileServing::Configuration do
include PuppetSpec::Files
before :each do
@path = make_absolute("/path/to/configuration/file.conf")
Puppet[:trace] = false
Puppet[:fileserverconfig] = @path
end
after :each do
Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil)
end
it "should make :new a private method" do
expect { Puppet::FileServing::Configuration.new }.to raise_error(NoMethodError, /private method `new' called/)
end
it "should return the same configuration each time 'configuration' is called" do
expect(Puppet::FileServing::Configuration.configuration).to equal(Puppet::FileServing::Configuration.configuration)
end
describe "when initializing" do
it "should work without a configuration file" do
allow(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(false)
expect { Puppet::FileServing::Configuration.configuration }.to_not raise_error
end
it "should parse the configuration file if present" do
allow(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true)
@parser = double('parser')
expect(@parser).to receive(:parse).and_return({})
allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(@parser)
Puppet::FileServing::Configuration.configuration
end
it "should determine the path to the configuration file from the Puppet settings" do
Puppet::FileServing::Configuration.configuration
end
end
describe "when parsing the configuration file" do
before do
allow(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true)
@parser = double('parser')
allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(@parser)
end
it "should set the mount list to the results of parsing" do
expect(@parser).to receive(:parse).and_return("one" => double("mount"))
config = Puppet::FileServing::Configuration.configuration
expect(config.mounted?("one")).to be_truthy
end
it "should not raise exceptions" do
expect(@parser).to receive(:parse).and_raise(ArgumentError)
expect { Puppet::FileServing::Configuration.configuration }.to_not raise_error
end
it "should replace the existing mount list with the results of reparsing" do
expect(@parser).to receive(:parse).and_return("one" => double("mount"))
config = Puppet::FileServing::Configuration.configuration
expect(config.mounted?("one")).to be_truthy
# Now parse again
expect(@parser).to receive(:parse).and_return("two" => double('other'))
config.send(:readconfig, false)
expect(config.mounted?("one")).to be_falsey
expect(config.mounted?("two")).to be_truthy
end
it "should not replace the mount list until the file is entirely parsed successfully" do
expect(@parser).to receive(:parse).and_return("one" => double("mount"))
expect(@parser).to receive(:parse).and_raise(ArgumentError)
config = Puppet::FileServing::Configuration.configuration
# Now parse again, so the exception gets thrown
config.send(:readconfig, false)
expect(config.mounted?("one")).to be_truthy
end
it "should add modules, plugins, scripts, and tasks mounts even if the file does not exist" do
expect(Puppet::FileSystem).to receive(:exist?).and_return(false) # the file doesn't exist
config = Puppet::FileServing::Configuration.configuration
expect(config.mounted?("modules")).to be_truthy
expect(config.mounted?("plugins")).to be_truthy
expect(config.mounted?("scripts")).to be_truthy
expect(config.mounted?("tasks")).to be_truthy
end
it "should allow all access to modules, plugins, scripts, and tasks if no fileserver.conf exists" do
expect(Puppet::FileSystem).to receive(:exist?).and_return(false) # the file doesn't exist
modules = double('modules')
allow(Puppet::FileServing::Mount::Modules).to receive(:new).and_return(modules)
plugins = double('plugins')
allow(Puppet::FileServing::Mount::Plugins).to receive(:new).and_return(plugins)
tasks = double('tasks')
allow(Puppet::FileServing::Mount::Tasks).to receive(:new).and_return(tasks)
scripts = double('scripts')
allow(Puppet::FileServing::Mount::Scripts).to receive(:new).and_return(scripts)
Puppet::FileServing::Configuration.configuration
end
it "should not allow access from all to modules, plugins, scripts, and tasks if the fileserver.conf provided some rules" do
expect(Puppet::FileSystem).to receive(:exist?).and_return(false) # the file doesn't exist
modules = double('modules')
allow(Puppet::FileServing::Mount::Modules).to receive(:new).and_return(modules)
plugins = double('plugins')
allow(Puppet::FileServing::Mount::Plugins).to receive(:new).and_return(plugins)
tasks = double('tasks')
allow(Puppet::FileServing::Mount::Tasks).to receive(:new).and_return(tasks)
scripts = double('scripts', :empty? => false)
allow(Puppet::FileServing::Mount::Scripts).to receive(:new).and_return(scripts)
Puppet::FileServing::Configuration.configuration
end
it "should add modules, plugins, scripts, and tasks mounts even if they are not returned by the parser" do
expect(@parser).to receive(:parse).and_return("one" => double("mount"))
expect(Puppet::FileSystem).to receive(:exist?).and_return(true) # the file doesn't exist
config = Puppet::FileServing::Configuration.configuration
expect(config.mounted?("modules")).to be_truthy
expect(config.mounted?("plugins")).to be_truthy
expect(config.mounted?("scripts")).to be_truthy
expect(config.mounted?("tasks")).to be_truthy
end
end
describe "when finding the specified mount" do
it "should choose the named mount if one exists" do
config = Puppet::FileServing::Configuration.configuration
expect(config).to receive(:mounts).and_return("one" => "foo")
expect(config.find_mount("one", double('env'))).to eq("foo")
end
it "should return nil if there is no such named mount" do
config = Puppet::FileServing::Configuration.configuration
env = double('environment')
mount = double('mount')
allow(config).to receive(:mounts).and_return("modules" => mount)
expect(config.find_mount("foo", env)).to be_nil
end
end
describe "#split_path" do
let(:config) { Puppet::FileServing::Configuration.configuration }
let(:request) { double('request', :key => "foo/bar/baz", :options => {}, :node => nil, :environment => double("env")) }
before do
allow(config).to receive(:find_mount)
end
it "should reread the configuration" do
expect(config).to receive(:readconfig)
config.split_path(request)
end
it "should treat the first field of the URI path as the mount name" do
expect(config).to receive(:find_mount).with("foo", anything)
config.split_path(request)
end
it "should fail if the mount name is not alpha-numeric" do
expect(request).to receive(:key).and_return("foo&bar/asdf")
expect { config.split_path(request) }.to raise_error(ArgumentError)
end
it "should support dashes in the mount name" do
expect(request).to receive(:key).and_return("foo-bar/asdf")
expect { config.split_path(request) }.to_not raise_error
end
it "should use the mount name and environment to find the mount" do
expect(config).to receive(:find_mount).with("foo", request.environment)
allow(request).to receive(:node).and_return("mynode")
config.split_path(request)
end
it "should return nil if the mount cannot be found" do
expect(config).to receive(:find_mount).and_return(nil)
expect(config.split_path(request)).to be_nil
end
it "should return the mount and the relative path if the mount is found" do
mount = double('mount', :name => "foo")
expect(config).to receive(:find_mount).and_return(mount)
expect(config.split_path(request)).to eq([mount, "bar/baz"])
end
it "should remove any double slashes" do
allow(request).to receive(:key).and_return("foo/bar//baz")
mount = double('mount', :name => "foo")
expect(config).to receive(:find_mount).and_return(mount)
expect(config.split_path(request)).to eq([mount, "bar/baz"])
end
it "should fail if the path contains .." do
allow(request).to receive(:key).and_return('module/foo/../../bar')
expect do
config.split_path(request)
end.to raise_error(ArgumentError, /Invalid relative path/)
end
it "should return the relative path as nil if it is an empty string" do
expect(request).to receive(:key).and_return("foo")
mount = double('mount', :name => "foo")
expect(config).to receive(:find_mount).and_return(mount)
expect(config.split_path(request)).to eq([mount, nil])
end
it "should add 'modules/' to the relative path if the modules mount is used but not specified, for backward compatibility" do
expect(request).to receive(:key).and_return("foo/bar")
mount = double('mount', :name => "modules")
expect(config).to receive(:find_mount).and_return(mount)
expect(config.split_path(request)).to eq([mount, "foo/bar"])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/content_spec.rb | spec/unit/file_serving/content_spec.rb | require 'spec_helper'
require 'puppet/file_serving/content'
describe Puppet::FileServing::Content do
let(:path) { File.expand_path('/path') }
it "should be a subclass of Base" do
expect(Puppet::FileServing::Content.superclass).to equal(Puppet::FileServing::Base)
end
it "should indirect file_content" do
expect(Puppet::FileServing::Content.indirection.name).to eq(:file_content)
end
it "should only support the binary format" do
expect(Puppet::FileServing::Content.supported_formats).to eq([:binary])
end
it "should have a method for collecting its attributes" do
expect(Puppet::FileServing::Content.new(path)).to respond_to(:collect)
end
it "should not retrieve and store its contents when its attributes are collected" do
content = Puppet::FileServing::Content.new(path)
expect(File).not_to receive(:read).with(path)
content.collect
expect(content.instance_variable_get("@content")).to be_nil
end
it "should have a method for setting its content" do
content = Puppet::FileServing::Content.new(path)
expect(content).to respond_to(:content=)
end
it "should make content available when set externally" do
content = Puppet::FileServing::Content.new(path)
content.content = "foo/bar"
expect(content.content).to eq("foo/bar")
end
it "should be able to create a content instance from binary file contents" do
expect(Puppet::FileServing::Content).to respond_to(:from_binary)
end
it "should create an instance with a fake file name and correct content when converting from binary" do
instance = double('instance')
expect(Puppet::FileServing::Content).to receive(:new).with("/this/is/a/fake/path").and_return(instance)
expect(instance).to receive(:content=).with("foo/bar")
expect(Puppet::FileServing::Content.from_binary("foo/bar")).to equal(instance)
end
it "should return an opened File when converted to binary" do
content = Puppet::FileServing::Content.new(path)
expect(File).to receive(:new).with(path, "rb").and_return(:file)
expect(content.to_binary).to eq(:file)
end
end
describe Puppet::FileServing::Content, "when returning the contents" do
let(:path) { File.expand_path('/my/path') }
let(:content) { Puppet::FileServing::Content.new(path, :links => :follow) }
it "should fail if the file is a symlink and links are set to :manage" do
content.links = :manage
expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(double("stat", :ftype => "symlink"))
expect { content.content }.to raise_error(ArgumentError)
end
it "should fail if a path is not set" do
expect { content.content }.to raise_error(Errno::ENOENT)
end
it "should raise Errno::ENOENT if the file is absent" do
content.path = File.expand_path("/there/is/absolutely/no/chance/that/this/path/exists")
expect { content.content }.to raise_error(Errno::ENOENT)
end
it "should return the contents of the path if the file exists" do
expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(double('stat', :ftype => 'file'))
expect(Puppet::FileSystem).to receive(:binread).with(path).and_return(:mycontent)
expect(content.content).to eq(:mycontent)
end
it "should cache the returned contents" do
expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(double('stat', :ftype => 'file'))
expect(Puppet::FileSystem).to receive(:binread).with(path).and_return(:mycontent)
content.content
# The second run would throw a failure if the content weren't being cached.
content.content
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/http_metadata_spec.rb | spec/unit/file_serving/http_metadata_spec.rb | require 'spec_helper'
require 'puppet/file_serving/http_metadata'
require 'matchers/json'
require 'net/http'
require 'digest'
describe Puppet::FileServing::HttpMetadata do
let(:foobar) { File.expand_path('/foo/bar') }
it "should be a subclass of Metadata" do
expect( described_class.superclass ).to be Puppet::FileServing::Metadata
end
describe "when initializing" do
let(:http_response) { Net::HTTPOK.new(1.0, '200', 'OK') }
it "can be instantiated from a HTTP response object" do
expect( described_class.new(http_response) ).to_not be_nil
end
it "represents a plain file" do
expect( described_class.new(http_response).ftype ).to eq 'file'
end
it "carries no information on owner, group and mode" do
metadata = described_class.new(http_response)
expect( metadata.owner ).to be_nil
expect( metadata.group ).to be_nil
expect( metadata.mode ).to be_nil
end
it "skips md5 checksum type in collect on FIPS enabled platforms" do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
http_response['X-Checksum-Md5'] = 'c58989e9740a748de4f5054286faf99b'
metadata = described_class.new(http_response)
metadata.collect
expect( metadata.checksum_type ).to eq :mtime
end
context "with no Last-Modified or Content-MD5 header from the server" do
it "should use :mtime as the checksum type, based on current time" do
# Stringifying Time.now does some rounding; do so here so we don't end up with a time
# that's greater than the stringified version returned by collect.
time = Time.parse(Time.now.to_s)
metadata = described_class.new(http_response)
metadata.collect
expect( metadata.checksum_type ).to eq :mtime
checksum = metadata.checksum
expect( checksum[0...7] ).to eq '{mtime}'
expect( Time.parse(checksum[7..-1]) ).to be >= time
end
end
context "with a Last-Modified header from the server" do
let(:time) { Time.now.utc }
it "should use :mtime as the checksum type, based on Last-Modified" do
# HTTP uses "GMT" not "UTC"
http_response.add_field('last-modified', time.strftime("%a, %d %b %Y %T GMT"))
metadata = described_class.new(http_response)
metadata.collect
expect( metadata.checksum_type ).to eq :mtime
expect( metadata.checksum ).to eq "{mtime}#{time.to_time.utc}"
end
end
context "with a Content-MD5 header being received" do
let(:input) { Time.now.to_s }
let(:base64) { Digest::MD5.new.base64digest input }
let(:hex) { Digest::MD5.new.hexdigest input }
it "should use the md5 checksum" do
http_response.add_field('content-md5', base64)
metadata = described_class.new(http_response)
metadata.collect
expect( metadata.checksum_type ).to eq :md5
expect( metadata.checksum ).to eq "{md5}#{hex}"
end
end
context "with X-Checksum-Md5" do
let(:md5) { "c58989e9740a748de4f5054286faf99b" }
it "should use the md5 checksum" do
http_response.add_field('X-Checksum-Md5', md5)
metadata = described_class.new(http_response)
metadata.collect
expect( metadata.checksum_type ).to eq :md5
expect( metadata.checksum ).to eq "{md5}#{md5}"
end
end
context "with X-Checksum-Sha1" do
let(:sha1) { "01e4d15746f4274b84d740a93e04b9fd2882e3ea" }
it "should use the SHA1 checksum" do
http_response.add_field('X-Checksum-Sha1', sha1)
metadata = described_class.new(http_response)
metadata.collect
expect( metadata.checksum_type ).to eq :sha1
expect( metadata.checksum ).to eq "{sha1}#{sha1}"
end
end
context "with X-Checksum-Sha256" do
let(:sha256) { "a3eda98259c30e1e75039c2123670c18105e1c46efb672e42ca0e4cbe77b002a" }
it "should use the SHA256 checksum" do
http_response.add_field('X-Checksum-Sha256', sha256)
metadata = described_class.new(http_response)
metadata.collect
expect( metadata.checksum_type ).to eq :sha256
expect( metadata.checksum ).to eq "{sha256}#{sha256}"
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/terminus_helper_spec.rb | spec/unit/file_serving/terminus_helper_spec.rb | require 'spec_helper'
require 'puppet/file_serving/terminus_helper'
class Puppet::FileServing::TestHelper
include Puppet::FileServing::TerminusHelper
attr_reader :model
def initialize(model)
@model = model
end
end
describe Puppet::FileServing::TerminusHelper do
before do
@model = double('model')
@helper = Puppet::FileServing::TestHelper.new(@model)
@request = double('request', :key => "url", :options => {})
@fileset = double('fileset', :files => [], :path => "/my/file")
allow(Puppet::FileServing::Fileset).to receive(:new).with("/my/file", {}).and_return(@fileset)
end
it "should find a file with absolute path" do
file = double('file', :collect => nil)
expect(file).to receive(:collect).with(no_args)
expect(@model).to receive(:new).with("/my/file", {:relative_path => nil}).and_return(file)
@helper.path2instance(@request, "/my/file")
end
it "should pass through links, checksum_type, and source_permissions" do
file = double('file', :checksum_type= => nil, :links= => nil, :collect => nil)
[[:checksum_type, :sha256], [:links, true], [:source_permissions, :use]].each {|k, v|
expect(file).to receive(k.to_s+'=').with(v)
@request.options[k] = v
}
expect(file).to receive(:collect)
expect(@model).to receive(:new).with("/my/file", {:relative_path => :file}).and_return(file)
@helper.path2instance(@request, "/my/file", {:relative_path => :file})
end
it "should use a fileset to find paths" do
@fileset = double('fileset', :files => [], :path => "/my/files")
expect(Puppet::FileServing::Fileset).to receive(:new).with("/my/file", anything).and_return(@fileset)
@helper.path2instances(@request, "/my/file")
end
it "should support finding across multiple paths by merging the filesets" do
first = double('fileset', :files => [], :path => "/first/file")
expect(Puppet::FileServing::Fileset).to receive(:new).with("/first/file", anything).and_return(first)
second = double('fileset', :files => [], :path => "/second/file")
expect(Puppet::FileServing::Fileset).to receive(:new).with("/second/file", anything).and_return(second)
expect(Puppet::FileServing::Fileset).to receive(:merge).with(first, second).and_return({})
@helper.path2instances(@request, "/first/file", "/second/file")
end
it "should pass the indirection request to the Fileset at initialization" do
expect(Puppet::FileServing::Fileset).to receive(:new).with(anything, @request).and_return(@fileset)
@helper.path2instances(@request, "/my/file")
end
describe "when creating instances" do
before do
allow(@request).to receive(:key).and_return("puppet://host/mount/dir")
@one = double('one', :links= => nil, :collect => nil)
@two = double('two', :links= => nil, :collect => nil)
@fileset = double('fileset', :files => %w{one two}, :path => "/my/file")
allow(Puppet::FileServing::Fileset).to receive(:new).and_return(@fileset)
end
it "should set each returned instance's path to the original path" do
expect(@model).to receive(:new).with("/my/file", anything).and_return(@one, @two)
@helper.path2instances(@request, "/my/file")
end
it "should set each returned instance's relative path to the file-specific path" do
expect(@model).to receive(:new).with(anything, hash_including(relative_path: "one")).and_return(@one)
expect(@model).to receive(:new).with(anything, hash_including(relative_path: "two")).and_return(@two)
@helper.path2instances(@request, "/my/file")
end
it "should set the links value on each instance if one is provided" do
expect(@one).to receive(:links=).with(:manage)
expect(@two).to receive(:links=).with(:manage)
expect(@model).to receive(:new).and_return(@one, @two)
@request.options[:links] = :manage
@helper.path2instances(@request, "/my/file")
end
it "should set the request checksum_type if one is provided" do
expect(@one).to receive(:checksum_type=).with(:test)
expect(@two).to receive(:checksum_type=).with(:test)
expect(@model).to receive(:new).and_return(@one, @two)
@request.options[:checksum_type] = :test
@helper.path2instances(@request, "/my/file")
end
it "should collect the instance's attributes" do
expect(@one).to receive(:collect)
expect(@two).to receive(:collect)
expect(@model).to receive(:new).and_return(@one, @two)
@helper.path2instances(@request, "/my/file")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/base_spec.rb | spec/unit/file_serving/base_spec.rb | require 'spec_helper'
require 'puppet/file_serving/base'
describe Puppet::FileServing::Base do
let(:path) { File.expand_path('/module/dir/file') }
let(:file) { File.expand_path('/my/file') }
it "should accept a path" do
expect(Puppet::FileServing::Base.new(path).path).to eq(path)
end
it "should require that paths be fully qualified" do
expect { Puppet::FileServing::Base.new("module/dir/file") }.to raise_error(ArgumentError)
end
it "should allow specification of whether links should be managed" do
expect(Puppet::FileServing::Base.new(path, :links => :manage).links).to eq(:manage)
end
it "should have a :source attribute" do
file = Puppet::FileServing::Base.new(path)
expect(file).to respond_to(:source)
expect(file).to respond_to(:source=)
end
it "should consider :ignore links equivalent to :manage links" do
expect(Puppet::FileServing::Base.new(path, :links => :ignore).links).to eq(:manage)
end
it "should fail if :links is set to anything other than :manage, :follow, or :ignore" do
expect { Puppet::FileServing::Base.new(path, :links => :else) }.to raise_error(ArgumentError)
end
it "should allow links values to be set as strings" do
expect(Puppet::FileServing::Base.new(path, :links => "follow").links).to eq(:follow)
end
it "should default to :manage for :links" do
expect(Puppet::FileServing::Base.new(path).links).to eq(:manage)
end
it "should allow specification of a relative path" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
expect(Puppet::FileServing::Base.new(path, :relative_path => "my/file").relative_path).to eq("my/file")
end
it "should have a means of determining if the file exists" do
expect(Puppet::FileServing::Base.new(file)).to respond_to(:exist?)
end
it "should correctly indicate if the file is present" do
expect(Puppet::FileSystem).to receive(:lstat).with(file).and_return(double('stat'))
expect(Puppet::FileServing::Base.new(file).exist?).to be_truthy
end
it "should correctly indicate if the file is absent" do
expect(Puppet::FileSystem).to receive(:lstat).with(file).and_raise(RuntimeError)
expect(Puppet::FileServing::Base.new(file).exist?).to be_falsey
end
describe "when setting the relative path" do
it "should require that the relative path be unqualified" do
@file = Puppet::FileServing::Base.new(path)
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
expect { @file.relative_path = File.expand_path("/qualified/file") }.to raise_error(ArgumentError)
end
end
describe "when determining the full file path" do
let(:path) { File.expand_path('/this/file') }
let(:file) { Puppet::FileServing::Base.new(path) }
it "should return the path if there is no relative path" do
expect(file.full_path).to eq(path)
end
it "should return the path if the relative_path is set to ''" do
file.relative_path = ""
expect(file.full_path).to eq(path)
end
it "should return the path if the relative_path is set to '.'" do
file.relative_path = "."
expect(file.full_path).to eq(path)
end
it "should return the path joined with the relative path if there is a relative path and it is not set to '/' or ''" do
file.relative_path = "not/qualified"
expect(file.full_path).to eq(File.join(path, "not/qualified"))
end
it "should strip extra slashes" do
file = Puppet::FileServing::Base.new(File.join(File.expand_path('/'), "//this//file"))
expect(file.full_path).to eq(path)
end
end
describe "when handling a UNC file path on Windows" do
let(:path) { '//server/share/filename' }
let(:file) { Puppet::FileServing::Base.new(path) }
before :each do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
it "should preserve double slashes at the beginning of the path" do
expect(file.full_path).to eq(path)
end
it "should strip double slashes not at the beginning of the path" do
file = Puppet::FileServing::Base.new('//server//share//filename')
expect(file.full_path).to eq(path)
end
end
describe "when stat'ing files" do
let(:path) { File.expand_path('/this/file') }
let(:file) { Puppet::FileServing::Base.new(path) }
let(:stat) { double('stat', :ftype => 'file' ) }
let(:stubbed_file) { double(path, :stat => stat, :lstat => stat)}
it "should stat the file's full path" do
expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stat)
file.stat
end
it "should fail if the file does not exist" do
expect(Puppet::FileSystem).to receive(:lstat).with(path).and_raise(Errno::ENOENT)
expect { file.stat }.to raise_error(Errno::ENOENT)
end
it "should use :lstat if :links is set to :manage" do
expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stubbed_file)
file.stat
end
it "should use :stat if :links is set to :follow" do
expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(stubbed_file)
file.links = :follow
file.stat
end
end
describe "#absolute?" do
it "should be accept POSIX paths" do
expect(Puppet::FileServing::Base).to be_absolute('/')
end
it "should accept Windows paths on Windows" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
allow(Puppet.features).to receive(:posix?).and_return(false)
expect(Puppet::FileServing::Base).to be_absolute('c:/foo')
end
it "should reject Windows paths on POSIX" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
expect(Puppet::FileServing::Base).not_to be_absolute('c:/foo')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount/file_spec.rb | spec/unit/file_serving/mount/file_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount/file'
module FileServingMountTesting
def stub_facter(hostname)
allow(Facter).to receive(:value).with("networking.hostname").and_return(hostname.sub(/\..+/, ''))
allow(Facter).to receive(:value).with("networking.domain").and_return(hostname.sub(/^[^.]+\./, ''))
end
end
describe Puppet::FileServing::Mount::File do
it "should be invalid if it does not have a path" do
expect { Puppet::FileServing::Mount::File.new("foo").validate }.to raise_error(ArgumentError)
end
it "should be valid if it has a path" do
allow(FileTest).to receive(:directory?).and_return(true)
allow(FileTest).to receive(:readable?).and_return(true)
mount = Puppet::FileServing::Mount::File.new("foo")
mount.path = "/foo"
expect { mount.validate }.not_to raise_error
end
describe "when setting the path" do
before do
@mount = Puppet::FileServing::Mount::File.new("test")
@dir = "/this/path/does/not/exist"
end
it "should fail if the path is not a directory" do
expect(FileTest).to receive(:directory?).and_return(false)
expect { @mount.path = @dir }.to raise_error(ArgumentError)
end
it "should fail if the path is not readable" do
expect(FileTest).to receive(:directory?).and_return(true)
expect(FileTest).to receive(:readable?).and_return(false)
expect { @mount.path = @dir }.to raise_error(ArgumentError)
end
end
describe "when substituting hostnames and ip addresses into file paths" do
include FileServingMountTesting
before do
allow(FileTest).to receive(:directory?).and_return(true)
allow(FileTest).to receive(:readable?).and_return(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@host = "host.domain.com"
end
after :each do
Puppet::FileServing::Mount::File.instance_variable_set(:@localmap, nil)
end
it "should replace incidences of %h in the path with the client's short name" do
@mount.path = "/dir/%h/yay"
expect(@mount.path(@host)).to eq("/dir/host/yay")
end
it "should replace incidences of %H in the path with the client's fully qualified name" do
@mount.path = "/dir/%H/yay"
expect(@mount.path(@host)).to eq("/dir/host.domain.com/yay")
end
it "should replace incidences of %d in the path with the client's domain name" do
@mount.path = "/dir/%d/yay"
expect(@mount.path(@host)).to eq("/dir/domain.com/yay")
end
it "should perform all necessary replacements" do
@mount.path = "/%h/%d/%H"
expect(@mount.path(@host)).to eq("/host/domain.com/host.domain.com")
end
it "should use local host information if no client data is provided" do
stub_facter("myhost.mydomain.com")
@mount.path = "/%h/%d/%H"
expect(@mount.path).to eq("/myhost/mydomain.com/myhost.mydomain.com")
end
end
describe "when determining the complete file path" do
include FileServingMountTesting
before do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(FileTest).to receive(:directory?).and_return(true)
allow(FileTest).to receive(:readable?).and_return(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@mount.path = "/mount"
stub_facter("myhost.mydomain.com")
@host = "host.domain.com"
end
it "should return nil if the file is absent" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(@mount.complete_path("/my/path", nil)).to be_nil
end
it "should write a log message if the file is absent" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(Puppet).to receive(:info).with("File does not exist or is not accessible: /mount/my/path")
@mount.complete_path("/my/path", nil)
end
it "should return the file path if the file is present" do
allow(Puppet::FileSystem).to receive(:exist?).with("/my/path").and_return(true)
expect(@mount.complete_path("/my/path", nil)).to eq("/mount/my/path")
end
it "should treat a nil file name as the path to the mount itself" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
expect(@mount.complete_path(nil, nil)).to eq("/mount")
end
it "should use the client host name if provided in the options" do
@mount.path = "/mount/%h"
expect(@mount.complete_path("/my/path", @host)).to eq("/mount/host/my/path")
end
it "should perform replacements on the base path" do
@mount.path = "/blah/%h"
expect(@mount.complete_path("/my/stuff", @host)).to eq("/blah/host/my/stuff")
end
it "should not perform replacements on the per-file path" do
@mount.path = "/blah"
expect(@mount.complete_path("/%h/stuff", @host)).to eq("/blah/%h/stuff")
end
it "should look for files relative to its base directory" do
expect(@mount.complete_path("/my/stuff", @host)).to eq("/mount/my/stuff")
end
end
describe "when finding files" do
include FileServingMountTesting
before do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(FileTest).to receive(:directory?).and_return(true)
allow(FileTest).to receive(:readable?).and_return(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@mount.path = "/mount"
stub_facter("myhost.mydomain.com")
@host = "host.domain.com"
@request = double('request', :node => "foo")
end
it "should return the results of the complete file path" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(@mount).to receive(:complete_path).with("/my/path", "foo").and_return("eh")
expect(@mount.find("/my/path", @request)).to eq("eh")
end
end
describe "when searching for files" do
include FileServingMountTesting
before do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(FileTest).to receive(:directory?).and_return(true)
allow(FileTest).to receive(:readable?).and_return(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@mount.path = "/mount"
stub_facter("myhost.mydomain.com")
@host = "host.domain.com"
@request = double('request', :node => "foo")
end
it "should return the results of the complete file path as an array" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(@mount).to receive(:complete_path).with("/my/path", "foo").and_return("eh")
expect(@mount.search("/my/path", @request)).to eq(["eh"])
end
it "should return nil if the complete path is nil" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(@mount).to receive(:complete_path).with("/my/path", "foo").and_return(nil)
expect(@mount.search("/my/path", @request)).to be_nil
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount/modules_spec.rb | spec/unit/file_serving/mount/modules_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount/modules'
describe Puppet::FileServing::Mount::Modules do
before do
@mount = Puppet::FileServing::Mount::Modules.new("modules")
@environment = double('environment', :module => nil)
@request = double('request', :environment => @environment)
end
describe "when finding files" do
it "should fail if no module is specified" do
expect { @mount.find("", @request) }.to raise_error(/No module specified/)
end
it "should use the provided environment to find the module" do
expect(@environment).to receive(:module)
@mount.find("foo", @request)
end
it "should treat the first field of the relative path as the module name" do
expect(@environment).to receive(:module).with("foo")
@mount.find("foo/bar/baz", @request)
end
it "should return nil if the specified module does not exist" do
expect(@environment).to receive(:module).with("foo")
@mount.find("foo/bar/baz", @request)
end
it "should return the file path from the module" do
mod = double('module')
expect(mod).to receive(:file).with("bar/baz").and_return("eh")
expect(@environment).to receive(:module).with("foo").and_return(mod)
expect(@mount.find("foo/bar/baz", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should fail if no module is specified" do
expect { @mount.search("", @request) }.to raise_error(/No module specified/)
end
it "should use the node's environment to search the module" do
expect(@environment).to receive(:module)
@mount.search("foo", @request)
end
it "should treat the first field of the relative path as the module name" do
expect(@environment).to receive(:module).with("foo")
@mount.search("foo/bar/baz", @request)
end
it "should return nil if the specified module does not exist" do
expect(@environment).to receive(:module).with("foo").and_return(nil)
@mount.search("foo/bar/baz", @request)
end
it "should return the file path as an array from the module" do
mod = double('module')
expect(mod).to receive(:file).with("bar/baz").and_return("eh")
expect(@environment).to receive(:module).with("foo").and_return(mod)
expect(@mount.search("foo/bar/baz", @request)).to eq(["eh"])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount/pluginfacts_spec.rb | spec/unit/file_serving/mount/pluginfacts_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount/pluginfacts'
describe Puppet::FileServing::Mount::PluginFacts do
before do
@mount = Puppet::FileServing::Mount::PluginFacts.new("pluginfacts")
@environment = double('environment', :module => nil)
@options = { :recurse => true }
@request = double('request', :environment => @environment, :options => @options)
end
describe "when finding files" do
it "should use the provided environment to find the modules" do
expect(@environment).to receive(:modules).and_return([])
@mount.find("foo", @request)
end
it "should return nil if no module can be found with a matching plugin" do
mod = double('module')
allow(mod).to receive(:pluginfact).with("foo/bar").and_return(nil)
allow(@environment).to receive(:modules).and_return([mod])
expect(@mount.find("foo/bar", @request)).to be_nil
end
it "should return the file path from the module" do
mod = double('module')
allow(mod).to receive(:pluginfact).with("foo/bar").and_return("eh")
allow(@environment).to receive(:modules).and_return([mod])
expect(@mount.find("foo/bar", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should use the node's environment to find the modules" do
expect(@environment).to receive(:modules).at_least(:once).and_return([])
allow(@environment).to receive(:modulepath).and_return(["/tmp/modules"])
@mount.search("foo", @request)
end
it "should return modulepath if no modules can be found that have plugins" do
mod = double('module')
allow(mod).to receive(:pluginfacts?).and_return(false)
allow(@environment).to receive(:modules).and_return([])
allow(@environment).to receive(:modulepath).and_return(["/"])
expect(@options).to receive(:[]=).with(:recurse, false)
expect(@mount.search("foo/bar", @request)).to eq(["/"])
end
it "should return the default search module path if no modules can be found that have plugins and modulepath is invalid" do
mod = double('module')
allow(mod).to receive(:pluginfacts?).and_return(false)
allow(@environment).to receive(:modules).and_return([])
allow(@environment).to receive(:modulepath).and_return([])
expect(@mount.search("foo/bar", @request)).to eq([Puppet[:codedir]])
end
it "should return the plugin paths for each module that has plugins" do
one = double('module', :pluginfacts? => true, :plugin_fact_directory => "/one")
two = double('module', :pluginfacts? => true, :plugin_fact_directory => "/two")
allow(@environment).to receive(:modules).and_return([one, two])
expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two})
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount/tasks_spec.rb | spec/unit/file_serving/mount/tasks_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount/tasks'
describe Puppet::FileServing::Mount::Tasks do
before do
@mount = Puppet::FileServing::Mount::Tasks.new("tasks")
@environment = double('environment', :module => nil)
@request = double('request', :environment => @environment)
end
describe "when finding task files" do
it "should fail if no task is specified" do
expect { @mount.find("", @request) }.to raise_error(/No task specified/)
end
it "should use the request's environment to find the module" do
mod_name = 'foo'
expect(@environment).to receive(:module).with(mod_name)
@mount.find(mod_name, @request)
end
it "should use the first segment of the request's path as the module name" do
expect(@environment).to receive(:module).with("foo")
@mount.find("foo/bartask", @request)
end
it "should return nil if the module in the path doesn't exist" do
expect(@environment).to receive(:module).with("foo").and_return(nil)
expect(@mount.find("foo/bartask", @request)).to be_nil
end
it "should return the file path from the module" do
mod = double('module')
expect(mod).to receive(:task_file).with("bartask").and_return("mocked")
expect(@environment).to receive(:module).with("foo").and_return(mod)
expect(@mount.find("foo/bartask", @request)).to eq("mocked")
end
end
describe "when searching for task files" do
it "should fail if no module is specified" do
expect { @mount.search("", @request) }.to raise_error(/No task specified/)
end
it "should use the request's environment to find the module" do
mod_name = 'foo'
expect(@environment).to receive(:module).with(mod_name)
@mount.search(mod_name, @request)
end
it "should use the first segment of the request's path as the module name" do
expect(@environment).to receive(:module).with("foo")
@mount.search("foo/bartask", @request)
end
it "should return nil if the module in the path doesn't exist" do
expect(@environment).to receive(:module).with("foo").and_return(nil)
expect(@mount.search("foo/bartask", @request)).to be_nil
end
it "should return the file path from the module" do
mod = double('module')
expect(mod).to receive(:task_file).with("bartask").and_return("mocked")
expect(@environment).to receive(:module).with("foo").and_return(mod)
expect(@mount.search("foo/bartask", @request)).to eq(["mocked"])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount/scripts_spec.rb | spec/unit/file_serving/mount/scripts_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount/scripts'
describe Puppet::FileServing::Mount::Scripts do
before do
@mount = Puppet::FileServing::Mount::Scripts.new("scripts")
@environment = double('environment', :module => nil)
@request = double('request', :environment => @environment)
end
describe "when finding files" do
it "should fail if no module is specified" do
expect { @mount.find("", @request) }.to raise_error(/No module specified/)
end
it "should use the provided environment to find the module" do
expect(@environment).to receive(:module)
@mount.find("foo", @request)
end
it "should treat the first field of the relative path as the module name" do
expect(@environment).to receive(:module).with("foo")
@mount.find("foo/bar/baz", @request)
end
it "should return nil if the specified module does not exist" do
expect(@environment).to receive(:module).with("foo")
@mount.find("foo/bar/baz", @request)
end
it "should return the file path from the module" do
mod = double('module')
expect(mod).to receive(:script).with("bar/baz").and_return("eh")
expect(@environment).to receive(:module).with("foo").and_return(mod)
expect(@mount.find("foo/bar/baz", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should fail if no module is specified" do
expect { @mount.search("", @request) }.to raise_error(/No module specified/)
end
it "should use the node's environment to search the module" do
expect(@environment).to receive(:module)
@mount.search("foo", @request)
end
it "should treat the first field of the relative path as the module name" do
expect(@environment).to receive(:module).with("foo")
@mount.search("foo/bar/baz", @request)
end
it "should return nil if the specified module does not exist" do
expect(@environment).to receive(:module).with("foo").and_return(nil)
@mount.search("foo/bar/baz", @request)
end
it "should return the script path as an array from the module" do
mod = double('module')
expect(mod).to receive(:script).with("bar/baz").and_return("eh")
expect(@environment).to receive(:module).with("foo").and_return(mod)
expect(@mount.search("foo/bar/baz", @request)).to eq(["eh"])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount/plugins_spec.rb | spec/unit/file_serving/mount/plugins_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount/plugins'
describe Puppet::FileServing::Mount::Plugins do
before do
@mount = Puppet::FileServing::Mount::Plugins.new("plugins")
@environment = double('environment', :module => nil)
@options = { :recurse => true }
@request = double('request', :environment => @environment, :options => @options)
end
describe "when finding files" do
it "should use the provided environment to find the modules" do
expect(@environment).to receive(:modules).and_return([])
@mount.find("foo", @request)
end
it "should return nil if no module can be found with a matching plugin" do
mod = double('module')
allow(mod).to receive(:plugin).with("foo/bar").and_return(nil)
allow(@environment).to receive(:modules).and_return([mod])
expect(@mount.find("foo/bar", @request)).to be_nil
end
it "should return the file path from the module" do
mod = double('module')
allow(mod).to receive(:plugin).with("foo/bar").and_return("eh")
allow(@environment).to receive(:modules).and_return([mod])
expect(@mount.find("foo/bar", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should use the node's environment to find the modules" do
expect(@environment).to receive(:modules).at_least(:once).and_return([])
allow(@environment).to receive(:modulepath).and_return(["/tmp/modules"])
@mount.search("foo", @request)
end
it "should return modulepath if no modules can be found that have plugins" do
mod = double('module')
allow(mod).to receive(:plugins?).and_return(false)
allow(@environment).to receive(:modules).and_return([])
allow(@environment).to receive(:modulepath).and_return(["/"])
expect(@options).to receive(:[]=).with(:recurse, false)
expect(@mount.search("foo/bar", @request)).to eq(["/"])
end
it "should return the default search module path if no modules can be found that have plugins and modulepath is invalid" do
mod = double('module')
allow(mod).to receive(:plugins?).and_return(false)
allow(@environment).to receive(:modules).and_return([])
allow(@environment).to receive(:modulepath).and_return([])
expect(@mount.search("foo/bar", @request)).to eq([Puppet[:codedir]])
end
it "should return the plugin paths for each module that has plugins" do
one = double('module', :plugins? => true, :plugin_directory => "/one")
two = double('module', :plugins? => true, :plugin_directory => "/two")
allow(@environment).to receive(:modules).and_return([one, two])
expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two})
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/mount/locales_spec.rb | spec/unit/file_serving/mount/locales_spec.rb | require 'spec_helper'
require 'puppet/file_serving/mount/locales'
describe Puppet::FileServing::Mount::Locales do
before do
@mount = Puppet::FileServing::Mount::Locales.new("locales")
@environment = double('environment', :module => nil)
@options = { :recurse => true }
@request = double('request', :environment => @environment, :options => @options)
end
describe "when finding files" do
it "should use the provided environment to find the modules" do
expect(@environment).to receive(:modules).and_return([])
@mount.find("foo", @request)
end
it "should return nil if no module can be found with a matching locale" do
mod = double('module')
allow(mod).to receive(:locale).with("foo/bar").and_return(nil)
allow(@environment).to receive(:modules).and_return([mod])
expect(@mount.find("foo/bar", @request)).to be_nil
end
it "should return the file path from the module" do
mod = double('module')
allow(mod).to receive(:locale).with("foo/bar").and_return("eh")
allow(@environment).to receive(:modules).and_return([mod])
expect(@mount.find("foo/bar", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should use the node's environment to find the modules" do
expect(@environment).to receive(:modules).at_least(:once).and_return([])
allow(@environment).to receive(:modulepath).and_return(["/tmp/modules"])
@mount.search("foo", @request)
end
it "should return modulepath if no modules can be found that have locales" do
mod = double('module')
allow(mod).to receive(:locales?).and_return(false)
allow(@environment).to receive(:modules).and_return([])
allow(@environment).to receive(:modulepath).and_return(["/"])
expect(@options).to receive(:[]=).with(:recurse, false)
expect(@mount.search("foo/bar", @request)).to eq(["/"])
end
it "should return the default search module path if no modules can be found that have locales and modulepath is invalid" do
mod = double('module')
allow(mod).to receive(:locales?).and_return(false)
allow(@environment).to receive(:modules).and_return([])
allow(@environment).to receive(:modulepath).and_return([])
expect(@mount.search("foo/bar", @request)).to eq([Puppet[:codedir]])
end
it "should return the locale paths for each module that has locales" do
one = double('module', :locales? => true, :locale_directory => "/one")
two = double('module', :locales? => true, :locale_directory => "/two")
allow(@environment).to receive(:modules).and_return([one, two])
expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two})
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_serving/configuration/parser_spec.rb | spec/unit/file_serving/configuration/parser_spec.rb | require 'spec_helper'
require 'puppet/file_serving/configuration/parser'
module FSConfigurationParserTesting
def write_config_file(content)
# We want an array, but we actually want our carriage returns on all of it.
File.open(@path, 'w') {|f| f.puts content}
end
end
describe Puppet::FileServing::Configuration::Parser do
include PuppetSpec::Files
before :each do
@path = tmpfile('fileserving_config')
FileUtils.touch(@path)
@parser = Puppet::FileServing::Configuration::Parser.new(@path)
end
describe Puppet::FileServing::Configuration::Parser, " when parsing" do
include FSConfigurationParserTesting
it "should allow comments" do
write_config_file("# this is a comment\n")
expect { @parser.parse }.not_to raise_error
end
it "should allow blank lines" do
write_config_file("\n")
expect { @parser.parse }.not_to raise_error
end
it "should return a hash of the created mounts" do
mount1 = double('one', :validate => true)
mount2 = double('two', :validate => true)
expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(mount1)
expect(Puppet::FileServing::Mount::File).to receive(:new).with("two").and_return(mount2)
write_config_file "[one]\n[two]\n"
result = @parser.parse
expect(result["one"]).to equal(mount1)
expect(result["two"]).to equal(mount2)
end
it "should only allow mount names that are alphanumeric plus dashes" do
write_config_file "[a*b]\n"
expect { @parser.parse }.to raise_error(ArgumentError)
end
it "should fail if the value for path starts with an equals sign" do
write_config_file "[one]\npath = /testing"
expect { @parser.parse }.to raise_error(ArgumentError)
end
it "should validate each created mount" do
mount1 = double('one')
expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(mount1)
write_config_file "[one]\n"
expect(mount1).to receive(:validate)
@parser.parse
end
it "should fail if any mount does not pass validation" do
mount1 = double('one')
expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(mount1)
write_config_file "[one]\n"
expect(mount1).to receive(:validate).and_raise(RuntimeError)
expect { @parser.parse }.to raise_error(RuntimeError)
end
it "should return comprehensible error message, if invalid line detected" do
write_config_file "[one]\n\n\x01path /etc/puppetlabs/puppet/files\n\x01allow *\n"
expect { @parser.parse }.to raise_error(ArgumentError, /Invalid entry at \(file: .*, line: 3\): .*/)
end
end
describe Puppet::FileServing::Configuration::Parser, " when parsing mount attributes" do
include FSConfigurationParserTesting
before do
@mount = double('testmount', :name => "one", :validate => true)
expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(@mount)
end
it "should set the mount path to the path attribute from that section" do
write_config_file "[one]\npath /some/path\n"
expect(@mount).to receive(:path=).with("/some/path")
@parser.parse
end
[:allow,:deny].each { |acl_type|
it "should ignore inline comments in #{acl_type}" do
write_config_file "[one]\n#{acl_type} something \# will it work?\n"
expect(@parser.parse).to eq('one' => @mount)
end
it "should ignore #{acl_type} from ACLs with varying spacing around commas" do
write_config_file "[one]\n#{acl_type} someone,sometwo, somethree , somefour ,somefive\n"
expect(@parser.parse).to eq('one' => @mount)
end
it "should log an error and print the location of the #{acl_type} rule" do
write_config_file(<<~CONFIG)
[one]
#{acl_type} one
CONFIG
expect(Puppet).to receive(:err).with(/Entry '#{acl_type} one' is unsupported and will be ignored at \(file: .*, line: 2\)/)
@parser.parse
end
}
it "should not generate an error when parsing 'allow *'" do
write_config_file "[one]\nallow *\n"
expect(Puppet).to receive(:err).never
@parser.parse
end
it "should return comprehensible error message, if failed on invalid attribute" do
write_config_file "[one]\ndo something\n"
expect { @parser.parse }.to raise_error(ArgumentError, /Invalid argument 'do' at \(file: .*, line: 2\)/)
end
end
describe Puppet::FileServing::Configuration::Parser, " when parsing the modules mount" do
include FSConfigurationParserTesting
before do
@mount = double('modulesmount', :name => "modules", :validate => true)
end
it "should create an instance of the Modules Mount class" do
write_config_file "[modules]\n"
expect(Puppet::FileServing::Mount::Modules).to receive(:new).with("modules").and_return(@mount)
@parser.parse
end
it "should warn if a path is set" do
write_config_file "[modules]\npath /some/path\n"
expect(Puppet::FileServing::Mount::Modules).to receive(:new).with("modules").and_return(@mount)
expect(Puppet).to receive(:warning)
@parser.parse
end
end
describe Puppet::FileServing::Configuration::Parser, " when parsing the scripts mount" do
include FSConfigurationParserTesting
before do
@mount = double('scriptsmount', :name => "scripts", :validate => true)
end
it "should create an instance of the Scripts Mount class" do
write_config_file "[scripts]\n"
expect(Puppet::FileServing::Mount::Scripts).to receive(:new).with("scripts").and_return(@mount)
@parser.parse
end
it "should warn if a path is set" do
write_config_file "[scripts]\npath /some/path\n"
expect(Puppet::FileServing::Mount::Scripts).to receive(:new).with("scripts").and_return(@mount)
expect(Puppet).to receive(:warning)
@parser.parse
end
end
describe Puppet::FileServing::Configuration::Parser, " when parsing the plugins mount" do
include FSConfigurationParserTesting
before do
@mount = double('pluginsmount', :name => "plugins", :validate => true)
end
it "should create an instance of the Plugins Mount class" do
write_config_file "[plugins]\n"
expect(Puppet::FileServing::Mount::Plugins).to receive(:new).with("plugins").and_return(@mount)
@parser.parse
end
it "should warn if a path is set" do
write_config_file "[plugins]\npath /some/path\n"
expect(Puppet).to receive(:warning)
@parser.parse
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/hiera/scope_spec.rb | spec/unit/hiera/scope_spec.rb | require 'spec_helper'
require 'hiera/scope'
require 'puppet_spec/scope'
describe Hiera::Scope do
include PuppetSpec::Scope
let(:real) { create_test_scope_for_node("test_node") }
let(:scope) { Hiera::Scope.new(real) }
describe "#initialize" do
it "should store the supplied puppet scope" do
expect(scope.real).to eq(real)
end
end
describe "#[]" do
it "should return nil when no value is found and strict mode is off" do
Puppet[:strict] = :warning
expect(scope["foo"]).to eq(nil)
end
it "should raise error by default when no value is found" do
expect { scope["foo"] }.to raise_error(/Undefined variable 'foo'/)
end
it "should treat '' as nil" do
real["foo"] = ""
expect(scope["foo"]).to eq(nil)
end
it "should return found data" do
real["foo"] = "bar"
expect(scope["foo"]).to eq("bar")
end
it "preserves the case of a string that is found" do
real["foo"] = "CAPITAL!"
expect(scope["foo"]).to eq("CAPITAL!")
end
it "aliases $module_name as calling_module" do
real["module_name"] = "the_module"
expect(scope["calling_module"]).to eq("the_module")
end
it "uses the name of the of the scope's class as the calling_class" do
real.source = Puppet::Resource::Type.new(:hostclass,
"testing",
:module_name => "the_module")
expect(scope["calling_class"]).to eq("testing")
end
it "downcases the calling_class" do
real.source = Puppet::Resource::Type.new(:hostclass,
"UPPER CASE",
:module_name => "the_module")
expect(scope["calling_class"]).to eq("upper case")
end
it "looks for the class which includes the defined type as the calling_class" do
parent = create_test_scope_for_node("parent")
real.parent = parent
parent.source = Puppet::Resource::Type.new(:hostclass,
"name_of_the_class_including_the_definition",
:module_name => "class_module")
real.source = Puppet::Resource::Type.new(:definition,
"definition_name",
:module_name => "definition_module")
expect(scope["calling_class"]).to eq("name_of_the_class_including_the_definition")
end
end
describe "#exist?" do
it "should correctly report missing data" do
real["nil_value"] = nil
real["blank_value"] = ""
expect(scope.exist?("nil_value")).to eq(true)
expect(scope.exist?("blank_value")).to eq(true)
expect(scope.exist?("missing_value")).to eq(false)
end
it "should always return true for calling_class and calling_module" do
expect(scope.include?("calling_class")).to eq(true)
expect(scope.include?("calling_class_path")).to eq(true)
expect(scope.include?("calling_module")).to eq(true)
end
end
describe "#call_function" do
it "should delegate a call to call_function to the real scope" do
expect(real).to receive(:call_function).once
scope.call_function('some_function', [1,2,3])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/metadata_spec.rb | spec/unit/module_tool/metadata_spec.rb | require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool::Metadata do
let(:data) { {} }
let(:metadata) { Puppet::ModuleTool::Metadata.new }
describe 'property lookups' do
subject { metadata }
%w[ name version author summary license source project_page issues_url
dependencies dashed_name release_name description data_provider].each do |prop|
describe "##{prop}" do
it "responds to the property" do
subject.send(prop)
end
end
end
end
describe "#update" do
subject { metadata.update(data) }
context "with a valid name" do
let(:data) { { 'name' => 'billgates-mymodule' } }
it "extracts the author name from the name field" do
expect(subject.to_hash['author']).to eq('billgates')
end
it "extracts a module name from the name field" do
expect(subject.module_name).to eq('mymodule')
end
context "and existing author" do
before { metadata.update('author' => 'foo') }
it "avoids overwriting the existing author" do
expect(subject.to_hash['author']).to eq('foo')
end
end
end
context "with a valid name and author" do
let(:data) { { 'name' => 'billgates-mymodule', 'author' => 'foo' } }
it "use the author name from the author field" do
expect(subject.to_hash['author']).to eq('foo')
end
context "and preexisting author" do
before { metadata.update('author' => 'bar') }
it "avoids overwriting the existing author" do
expect(subject.to_hash['author']).to eq('foo')
end
end
end
context "with an invalid name" do
context "(short module name)" do
let(:data) { { 'name' => 'mymodule' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name")
end
end
context "(missing namespace)" do
let(:data) { { 'name' => '/mymodule' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name")
end
end
context "(missing module name)" do
let(:data) { { 'name' => 'namespace/' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name")
end
end
context "(invalid namespace)" do
let(:data) { { 'name' => "dolla'bill$-mymodule" } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the namespace contains non-alphanumeric characters")
end
end
context "(non-alphanumeric module name)" do
let(:data) { { 'name' => "dollabils-fivedolla'" } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the module name contains non-alphanumeric (or underscore) characters")
end
end
context "(module name starts with a number)" do
let(:data) { { 'name' => "dollabills-5dollars" } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the module name must begin with a letter")
end
end
end
context "with an invalid version" do
let(:data) { { 'version' => '3.0' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'version' field in metadata.json: version string cannot be parsed as a valid Semantic Version")
end
end
context "with a valid source" do
context "which is a GitHub URL" do
context "with a scheme" do
before { metadata.update('source' => 'https://github.com/billgates/amazingness') }
it "predicts a default project_page" do
expect(subject.to_hash['project_page']).to eq('https://github.com/billgates/amazingness')
end
it "predicts a default issues_url" do
expect(subject.to_hash['issues_url']).to eq('https://github.com/billgates/amazingness/issues')
end
end
context "without a scheme" do
before { metadata.update('source' => 'github.com/billgates/amazingness') }
it "predicts a default project_page" do
expect(subject.to_hash['project_page']).to eq('https://github.com/billgates/amazingness')
end
it "predicts a default issues_url" do
expect(subject.to_hash['issues_url']).to eq('https://github.com/billgates/amazingness/issues')
end
end
end
context "which is not a GitHub URL" do
before { metadata.update('source' => 'https://notgithub.com/billgates/amazingness') }
it "does not predict a default project_page" do
expect(subject.to_hash['project_page']).to be nil
end
it "does not predict a default issues_url" do
expect(subject.to_hash['issues_url']).to be nil
end
end
context "which is not a URL" do
before { metadata.update('source' => 'my brain') }
it "does not predict a default project_page" do
expect(subject.to_hash['project_page']).to be nil
end
it "does not predict a default issues_url" do
expect(subject.to_hash['issues_url']).to be nil
end
end
end
context "with a valid dependency" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-goodmodule'}] }}
it "adds the dependency" do
expect(subject.dependencies.size).to eq(1)
end
end
context "with a invalid dependency name" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabsbadmodule'}] }}
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError)
end
end
context "with a valid dependency version range" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-badmodule', 'version_requirement' => '>= 2.0.0'}] }}
it "adds the dependency" do
expect(subject.dependencies.size).to eq(1)
end
end
context "with a invalid version range" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabsbadmodule', 'version_requirement' => '>= banana'}] }}
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError)
end
end
context "with duplicate dependencies" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-dupmodule', 'version_requirement' => '1.0.0'},
{'name' => 'puppetlabs-dupmodule', 'version_requirement' => '0.0.1'}] }
}
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError)
end
end
context "adding a duplicate dependency" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-origmodule', 'version_requirement' => '1.0.0'}] }}
it "with a different version raises an exception" do
metadata.add_dependency('puppetlabs-origmodule', '>= 0.0.1')
expect { subject }.to raise_error(ArgumentError)
end
it "with the same version does not add another dependency" do
metadata.add_dependency('puppetlabs-origmodule', '1.0.0')
expect(subject.dependencies.size).to eq(1)
end
end
context 'with valid data_provider' do
let(:data) { {'data_provider' => 'the_name'} }
it 'validates the provider correctly' do
expect { subject }.not_to raise_error
end
it 'returns the provider' do
expect(subject.data_provider).to eq('the_name')
end
end
context 'with invalid data_provider' do
let(:data) { }
it "raises exception unless argument starts with a letter" do
expect { metadata.update('data_provider' => '_the_name') }.to raise_error(ArgumentError, /field 'data_provider' must begin with a letter/)
expect { metadata.update('data_provider' => '') }.to raise_error(ArgumentError, /field 'data_provider' must begin with a letter/)
end
it "raises exception if argument contains non-alphanumeric characters" do
expect { metadata.update('data_provider' => 'the::name') }.to raise_error(ArgumentError, /field 'data_provider' contains non-alphanumeric characters/)
end
it "raises exception unless argument is a string" do
expect { metadata.update('data_provider' => 23) }.to raise_error(ArgumentError, /field 'data_provider' must be a string/)
end
end
end
describe '#dashed_name' do
it 'returns nil in the absence of a module name' do
expect(metadata.update('version' => '1.0.0').release_name).to be_nil
end
it 'returns a hyphenated string containing namespace and module name' do
data = metadata.update('name' => 'foo-bar')
expect(data.dashed_name).to eq('foo-bar')
end
it 'properly handles slash-separated names' do
data = metadata.update('name' => 'foo/bar')
expect(data.dashed_name).to eq('foo-bar')
end
it 'is unaffected by author name' do
data = metadata.update('name' => 'foo/bar', 'author' => 'me')
expect(data.dashed_name).to eq('foo-bar')
end
end
describe '#release_name' do
it 'returns nil in the absence of a module name' do
expect(metadata.update('version' => '1.0.0').release_name).to be_nil
end
it 'returns nil in the absence of a version' do
expect(metadata.update('name' => 'foo/bar').release_name).to be_nil
end
it 'returns a hyphenated string containing module name and version' do
data = metadata.update('name' => 'foo/bar', 'version' => '1.0.0')
expect(data.release_name).to eq('foo-bar-1.0.0')
end
it 'is unaffected by author name' do
data = metadata.update('name' => 'foo/bar', 'version' => '1.0.0', 'author' => 'me')
expect(data.release_name).to eq('foo-bar-1.0.0')
end
end
describe "#to_hash" do
subject { metadata.to_hash }
it "contains the default set of keys" do
expect(subject.keys.sort).to eq(%w[ name version author summary license source issues_url project_page dependencies data_provider].sort)
end
describe "['license']" do
it "defaults to Apache 2" do
expect(subject['license']).to eq("Apache-2.0")
end
end
describe "['dependencies']" do
it "defaults to an empty set" do
expect(subject['dependencies']).to eq(Set.new)
end
end
context "when updated with non-default data" do
subject { metadata.update('license' => 'MIT', 'non-standard' => 'yup').to_hash }
it "overrides the defaults" do
expect(subject['license']).to eq('MIT')
end
it 'contains unanticipated values' do
expect(subject['non-standard']).to eq('yup')
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/install_directory_spec.rb | spec/unit/module_tool/install_directory_spec.rb | require 'spec_helper'
require 'puppet/module_tool/install_directory'
describe Puppet::ModuleTool::InstallDirectory do
def expect_normal_results
results = installer.run
expect(results[:installed_modules].length).to eq 1
expect(results[:installed_modules][0][:module]).to eq("pmtacceptance-stdlib")
expect(results[:installed_modules][0][:version][:vstring]).to eq("1.0.0")
results
end
it "(#15202) creates the install directory" do
target_dir = the_directory('foo', :directory? => false, :exist? => false)
expect(target_dir).to receive(:mkpath)
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
install.prepare('pmtacceptance-stdlib', '1.0.0')
end
it "(#15202) errors when the directory is not accessible" do
target_dir = the_directory('foo', :directory? => false, :exist? => false)
expect(target_dir).to receive(:mkpath).and_raise(Errno::EACCES)
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect {
install.prepare('module', '1.0.1')
}.to raise_error(
Puppet::ModuleTool::Errors::PermissionDeniedCreateInstallDirectoryError
)
end
it "(#15202) errors when an entry along the path is not a directory" do
target_dir = the_directory("foo/bar", :exist? => false, :directory? => false)
expect(target_dir).to receive(:mkpath).and_raise(Errno::EEXIST)
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect {
install.prepare('module', '1.0.1')
}.to raise_error(Puppet::ModuleTool::Errors::InstallPathExistsNotDirectoryError)
end
it "(#15202) simply re-raises an unknown error" do
target_dir = the_directory("foo/bar", :exist? => false, :directory? => false)
expect(target_dir).to receive(:mkpath).and_raise("unknown error")
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect { install.prepare('module', '1.0.1') }.to raise_error("unknown error")
end
it "(#15202) simply re-raises an unknown system call error" do
target_dir = the_directory("foo/bar", :exist? => false, :directory? => false)
expect(target_dir).to receive(:mkpath).and_raise(SystemCallError, "unknown")
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect { install.prepare('module', '1.0.1') }.to raise_error(SystemCallError)
end
def the_directory(name, options)
dir = double("Pathname<#{name}>")
allow(dir).to receive(:exist?).and_return(options.fetch(:exist?, true))
allow(dir).to receive(:directory?).and_return(options.fetch(:directory?, true))
dir
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/tar_spec.rb | spec/unit/module_tool/tar_spec.rb | require 'spec_helper'
require 'puppet/module_tool/tar'
describe Puppet::ModuleTool::Tar do
[
{ :name => 'ObscureLinuxDistro', :win => false },
{ :name => 'Windows', :win => true }
].each do |os|
it "always prefers minitar if it and zlib are present, even with tar available" do
allow(Facter).to receive(:value).with('os.family').and_return(os[:name])
allow(Puppet::Util).to receive(:which).with('tar').and_return('/usr/bin/tar')
allow(Puppet::Util::Platform).to receive(:windows?).and_return(os[:win])
allow(Puppet).to receive(:features).and_return(double(:minitar? => true, :zlib? => true))
expect(described_class.instance).to be_a_kind_of Puppet::ModuleTool::Tar::Mini
end
end
it "falls back to tar when minitar not present and not on Windows" do
allow(Facter).to receive(:value).with('os.family').and_return('ObscureLinuxDistro')
allow(Puppet::Util).to receive(:which).with('tar').and_return('/usr/bin/tar')
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
allow(Puppet).to receive(:features).and_return(double(:minitar? => false))
expect(described_class.instance).to be_a_kind_of Puppet::ModuleTool::Tar::Gnu
end
it "fails when there is no possible implementation" do
allow(Facter).to receive(:value).with('os.family').and_return('Windows')
allow(Puppet::Util).to receive(:which).with('tar')
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
allow(Puppet).to receive(:features).and_return(double(:minitar? => false, :zlib? => false))
expect { described_class.instance }.to raise_error RuntimeError, /No suitable tar/
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/application_spec.rb | spec/unit/module_tool/application_spec.rb | require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool::Applications::Application do
describe 'app' do
good_versions = %w{ 1.2.4 0.0.1 0.0.0 0.0.2-git-8-g3d316d1 0.0.3-b1 10.100.10000
0.1.2-rc1 0.1.2-dev-1 0.1.2-svn12345 0.1.2-3 }
bad_versions = %w{ 0.1 0 0.1.2.3 dev 0.1.2beta }
let :app do Class.new(described_class).new end
good_versions.each do |ver|
it "should accept version string #{ver}" do
app.parse_filename("puppetlabs-ntp-#{ver}")
end
end
bad_versions.each do |ver|
it "should not accept version string #{ver}" do
expect { app.parse_filename("puppetlabs-ntp-#{ver}") }.to raise_error(ArgumentError, /(Invalid version format|Could not parse filename)/)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/installed_modules_spec.rb | spec/unit/module_tool/installed_modules_spec.rb | require 'spec_helper'
require 'puppet/module_tool/installed_modules'
require 'puppet_spec/modules'
describe Puppet::ModuleTool::InstalledModules do
include PuppetSpec::Files
around do |example|
dir = tmpdir("deep_path")
FileUtils.mkdir_p(@modpath = File.join(dir, "modpath"))
@env = Puppet::Node::Environment.create(:env, [@modpath])
Puppet.override(:current_environment => @env) do
example.run
end
end
it 'works when given a semantic version' do
mod = PuppetSpec::Modules.create('goodsemver', @modpath, :metadata => {:version => '1.2.3'})
installed = described_class.new(@env)
expect(installed.modules["puppetlabs-#{mod.name}"].version).to eq(SemanticPuppet::Version.parse('1.2.3'))
end
it 'defaults when not given a semantic version' do
mod = PuppetSpec::Modules.create('badsemver', @modpath, :metadata => {:version => 'banana'})
expect(Puppet).to receive(:warning).with(/Semantic Version/)
installed = described_class.new(@env)
expect(installed.modules["puppetlabs-#{mod.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0'))
end
it 'defaults when not given a full semantic version' do
mod = PuppetSpec::Modules.create('badsemver', @modpath, :metadata => {:version => '1.2'})
expect(Puppet).to receive(:warning).with(/Semantic Version/)
installed = described_class.new(@env)
expect(installed.modules["puppetlabs-#{mod.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0'))
end
it 'still works if there is an invalid version in one of the modules' do
mod1 = PuppetSpec::Modules.create('badsemver', @modpath, :metadata => {:version => 'banana'})
mod2 = PuppetSpec::Modules.create('goodsemver', @modpath, :metadata => {:version => '1.2.3'})
mod3 = PuppetSpec::Modules.create('notquitesemver', @modpath, :metadata => {:version => '1.2'})
expect(Puppet).to receive(:warning).with(/Semantic Version/).twice
installed = described_class.new(@env)
expect(installed.modules["puppetlabs-#{mod1.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0'))
expect(installed.modules["puppetlabs-#{mod2.name}"].version).to eq(SemanticPuppet::Version.parse('1.2.3'))
expect(installed.modules["puppetlabs-#{mod3.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0'))
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/tar/gnu_spec.rb | spec/unit/module_tool/tar/gnu_spec.rb | require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool::Tar::Gnu, unless: Puppet::Util::Platform.windows? do
let(:sourcedir) { '/space path/the/src/dir' }
let(:sourcefile) { '/space path/the/module.tar.gz' }
let(:destdir) { '/space path/the/dest/dir' }
let(:destfile) { '/space path/the/dest/fi le.tar.gz' }
let(:safe_sourcedir) { '/space\ path/the/src/dir' }
let(:safe_sourcefile) { '/space\ path/the/module.tar.gz' }
let(:safe_destdir) { '/space\ path/the/dest/dir' }
let(:safe_destfile) { 'fi\ le.tar.gz' }
it "unpacks a tar file" do
expect(Puppet::Util::Execution).to receive(:execute).with("gzip -dc #{safe_sourcefile} | tar --extract --no-same-owner --directory #{safe_destdir} --file -")
expect(Puppet::Util::Execution).to receive(:execute).with(['find', destdir, '-type', 'd', '-exec', 'chmod', '755', '{}', '+'])
expect(Puppet::Util::Execution).to receive(:execute).with(['find', destdir, '-type', 'f', '-exec', 'chmod', 'u+rw,g+r,a-st', '{}', '+'])
expect(Puppet::Util::Execution).to receive(:execute).with(['chown', '-R', '<owner:group>', destdir])
subject.unpack(sourcefile, destdir, '<owner:group>')
end
it "packs a tar file" do
expect(Puppet::Util::Execution).to receive(:execute).with("tar cf - #{safe_sourcedir} | gzip -c > #{safe_destfile}")
subject.pack(sourcedir, destfile)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/tar/mini_spec.rb | spec/unit/module_tool/tar/mini_spec.rb | require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool::Tar::Mini, :if => (Puppet.features.minitar? and Puppet.features.zlib?) do
let(:sourcefile) { '/the/module.tar.gz' }
let(:destdir) { File.expand_path '/the/dest/dir' }
let(:sourcedir) { '/the/src/dir' }
let(:destfile) { '/the/dest/file.tar.gz' }
let(:minitar) { described_class.new }
class MockFileStatEntry
def initialize(mode = 0100)
@mode = mode
end
end
it "unpacks a tar file with correct permissions" do
entry = unpacks_the_entry(:file_start, 'thefile')
minitar.unpack(sourcefile, destdir, 'uid')
expect(entry.instance_variable_get(:@mode)).to eq(0755)
end
it "does not allow an absolute path" do
unpacks_the_entry(:file_start, '/thefile')
expect {
minitar.unpack(sourcefile, destdir, 'uid')
}.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError,
"Attempt to install file with an invalid path into \"/thefile\" under \"#{destdir}\"")
end
it "does not allow a file to be written outside the destination directory" do
unpacks_the_entry(:file_start, '../../thefile')
expect {
minitar.unpack(sourcefile, destdir, 'uid')
}.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError,
"Attempt to install file with an invalid path into \"#{File.expand_path('/the/thefile')}\" under \"#{destdir}\"")
end
it "does not allow a directory to be written outside the destination directory" do
unpacks_the_entry(:dir, '../../thedir')
expect {
minitar.unpack(sourcefile, destdir, 'uid')
}.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError,
"Attempt to install file with an invalid path into \"#{File.expand_path('/the/thedir')}\" under \"#{destdir}\"")
end
it "unpacks on Windows" do
unpacks_the_entry(:file_start, 'thefile', nil)
entry = minitar.unpack(sourcefile, destdir, 'uid')
# Windows does not use these permissions.
expect(entry.instance_variable_get(:@mode)).to eq(nil)
end
it "packs a tar file" do
writer = double('GzipWriter')
expect(Zlib::GzipWriter).to receive(:open).with(destfile).and_yield(writer)
stats = {:mode => 0222}
expect(Archive::Tar::Minitar).to receive(:pack).with(sourcedir, writer).and_yield(:file_start, 'abc', stats)
minitar.pack(sourcedir, destfile)
end
it "packs a tar file on Windows" do
writer = double('GzipWriter')
expect(Zlib::GzipWriter).to receive(:open).with(destfile).and_yield(writer)
expect(Archive::Tar::Minitar).to receive(:pack).with(sourcedir, writer).
and_yield(:file_start, 'abc', {:entry => MockFileStatEntry.new(nil)})
minitar.pack(sourcedir, destfile)
end
def unpacks_the_entry(type, name, mode = 0100)
reader = double('GzipReader')
expect(Zlib::GzipReader).to receive(:open).with(sourcefile).and_yield(reader)
expect(minitar).to receive(:find_valid_files).with(reader).and_return([name])
entry = MockFileStatEntry.new(mode)
expect(Archive::Tar::Minitar).to receive(:unpack).with(reader, destdir, [name], {:fsync => false}).
and_yield(type, name, {:entry => entry})
entry
end
describe "Extracts tars with long and short pathnames" do
let (:sourcetar) { fixtures('module.tar.gz') }
let (:longfilepath) { "puppetlabs-dsc-1.0.0/lib/puppet_x/dsc_resources/xWebAdministration/DSCResources/MSFT_xWebAppPoolDefaults/MSFT_xWebAppPoolDefaults.schema.mof" }
let (:shortfilepath) { "puppetlabs-dsc-1.0.0/README.md" }
it "unpacks a tar with a short path length" do
extractdir = PuppetSpec::Files.tmpdir('minitar')
minitar.unpack(sourcetar,extractdir,'module')
expect(File).to exist(File.expand_path("#{extractdir}/#{shortfilepath}"))
end
it "unpacks a tar with a long path length" do
extractdir = PuppetSpec::Files.tmpdir('minitar')
minitar.unpack(sourcetar,extractdir,'module')
expect(File).to exist(File.expand_path("#{extractdir}/#{longfilepath}"))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/applications/checksummer_spec.rb | spec/unit/module_tool/applications/checksummer_spec.rb | require 'spec_helper'
require 'puppet/module_tool/applications'
require 'puppet_spec/files'
require 'pathname'
describe Puppet::ModuleTool::Applications::Checksummer do
let(:tmpdir) do
Pathname.new(PuppetSpec::Files.tmpdir('checksummer'))
end
let(:checksums) { Puppet::ModuleTool::Checksums.new(tmpdir).data }
subject do
described_class.run(tmpdir)
end
before do
File.open(tmpdir + 'README', 'w') { |f| f.puts "This is a README!" }
File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changelog!" }
File.open(tmpdir + 'DELETEME', 'w') { |f| f.puts "I've got a really good feeling about this!" }
Dir.mkdir(tmpdir + 'pkg')
File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm unimportant!" }
File.open(tmpdir + 'metadata.json', 'w') { |f| f.puts '{"name": "package-name", "version": "1.0.0"}' }
File.open(tmpdir + 'checksums.json', 'w') { |f| f.puts '{}' }
end
context 'with checksums.json' do
before do
File.open(tmpdir + 'checksums.json', 'w') { |f| f.puts checksums.to_json }
File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" }
File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" }
(tmpdir + 'DELETEME').unlink
end
it 'reports changed files' do
expect(subject).to include 'CHANGES'
end
it 'reports removed files' do
expect(subject).to include 'DELETEME'
end
it 'does not report unchanged files' do
expect(subject).to_not include 'README'
end
it 'does not report build artifacts' do
expect(subject).to_not include 'pkg/build-artifact'
end
it 'does not report checksums.json' do
expect(subject).to_not include 'checksums.json'
end
end
context 'without checksums.json' do
context 'but with metadata.json containing checksums' do
before do
(tmpdir + 'checksums.json').unlink
File.open(tmpdir + 'metadata.json', 'w') { |f| f.puts "{\"checksums\":#{checksums.to_json}}" }
File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" }
File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" }
(tmpdir + 'DELETEME').unlink
end
it 'reports changed files' do
expect(subject).to include 'CHANGES'
end
it 'reports removed files' do
expect(subject).to include 'DELETEME'
end
it 'does not report unchanged files' do
expect(subject).to_not include 'README'
end
it 'does not report build artifacts' do
expect(subject).to_not include 'pkg/build-artifact'
end
it 'does not report checksums.json' do
expect(subject).to_not include 'checksums.json'
end
end
context 'and with metadata.json that does not contain checksums' do
before do
(tmpdir + 'checksums.json').unlink
File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" }
File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" }
(tmpdir + 'DELETEME').unlink
end
it 'fails' do
expect { subject }.to raise_error(ArgumentError, 'No file containing checksums found.')
end
end
context 'and without metadata.json' do
before do
(tmpdir + 'checksums.json').unlink
(tmpdir + 'metadata.json').unlink
File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" }
File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" }
(tmpdir + 'DELETEME').unlink
end
it 'fails' do
expect { subject }.to raise_error(ArgumentError, 'No file containing checksums found.')
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/applications/uninstaller_spec.rb | spec/unit/module_tool/applications/uninstaller_spec.rb | require 'spec_helper'
require 'puppet/module_tool'
require 'tmpdir'
require 'puppet_spec/module_tool/shared_functions'
require 'puppet_spec/module_tool/stub_source'
describe Puppet::ModuleTool::Applications::Uninstaller do
include PuppetSpec::ModuleTool::SharedFunctions
include PuppetSpec::Files
before do
FileUtils.mkdir_p(primary_dir)
FileUtils.mkdir_p(secondary_dir)
end
let(:environment) do
Puppet.lookup(:current_environment).override_with(
:vardir => vardir,
:modulepath => [ primary_dir, secondary_dir ]
)
end
let(:vardir) { tmpdir('uninstaller') }
let(:primary_dir) { File.join(vardir, "primary") }
let(:secondary_dir) { File.join(vardir, "secondary") }
let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new }
let(:module) { 'module-not_installed' }
let(:application) do
opts = options
Puppet::ModuleTool.set_option_defaults(opts)
Puppet::ModuleTool::Applications::Uninstaller.new(self.module, opts)
end
def options
{ :environment => environment }
end
subject { application.run }
context "when the module is not installed" do
it "should fail" do
expect(subject).to include :result => :failure
end
end
context "when the module is installed" do
let(:module) { 'pmtacceptance-stdlib' }
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
before { preinstall('pmtacceptance-apache', '0.0.4') }
it "should uninstall the module" do
expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib")
end
it "should only uninstall the requested module" do
subject[:affected_modules].length == 1
end
it 'should refuse to uninstall in FIPS mode' do
allow(Facter).to receive(:value).with(:fips_enabled).and_return(true)
err = subject[:error][:oneline]
expect(err).to eq("Either the `--ignore_changes` or `--force` argument must be specified to uninstall modules when running in FIPS mode.")
end
context 'in two modulepaths' do
before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) }
it "should fail if a module exists twice in the modpath" do
expect(subject).to include :result => :failure
end
end
context "when options[:version] is specified" do
def options
super.merge(:version => '1.0.0')
end
it "should uninstall the module if the version matches" do
expect(subject[:affected_modules].length).to eq(1)
expect(subject[:affected_modules].first.version).to eq("1.0.0")
end
context 'but not matched' do
def options
super.merge(:version => '2.0.0')
end
it "should not uninstall the module if the version does not match" do
expect(subject).to include :result => :failure
end
end
end
context "when the module metadata is missing" do
before { File.unlink(File.join(primary_dir, 'stdlib', 'metadata.json')) }
it "should not uninstall the module" do
expect(application.run[:result]).to eq(:failure)
end
end
context "when the module has local changes" do
before do
mark_changed(File.join(primary_dir, 'stdlib'))
end
it "should not uninstall the module" do
expect(subject).to include :result => :failure
end
end
context "when uninstalling the module will cause broken dependencies" do
before { preinstall('pmtacceptance-apache', '0.10.0') }
it "should not uninstall the module" do
expect(subject).to include :result => :failure
end
end
context 'with --ignore-changes' do
def options
super.merge(:ignore_changes => true)
end
context 'with local changes' do
before do
mark_changed(File.join(primary_dir, 'stdlib'))
end
it 'overwrites the installed module with the greatest version matching that range' do
expect(subject).to include :result => :success
end
it 'uninstalls in FIPS mode' do
allow(Facter).to receive(:value).with(:fips_enabled).and_return(true)
expect(subject).to include :result => :success
end
end
context 'without local changes' do
it 'overwrites the installed module with the greatest version matching that range' do
expect(subject).to include :result => :success
end
end
end
context "when using the --force flag" do
def options
super.merge(:force => true)
end
context "with local changes" do
before do
mark_changed(File.join(primary_dir, 'stdlib'))
end
it "should ignore local changes" do
expect(subject[:affected_modules].length).to eq(1)
expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib")
end
it 'uninstalls in FIPS mode' do
allow(Facter).to receive(:value).with(:fips_enabled).and_return(true)
expect(subject).to include :result => :success
end
end
context "while depended upon" do
before { preinstall('pmtacceptance-apache', '0.10.0') }
it "should ignore broken dependencies" do
expect(subject[:affected_modules].length).to eq(1)
expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib")
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/applications/unpacker_spec.rb | spec/unit/module_tool/applications/unpacker_spec.rb | require 'spec_helper'
require 'puppet/util/json'
require 'puppet/module_tool/applications'
require 'puppet/file_system'
require 'puppet_spec/modules'
describe Puppet::ModuleTool::Applications::Unpacker do
include PuppetSpec::Files
let(:target) { tmpdir("unpacker") }
let(:module_name) { 'myusername-mytarball' }
let(:filename) { tmpdir("module") + "/module.tar.gz" }
let(:working_dir) { tmpdir("working_dir") }
before :each do
allow(Puppet.settings).to receive(:[])
allow(Puppet.settings).to receive(:[]).with(:module_working_dir).and_return(working_dir)
end
it "should attempt to untar file to temporary location" do
untar = double('Tar')
expect(untar).to receive(:unpack).with(filename, anything, anything) do |src, dest, _|
FileUtils.mkdir(File.join(dest, 'extractedmodule'))
File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file|
file.puts Puppet::Util::Json.dump('name' => module_name, 'version' => '1.0.0')
end
true
end
expect(Puppet::ModuleTool::Tar).to receive(:instance).and_return(untar)
Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target)
expect(File).to be_directory(File.join(target, 'mytarball'))
end
it "should warn about symlinks", :if => Puppet.features.manages_symlinks? do
untar = double('Tar')
expect(untar).to receive(:unpack).with(filename, anything, anything) do |src, dest, _|
FileUtils.mkdir(File.join(dest, 'extractedmodule'))
File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file|
file.puts Puppet::Util::Json.dump('name' => module_name, 'version' => '1.0.0')
end
FileUtils.touch(File.join(dest, 'extractedmodule/tempfile'))
Puppet::FileSystem.symlink(File.join(dest, 'extractedmodule/tempfile'), File.join(dest, 'extractedmodule/tempfile2'))
true
end
expect(Puppet::ModuleTool::Tar).to receive(:instance).and_return(untar)
expect(Puppet).to receive(:warning).with(/symlinks/i)
Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target)
expect(File).to be_directory(File.join(target, 'mytarball'))
end
it "should warn about symlinks in subdirectories", :if => Puppet.features.manages_symlinks? do
untar = double('Tar')
expect(untar).to receive(:unpack).with(filename, anything, anything) do |src, dest, _|
FileUtils.mkdir(File.join(dest, 'extractedmodule'))
File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file|
file.puts Puppet::Util::Json.dump('name' => module_name, 'version' => '1.0.0')
end
FileUtils.mkdir(File.join(dest, 'extractedmodule/manifests'))
FileUtils.touch(File.join(dest, 'extractedmodule/manifests/tempfile'))
Puppet::FileSystem.symlink(File.join(dest, 'extractedmodule/manifests/tempfile'), File.join(dest, 'extractedmodule/manifests/tempfile2'))
true
end
expect(Puppet::ModuleTool::Tar).to receive(:instance).and_return(untar)
expect(Puppet).to receive(:warning).with(/symlinks/i)
Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target)
expect(File).to be_directory(File.join(target, 'mytarball'))
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/applications/installer_spec.rb | spec/unit/module_tool/applications/installer_spec.rb | require 'spec_helper'
require 'puppet/module_tool/applications'
require 'puppet_spec/module_tool/shared_functions'
require 'puppet_spec/module_tool/stub_source'
require 'tmpdir'
describe Puppet::ModuleTool::Applications::Installer, :unless => RUBY_PLATFORM == 'java' do
include PuppetSpec::ModuleTool::SharedFunctions
include PuppetSpec::Files
include PuppetSpec::Fixtures
before do
FileUtils.mkdir_p(primary_dir)
FileUtils.mkdir_p(secondary_dir)
end
let(:vardir) { tmpdir('installer') }
let(:primary_dir) { File.join(vardir, "primary") }
let(:secondary_dir) { File.join(vardir, "secondary") }
let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new }
let(:install_dir) do
dir = double("Puppet::ModuleTool::InstallDirectory")
allow(dir).to receive(:prepare)
allow(dir).to receive(:target).and_return(primary_dir)
dir
end
before do
SemanticPuppet::Dependency.clear_sources
allow_any_instance_of(Puppet::ModuleTool::Applications::Installer).to receive(:module_repository).and_return(remote_source)
end
if Puppet::Util::Platform.windows?
before :each do
Puppet[:module_working_dir] = tmpdir('module_tool_install').gsub('/', '\\')
end
end
def installer(modname, target_dir, options)
Puppet::ModuleTool.set_option_defaults(options)
Puppet::ModuleTool::Applications::Installer.new(modname, target_dir, options)
end
let(:environment) do
Puppet.lookup(:current_environment).override_with(
:vardir => vardir,
:modulepath => [ primary_dir, secondary_dir ]
)
end
context '#run' do
let(:module) { 'pmtacceptance-stdlib' }
def options
{ :environment => environment }
end
let(:application) { installer(self.module, install_dir, options) }
subject { application.run }
it 'installs the specified module' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0')
end
it 'reports a meaningful error if the name is invalid' do
app = installer('ntp', install_dir, options)
results = app.run
expect(results).to include :result => :failure
expect(results[:error][:oneline]).to eq("Could not install 'ntp', did you mean 'puppetlabs-ntp'?")
expect(results[:error][:multiline]).to eq(<<~END.chomp)
Could not install module 'ntp'
The name 'ntp' is invalid
Did you mean `puppet module install puppetlabs-ntp`?
END
end
context 'with a tarball file' do
let(:module) { fixtures('stdlib.tgz') }
it 'installs the specified tarball' do
expect(subject).to include :result => :success
graph_should_include 'puppetlabs-stdlib', nil => v('3.2.0')
end
context 'with --ignore-dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'installs the specified tarball' do
expect(remote_source).not_to receive(:fetch)
expect(subject).to include :result => :success
graph_should_include 'puppetlabs-stdlib', nil => v('3.2.0')
end
end
context 'with dependencies' do
let(:module) { fixtures('java.tgz') }
it 'installs the specified tarball' do
expect(subject).to include :result => :success
graph_should_include 'puppetlabs-java', nil => v('1.0.0')
graph_should_include 'puppetlabs-stdlib', nil => v('4.1.0')
end
context 'with --ignore-dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'installs the specified tarball without dependencies' do
expect(remote_source).not_to receive(:fetch)
expect(subject).to include :result => :success
graph_should_include 'puppetlabs-java', nil => v('1.0.0')
graph_should_include 'puppetlabs-stdlib', nil
end
end
end
end
context 'with dependencies' do
let(:module) { 'pmtacceptance-apache' }
it 'installs the specified module and its dependencies' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0')
end
context 'and using --ignore_dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'installs only the specified module' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'that are already installed' do
context 'and satisfied' do
before { preinstall('pmtacceptance-stdlib', '4.1.0') }
it 'installs only the specified module' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', :path => primary_dir
end
context '(outdated but suitable version)' do
before { preinstall('pmtacceptance-stdlib', '2.4.0') }
it 'installs only the specified module' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.4.0') => v('2.4.0'), :path => primary_dir
end
end
context '(outdated and unsuitable version)' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
it 'installs a version that is compatible with the installed dependencies' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.0.4')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
end
context 'but not satisfied' do
let(:module) { 'pmtacceptance-keystone' }
def options
super.merge(:version => '2.0.0')
end
before { preinstall('pmtacceptance-mysql', '2.1.0') }
it 'installs only the specified module' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-keystone', nil => v('2.0.0')
graph_should_include 'pmtacceptance-mysql', v('2.1.0') => v('2.1.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
end
context 'that are already installed in other modulepath directories' do
before { preinstall('pmtacceptance-stdlib', '1.0.0', :into => secondary_dir) }
let(:module) { 'pmtacceptance-apache' }
context 'without dependency updates' do
it 'installs the module only' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.0.4')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with dependency updates' do
before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) }
it 'installs the module and upgrades dependencies in-place' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0'), :path => secondary_dir
end
end
end
end
context 'with a specified' do
context 'version' do
def options
super.merge(:version => '3.0.0')
end
it 'installs the specified release (or a prerelease thereof)' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('3.0.0')
end
end
context 'version range' do
def options
super.merge(:version => '3.x')
end
it 'installs the greatest available version matching that range' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('3.2.0')
end
end
end
context 'when depended upon' do
before { preinstall('pmtacceptance-keystone', '2.1.0') }
let(:module) { 'pmtacceptance-mysql' }
it 'installs the greatest available version meeting the dependency constraints' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', nil => v('0.9.0')
end
context 'with a --version that can satisfy' do
def options
super.merge(:version => '0.8.0')
end
it 'installs the greatest available version satisfying both constraints' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', nil => v('0.8.0')
end
context 'with an already installed dependency' do
before { preinstall('pmtacceptance-stdlib', '2.6.0') }
def options
super.merge(:version => '0.7.0')
end
it 'installs given version without errors and does not change version of dependency' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', nil => v('0.7.0')
expect(subject[:error]).to be_nil
graph_should_include 'pmtacceptance-stdlib', v('2.6.0') => v('2.6.0')
end
end
end
context 'with a --version that cannot satisfy' do
def options
super.merge(:version => '> 1.0.0')
end
it 'fails to install, since there is no version that can satisfy both constraints' do
expect(subject).to include :result => :failure
end
context 'with unsatisfiable dependencies' do
let(:graph) { double(SemanticPuppet::Dependency::Graph, :modules => ['pmtacceptance-mysql']) }
let(:exception) { SemanticPuppet::Dependency::UnsatisfiableGraph.new(graph, constraint) }
before do
allow(SemanticPuppet::Dependency).to receive(:resolve).and_raise(exception)
end
context 'with known constraint' do
let(:constraint) { 'pmtacceptance-mysql' }
it 'prints a detailed error containing the modules that would not be satisfied' do
expect(subject[:error]).to include(:multiline)
expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (> 1.0.0)")
expect(subject[:error][:multiline]).to include("The requested version cannot satisfy one or more of the following installed modules:")
expect(subject[:error][:multiline]).to include("pmtacceptance-keystone, expects 'pmtacceptance-mysql': >=0.6.1 <1.0.0")
expect(subject[:error][:multiline]).to include("Use `puppet module install 'pmtacceptance-mysql' --ignore-dependencies` to install only this module")
end
end
context 'with missing constraint' do
let(:constraint) { nil }
it 'prints the generic error message' do
expect(subject[:error]).to include(:multiline)
expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (> 1.0.0)")
expect(subject[:error][:multiline]).to include("The requested version cannot satisfy all dependencies")
end
end
context 'with unknown constraint' do
let(:constraint) { 'another' }
it 'prints the generic error message' do
expect(subject[:error]).to include(:multiline)
expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (> 1.0.0)")
expect(subject[:error][:multiline]).to include("The requested version cannot satisfy all dependencies")
end
end
end
context 'with --ignore-dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'fails to install, since ignore_dependencies should still respect dependencies from installed modules' do
expect(subject).to include :result => :failure
end
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'installs the greatest available version, ignoring dependencies' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', nil => v('2.1.0')
end
end
context 'with an already installed dependency' do
let(:graph) {
double(SemanticPuppet::Dependency::Graph,
:dependencies => {
'pmtacceptance-mysql' => {
:version => '2.1.0'
}
},
:modules => ['pmtacceptance-mysql'],
:unsatisfied => 'pmtacceptance-stdlib'
)
}
let(:unsatisfiable_graph_exception) { SemanticPuppet::Dependency::UnsatisfiableGraph.new(graph) }
before do
allow(SemanticPuppet::Dependency).to receive(:resolve).and_raise(unsatisfiable_graph_exception)
allow(unsatisfiable_graph_exception).to receive(:respond_to?).and_return(true)
allow(unsatisfiable_graph_exception).to receive(:unsatisfied).and_return(graph.unsatisfied)
preinstall('pmtacceptance-stdlib', '2.6.0')
end
def options
super.merge(:version => '2.1.0')
end
it 'fails to install and outputs a multiline error containing the versions, expectations and workaround' do
expect(subject).to include :result => :failure
expect(subject[:error]).to include(:multiline)
expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (v2.1.0)")
expect(subject[:error][:multiline]).to include("The requested version cannot satisfy one or more of the following installed modules:")
expect(subject[:error][:multiline]).to include("pmtacceptance-stdlib, installed: 2.6.0, expected: >= 2.2.1")
expect(subject[:error][:multiline]).to include("Use `puppet module install 'pmtacceptance-mysql' --ignore-dependencies` to install only this module")
end
end
end
end
context 'when already installed' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
context 'but matching the requested version' do
it 'does nothing, since the installed version satisfies' do
expect(subject).to include :result => :noop
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'does reinstall the module' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
context 'with local changes' do
before do
release = application.send(:installed_modules)['pmtacceptance-stdlib']
mark_changed(release.mod.path)
end
it 'does nothing, since local changes do not affect that' do
expect(subject).to include :result => :noop
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'does reinstall the module, since --force ignores local changes' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
end
end
context 'but not matching the requested version' do
def options
super.merge(:version => '2.x')
end
it 'fails to install the module, since it is already installed' do
expect(subject).to include :result => :failure
expect(subject[:error]).to include :oneline => "'pmtacceptance-stdlib' (v2.x) requested; 'pmtacceptance-stdlib' (v1.0.0) already installed"
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'installs the greatest version matching the new version range' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('2.6.0')
end
end
end
end
context 'when a module with the same name is already installed' do
let(:module) { 'pmtacceptance-stdlib' }
before { preinstall('puppetlabs-stdlib', '4.1.0') }
it 'fails to install, since two modules with the same name cannot be installed simultaneously' do
expect(subject).to include :result => :failure
end
context 'using --force' do
def options
super.merge(:force => true)
end
it 'overwrites the existing module with the greatest version of the requested module' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0')
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool/applications/upgrader_spec.rb | spec/unit/module_tool/applications/upgrader_spec.rb | require 'spec_helper'
require 'puppet/module_tool/applications'
require 'puppet_spec/module_tool/shared_functions'
require 'puppet_spec/module_tool/stub_source'
require 'tmpdir'
describe Puppet::ModuleTool::Applications::Upgrader do
include PuppetSpec::ModuleTool::SharedFunctions
include PuppetSpec::Files
before do
FileUtils.mkdir_p(primary_dir)
FileUtils.mkdir_p(secondary_dir)
end
let(:vardir) { tmpdir('upgrader') }
let(:primary_dir) { File.join(vardir, "primary") }
let(:secondary_dir) { File.join(vardir, "secondary") }
let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new }
let(:environment) do
Puppet.lookup(:current_environment).override_with(
:vardir => vardir,
:modulepath => [ primary_dir, secondary_dir ]
)
end
before do
SemanticPuppet::Dependency.clear_sources
allow_any_instance_of(Puppet::ModuleTool::Applications::Upgrader).to receive(:module_repository).and_return(remote_source)
end
if Puppet::Util::Platform.windows?
before :each do
allow(Puppet.settings).to receive(:[])
allow(Puppet.settings).to receive(:[]).with(:module_working_dir).and_return(Dir.mktmpdir('upgradertmp'))
end
end
def upgrader(name, options = {})
Puppet::ModuleTool.set_option_defaults(options)
Puppet::ModuleTool::Applications::Upgrader.new(name, options)
end
describe '#run' do
let(:module) { 'pmtacceptance-stdlib' }
def options
{ :environment => environment }
end
let(:application) { upgrader(self.module, options) }
subject { application.run }
it 'fails if the module is not already installed' do
expect(subject).to include :result => :failure
expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}'; module is not installed"
end
context 'for an installed module' do
context 'with only one version' do
before { preinstall('puppetlabs-oneversion', '0.0.1') }
let(:module) { 'puppetlabs-oneversion' }
it 'declines to upgrade' do
expect(subject).to include :result => :noop
expect(subject[:error][:multiline]).to match(/already the latest version/)
end
end
context 'without dependencies' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
context 'without options' do
it 'properly upgrades the module to the greatest version' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
context 'with version range' do
def options
super.merge(:version => '3.x')
end
context 'not matching the installed version' do
it 'properly upgrades the module to the greatest version within that range' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('3.2.0')
end
end
context 'matching the installed version' do
context 'with more recent version' do
before { preinstall('pmtacceptance-stdlib', '3.0.0')}
it 'properly upgrades the module to the greatest version within that range' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('3.0.0') => v('3.2.0')
end
end
context 'without more recent version' do
before { preinstall('pmtacceptance-stdlib', '3.2.0')}
context 'without options' do
it 'declines to upgrade' do
expect(subject).to include :result => :noop
expect(subject[:error][:multiline]).to match(/already the latest version/)
end
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'overwrites the installed module with the greatest version matching that range' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('3.2.0') => v('3.2.0')
end
end
end
end
end
end
context 'that is depended upon' do
# pmtacceptance-keystone depends on pmtacceptance-mysql >=0.6.1 <1.0.0
before { preinstall('pmtacceptance-keystone', '2.1.0') }
before { preinstall('pmtacceptance-mysql', '0.9.0') }
let(:module) { 'pmtacceptance-mysql' }
context 'and out of date' do
before { preinstall('pmtacceptance-mysql', '0.8.0') }
it 'properly upgrades to the greatest version matching the dependency' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', v('0.8.0') => v('0.9.0')
end
end
context 'and up to date' do
it 'declines to upgrade' do
expect(subject).to include :result => :failure
end
end
context 'when specifying a violating version range' do
def options
super.merge(:version => '2.1.0')
end
it 'fails to upgrade the module' do
# TODO: More helpful error message?
expect(subject).to include :result => :failure
expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}' (v0.9.0 -> v2.1.0); no version satisfies all dependencies"
end
context 'using --force' do
def options
super.merge(:force => true)
end
it 'overwrites the installed module with the specified version' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', v('0.9.0') => v('2.1.0')
end
end
end
end
context 'with local changes' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
before do
release = application.send(:installed_modules)['pmtacceptance-stdlib']
mark_changed(release.mod.path)
end
it 'fails to upgrade' do
expect(subject).to include :result => :failure
expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}'; module has had changes made locally"
end
context 'with --ignore-changes' do
def options
super.merge(:ignore_changes => true)
end
it 'overwrites the installed module with the greatest version matching that range' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
end
context 'with dependencies' do
context 'that are unsatisfied' do
def options
super.merge(:version => '0.1.1')
end
before { preinstall('pmtacceptance-apache', '0.0.3') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module and installs the missing dependencies' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.1.1')
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0'), :action => :install
end
end
context 'with older major versions' do
# pmtacceptance-apache 0.0.4 has no dependency on pmtacceptance-stdlib
# the next available version (0.1.1) and all subsequent versions depend on pmtacceptance-stdlib >= 2.2.1
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
let(:module) { 'pmtacceptance-apache' }
it 'refuses to upgrade the installed dependency to a new major version, but upgrades the module to the greatest compatible version' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.0.4')
end
context 'using --ignore_dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'upgrades the module to the greatest available version' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
end
end
end
context 'with satisfying major versions' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '2.0.0') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module and its dependencies to their greatest compatible versions' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0')
end
end
context 'with satisfying versions' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '2.4.0') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module to the greatest available version' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with current versions' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '2.6.0') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module to the greatest available version' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with shared dependencies' do
# bacula 0.0.3 depends on stdlib >= 2.2.0 and pmtacceptance/mysql >= 1.0.0
# bacula 0.0.2 depends on stdlib >= 2.2.0 and pmtacceptance/mysql >= 0.0.1
# bacula 0.0.1 depends on stdlib >= 2.2.0
# keystone 2.1.0 depends on pmtacceptance/stdlib >= 2.5.0 and pmtacceptance/mysql >=0.6.1 <1.0.0
before { preinstall('pmtacceptance-bacula', '0.0.1') }
before { preinstall('pmtacceptance-mysql', '0.9.0') }
before { preinstall('pmtacceptance-keystone', '2.1.0') }
let(:module) { 'pmtacceptance-bacula' }
it 'upgrades the module to the greatest version compatible with all other installed modules' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-bacula', v('0.0.1') => v('0.0.2')
end
context 'using --force' do
def options
super.merge(:force => true)
end
it 'upgrades the module to the greatest version available' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-bacula', v('0.0.1') => v('0.0.3')
end
end
end
context 'in other modulepath directories' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '1.0.0', :into => secondary_dir) }
let(:module) { 'pmtacceptance-apache' }
context 'with older major versions' do
it 'upgrades the module to the greatest version compatible with the installed modules' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.0.4')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with satisfying major versions' do
before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) }
it 'upgrades the module and its dependencies to their greatest compatible versions, in-place' do
expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0'), :path => secondary_dir
end
end
end
end
end
context 'when in FIPS mode...' do
it 'module unpgrader refuses to run' do
allow(Facter).to receive(:value).with(:fips_enabled).and_return(true)
expect { application.run }.to raise_error(/Module upgrade is prohibited in FIPS mode/)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/agent/disabler_spec.rb | spec/unit/agent/disabler_spec.rb | require 'spec_helper'
require 'puppet/agent'
require 'puppet/agent/locker'
class DisablerTester
include Puppet::Agent::Disabler
end
describe Puppet::Agent::Disabler do
before do
@disabler = DisablerTester.new
end
## These tests are currently very implementation-specific, and they rely heavily on
## having access to the "disable_lockfile" method. However, I've made this method private
## because it really shouldn't be exposed outside of our implementation... therefore
## these tests have to use a lot of ".send" calls. They should probably be cleaned up
## but for the moment I wanted to make sure not to lose any of the functionality of
## the tests. --cprice 2012-04-16
it "should use an JsonLockfile instance as its disable_lockfile" do
expect(@disabler.send(:disable_lockfile)).to be_instance_of(Puppet::Util::JsonLockfile)
end
it "should use puppet's :agent_disabled_lockfile' setting to determine its lockfile path" do
lockfile = File.expand_path("/my/lock.disabled")
Puppet[:agent_disabled_lockfile] = lockfile
lock = Puppet::Util::JsonLockfile.new(lockfile)
expect(Puppet::Util::JsonLockfile).to receive(:new).with(lockfile).and_return(lock)
@disabler.send(:disable_lockfile)
end
it "should reuse the same lock file each time" do
expect(@disabler.send(:disable_lockfile)).to equal(@disabler.send(:disable_lockfile))
end
it "should lock the file when disabled" do
expect(@disabler.send(:disable_lockfile)).to receive(:lock)
@disabler.disable
end
it "should unlock the file when enabled" do
expect(@disabler.send(:disable_lockfile)).to receive(:unlock)
@disabler.enable
end
it "should check the lock if it is disabled" do
expect(@disabler.send(:disable_lockfile)).to receive(:locked?)
@disabler.disabled?
end
it "should report the disable message when disabled" do
Puppet[:agent_disabled_lockfile] = PuppetSpec::Files.tmpfile("lock")
msg = "I'm busy, go away"
@disabler.disable(msg)
expect(@disabler.disable_message).to eq(msg)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/agent/locker_spec.rb | spec/unit/agent/locker_spec.rb | require 'spec_helper'
require 'puppet/agent'
require 'puppet/agent/locker'
class LockerTester
include Puppet::Agent::Locker
end
describe Puppet::Agent::Locker do
before do
@locker = LockerTester.new
end
## These tests are currently very implementation-specific, and they rely heavily on
## having access to the lockfile object. However, I've made this method private
## because it really shouldn't be exposed outside of our implementation... therefore
## these tests have to use a lot of ".send" calls. They should probably be cleaned up
## but for the moment I wanted to make sure not to lose any of the functionality of
## the tests. --cprice 2012-04-16
it "should use a Pidlock instance as its lockfile" do
expect(@locker.send(:lockfile)).to be_instance_of(Puppet::Util::Pidlock)
end
it "should use puppet's agent_catalog_run_lockfile' setting to determine its lockfile path" do
lockfile = File.expand_path("/my/lock")
Puppet[:agent_catalog_run_lockfile] = lockfile
lock = Puppet::Util::Pidlock.new(lockfile)
expect(Puppet::Util::Pidlock).to receive(:new).with(lockfile).and_return(lock)
@locker.send(:lockfile)
end
it "#lockfile_path provides the path to the lockfile" do
lockfile = File.expand_path("/my/lock")
Puppet[:agent_catalog_run_lockfile] = lockfile
expect(@locker.lockfile_path).to eq(File.expand_path("/my/lock"))
end
it "should reuse the same lock file each time" do
expect(@locker.send(:lockfile)).to equal(@locker.send(:lockfile))
end
it "should have a method that yields when a lock is attained" do
expect(@locker.send(:lockfile)).to receive(:lock).and_return(true)
yielded = false
@locker.lock do
yielded = true
end
expect(yielded).to be_truthy
end
it "should return the block result when the lock method successfully locked" do
expect(@locker.send(:lockfile)).to receive(:lock).and_return(true)
expect(@locker.lock { :result }).to eq(:result)
end
it "should raise LockError when the lock method does not receive the lock" do
expect(@locker.send(:lockfile)).to receive(:lock).and_return(false)
expect { @locker.lock {} }.to raise_error(Puppet::LockError)
end
it "should not yield when the lock method does not receive the lock" do
expect(@locker.send(:lockfile)).to receive(:lock).and_return(false)
yielded = false
expect { @locker.lock { yielded = true } }.to raise_error(Puppet::LockError)
expect(yielded).to be_falsey
end
it "should not unlock when a lock was not received" do
expect(@locker.send(:lockfile)).to receive(:lock).and_return(false)
expect(@locker.send(:lockfile)).not_to receive(:unlock)
expect { @locker.lock {} }.to raise_error(Puppet::LockError)
end
it "should unlock after yielding upon obtaining a lock" do
allow(@locker.send(:lockfile)).to receive(:lock).and_return(true)
expect(@locker.send(:lockfile)).to receive(:unlock)
@locker.lock {}
end
it "should unlock after yielding upon obtaining a lock, even if the block throws an exception" do
allow(@locker.send(:lockfile)).to receive(:lock).and_return(true)
expect(@locker.send(:lockfile)).to receive(:unlock)
expect { @locker.lock { raise "foo" } }.to raise_error(RuntimeError)
end
it "should be considered running if the lockfile is locked" do
expect(@locker.send(:lockfile)).to receive(:locked?).and_return(true)
expect(@locker).to be_running
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/generate_spec.rb | spec/unit/face/generate_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/face'
describe Puppet::Face[:generate, :current] do
include PuppetSpec::Files
let(:genface) { Puppet::Face[:generate, :current] }
# * Format is 'pcore' by default
# * Format is accepted as 'pcore'
# * Any format expect 'pcore' is an error
# * Produces output to '<envroot>/.resource_types'
# * Produces all types found on the module path (that are not in puppet core)
# * Output files match input
# * Removes files for which there is no input
# * Updates a pcore file if it is out of date
# * The --force flag overwrite the output even if it is up to date
# * Environment is set with --environment (setting) (not tested explicitly)
# Writes output for:
# - isomorphic
# - parameters
# - properties
# - title patterns
# - type information is written when the type is X, Y, or Z
#
# Additional features
# - blacklist? whitelist? types to exclude/include
# - generate one resource type (somewhere on modulepath)
# - output to directory of choice
# - clean, clean the output directory (similar to force)
#
[:types].each do |action|
it { is_expected.to be_action(action) }
it { is_expected.to respond_to(action) }
end
context "when used from an interactive terminal" do
before :each do
from_an_interactive_terminal
end
context "in an environment with two modules containing resource types" do
let(:dir) do
dir_containing('environments', { 'testing_generate' => {
'environment.conf' => "modulepath = modules",
'manifests' => { 'site.pp' => "" },
'modules' => {
'm1' => {
'lib' => { 'puppet' => { 'type' => {
'test1.rb' => <<-EOF
module Puppet
Type.newtype(:test1) do
@doc = "Docs for resource"
newproperty(:message) do
desc "Docs for 'message' property"
end
newparam(:name) do
desc "Docs for 'name' parameter"
isnamevar
end
end; end
EOF
} }
},
},
'm2' => {
'lib' => { 'puppet' => { 'type' => {
'test2.rb' => <<-EOF
module Puppet
Type.newtype(:test2) do
@doc = "Docs for resource"
newproperty(:message) do
desc "Docs for 'message' property"
end
newparam(:name) do
desc "Docs for 'name' parameter"
isnamevar
end
end;end
EOF
} } },
}
}}})
end
let(:modulepath) do
File.join(dir, 'testing_generate', 'modules')
end
let(:m1) do
File.join(modulepath, 'm1')
end
let(:m2) do
File.join(modulepath, 'm2')
end
let(:outputdir) do
File.join(dir, 'testing_generate', '.resource_types')
end
around(:each) do |example|
Puppet.settings.initialize_global_settings
Puppet[:manifest] = ''
loader = Puppet::Environments::Directories.new(dir, [])
Puppet.override(:environments => loader) do
Puppet.override(:current_environment => loader.get('testing_generate')) do
example.run
end
end
end
it 'error if format is given as something other than pcore' do
expect {
genface.types(:format => 'json')
}.to raise_exception(ArgumentError, /'json' is not a supported format for type generation/)
end
it 'accepts --format pcore as a format' do
expect {
genface.types(:format => 'pcore')
}.not_to raise_error
end
it 'sets pcore as the default format' do
expect(Puppet::Generate::Type).to receive(:find_inputs).with(:pcore).and_return([])
genface.types()
end
it 'finds all files to generate types for' do
# using expects and returning what the side effect should have been
# (There is no way to call the original when mocking expected parameters).
input1 = Puppet::Generate::Type::Input.new(m1, File.join(m1, 'lib', 'puppet', 'type', 'test1.rb'), :pcore)
input2 = Puppet::Generate::Type::Input.new(m1, File.join(m2, 'lib', 'puppet', 'type', 'test2.rb'), :pcore)
expect(Puppet::Generate::Type::Input).to receive(:new).with(m1, File.join(m1, 'lib', 'puppet', 'type', 'test1.rb'), :pcore).and_return(input1)
expect(Puppet::Generate::Type::Input).to receive(:new).with(m2, File.join(m2, 'lib', 'puppet', 'type', 'test2.rb'), :pcore).and_return(input2)
genface.types
end
it 'creates output directory <env>/.resource_types/ if it does not exist' do
expect(Puppet::FileSystem.exist?(outputdir)).to be(false)
genface.types
expect(Puppet::FileSystem.dir_exist?(outputdir)).to be(true)
end
it 'creates output with matching names for each input' do
expect(Puppet::FileSystem.exist?(outputdir)).to be(false)
genface.types
children = Puppet::FileSystem.children(outputdir).map {|p| Puppet::FileSystem.basename_string(p) }
expect(children.sort).to eql(['test1.pp', 'test2.pp'])
end
it 'tolerates that <env>/.resource_types/ directory exists' do
Puppet::FileSystem.mkpath(outputdir)
expect(Puppet::FileSystem.exist?(outputdir)).to be(true)
genface.types
expect(Puppet::FileSystem.dir_exist?(outputdir)).to be(true)
end
it 'errors if <env>/.resource_types exists and is not a directory' do
expect(Puppet::FileSystem.exist?(outputdir)).to be(false) # assert it is not already there
Puppet::FileSystem.touch(outputdir)
expect(Puppet::FileSystem.exist?(outputdir)).to be(true)
expect(Puppet::FileSystem.directory?(outputdir)).to be(false)
expect {
genface.types
}.to raise_error(ArgumentError, /The output directory '#{outputdir}' exists and is not a directory/)
end
it 'does not overwrite if files exists and are up to date' do
# create them (first run)
genface.types
stats_before = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))]
# generate again
genface.types
stats_after = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))]
expect(stats_before <=> stats_after).to be(0)
end
it 'overwrites if files exists that are not up to date while keeping up to date files' do
# create them (first run)
genface.types
stats_before = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))]
# fake change in input test1 - sorry about the sleep (which there was a better way to change the modtime
sleep(1)
Puppet::FileSystem.touch(File.join(m1, 'lib', 'puppet', 'type', 'test1.rb'))
# generate again
genface.types
# assert that test1 was overwritten (later) but not test2 (same time)
stats_after = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))]
expect(stats_before[1] <=> stats_after[1]).to be(0)
expect(stats_before[0] <=> stats_after[0]).to be(-1)
end
it 'overwrites all files when called with --force' do
# create them (first run)
genface.types
stats_before = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))]
# generate again
sleep(1) # sorry, if there is no delay the stats will be the same
genface.types(:force => true)
stats_after = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))]
expect(stats_before <=> stats_after).to be(-1)
end
it 'removes previously generated files from output when there is no input for it' do
# create them (first run)
genface.types
stat_before = Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))
# remove input
Puppet::FileSystem.unlink(File.join(m1, 'lib', 'puppet', 'type', 'test1.rb'))
# generate again
genface.types
# assert that test1 was deleted but not test2 (same time)
expect(Puppet::FileSystem.exist?(File.join(outputdir, 'test1.pp'))).to be(false)
stats_after = Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))
expect(stat_before <=> stats_after).to be(0)
end
end
context "in an environment with a faulty type" do
let(:dir) do
dir_containing('environments', { 'testing_generate2' => {
'environment.conf' => "modulepath = modules",
'manifests' => { 'site.pp' => "" },
'modules' => {
'm3' => {
'lib' => { 'puppet' => { 'type' => {
'test3.rb' => <<-EOF
module Puppet
Type.newtype(:test3) do
@doc = "Docs for resource"
def self.title_patterns
identity = lambda {|x| x}
[
[
/^(.*)_(.*)$/,
[
[:name, identity ]
]
]
]
end
newproperty(:message) do
desc "Docs for 'message' property"
end
newparam(:name) do
desc "Docs for 'name' parameter"
isnamevar
end
end; end
EOF
} }
}
}
}}})
end
let(:modulepath) do
File.join(dir, 'testing_generate2', 'modules')
end
let(:m3) do
File.join(modulepath, 'm3')
end
around(:each) do |example|
Puppet.settings.initialize_global_settings
Puppet[:manifest] = ''
loader = Puppet::Environments::Directories.new(dir, [])
Puppet.override(:environments => loader) do
Puppet.override(:current_environment => loader.get('testing_generate2')) do
example.run
end
end
end
it 'fails when using procs for title patterns' do
expect {
genface.types(:format => 'pcore')
}.to exit_with(1)
end
end
end
def from_an_interactive_terminal
allow(STDIN).to receive(:tty?).and_return(true)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/epp_face_spec.rb | spec/unit/face/epp_face_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/face'
describe Puppet::Face[:epp, :current] do
include PuppetSpec::Files
let(:eppface) { Puppet::Face[:epp, :current] }
context "validate" do
context "from an interactive terminal" do
before :each do
from_an_interactive_terminal
end
it "validates the template referenced as an absolute file" do
template_name = 'template1.epp'
dir = dir_containing('templates', { template_name => "<%= |$a $b |%>" })
template = File.join(dir, template_name)
expect { eppface.validate(template) }.to raise_exception(Puppet::Error, /Errors while validating epp/)
end
it "runs error free when there are no validation errors from an absolute file" do
template_name = 'template1.epp'
dir = dir_containing('templates', { template_name => "just text" })
template = File.join(dir, template_name)
expect { eppface.validate(template) }.to_not raise_exception()
end
it "reports missing files" do
expect do
eppface.validate("missing.epp")
end.to raise_error(Puppet::Error, /One or more file\(s\) specified did not exist.*missing\.epp/m)
end
context "in an environment with templates" do
let(:dir) do
dir_containing('environments', { 'production' => { 'modules' => {
'm1' => { 'templates' => {
'greetings.epp' => "<% |$subject = world| %>hello <%= $subject -%>",
'broken.epp' => "<% | $a $b | %> I am broken",
'broken2.epp' => "<% | $a $b | %> I am broken too"
}},
'm2' => { 'templates' => {
'goodbye.epp' => "<% | $subject = world |%>goodbye <%= $subject -%>",
'broken3.epp' => "<% | $a $b | %> I am broken too"
}}
}}})
end
around(:each) do |example|
Puppet.settings.initialize_global_settings
loader = Puppet::Environments::Directories.new(dir, [])
Puppet.override(:environments => loader) do
example.run
end
end
it "parses supplied template files in different modules of a directory environment" do
expect(eppface.validate('m1/greetings.epp')).to be_nil
expect(eppface.validate('m2/goodbye.epp')).to be_nil
end
it "finds errors in supplied template file in the context of a directory environment" do
expect { eppface.validate('m1/broken.epp') }.to raise_exception(Puppet::Error, /Errors while validating epp/)
expect(@logs.join).to match(/Syntax error at 'b'/)
end
it "stops on first error by default" do
expect { eppface.validate('m1/broken.epp', 'm1/broken2.epp') }.to raise_exception(Puppet::Error, /Errors while validating epp/)
expect(@logs.join).to match(/Syntax error at 'b'.*broken\.epp/)
expect(@logs.join).to_not match(/Syntax error at 'b'.*broken2\.epp/)
end
it "continues after error when --continue_on_error is given" do
expect { eppface.validate('m1/broken.epp', 'm1/broken2.epp', :continue_on_error => true) }.to raise_exception(Puppet::Error, /Errors while validating epp/)
expect(@logs.join).to match(/Syntax error at 'b'.*broken\.epp/)
expect(@logs.join).to match(/Syntax error at 'b'.*broken2\.epp/)
end
it "validates all templates in the environment" do
pending "NOT IMPLEMENTED YET"
expect { eppface.validate(:continue_on_error => true) }.to raise_exception(Puppet::Error, /Errors while validating epp/)
expect(@logs.join).to match(/Syntax error at 'b'.*broken\.epp/)
expect(@logs.join).to match(/Syntax error at 'b'.*broken2\.epp/)
expect(@logs.join).to match(/Syntax error at 'b'.*broken3\.epp/)
end
end
end
it "validates the contents of STDIN when no files given and STDIN is not a tty" do
from_a_piped_input_of("<% | $a $oh_no | %> I am broken")
expect { eppface.validate() }.to raise_exception(Puppet::Error, /Errors while validating epp/)
expect(@logs.join).to match(/Syntax error at 'oh_no'/)
end
it "validates error free contents of STDIN when no files given and STDIN is not a tty" do
from_a_piped_input_of("look, just text")
expect(eppface.validate()).to be_nil
end
end
context "dump" do
it "prints the AST of a template given with the -e option" do
expect(eppface.dump({ :e => 'hello world' })).to eq("(lambda (epp (block\n (render-s 'hello world')\n)))\n")
end
it "prints the AST of a template given as an absolute file" do
template_name = 'template1.epp'
dir = dir_containing('templates', { template_name => "hello world" })
template = File.join(dir, template_name)
expect(eppface.dump(template)).to eq("(lambda (epp (block\n (render-s 'hello world')\n)))\n")
end
it "adds a header between dumps by default" do
template_name1 = 'template1.epp'
template_name2 = 'template2.epp'
dir = dir_containing('templates', { template_name1 => "hello world", template_name2 => "hello again"} )
template1 = File.join(dir, template_name1)
template2 = File.join(dir, template_name2)
# Do not move the text block, the left margin and indentation matters
expect(eppface.dump(template1, template2)).to eq( <<-"EOT" )
--- #{template1}
(lambda (epp (block
(render-s 'hello world')
)))
--- #{template2}
(lambda (epp (block
(render-s 'hello again')
)))
EOT
end
it "dumps non validated content when given --no-validate" do
template_name = 'template1.epp'
dir = dir_containing('templates', { template_name => "<% 1 2 3 %>" })
template = File.join(dir, template_name)
expect(eppface.dump(template, :validate => false)).to eq("(lambda (epp (block\n 1\n 2\n 3\n)))\n")
end
it "validated content when given --validate" do
template_name = 'template1.epp'
dir = dir_containing('templates', { template_name => "<% 1 2 3 %>" })
template = File.join(dir, template_name)
expect(eppface.dump(template, :validate => true)).to eq("")
expect(@logs.join).to match(/This Literal Integer has no effect.*\(file: .*\/template1\.epp, line: 1, column: 4\)/)
end
it "validated content by default" do
template_name = 'template1.epp'
dir = dir_containing('templates', { template_name => "<% 1 2 3 %>" })
template = File.join(dir, template_name)
expect(eppface.dump(template)).to eq("")
expect(@logs.join).to match(/This Literal Integer has no effect.*\(file: .*\/template1\.epp, line: 1, column: 4\)/)
end
it "informs the user of files that don't exist" do
expected_message = /One or more file\(s\) specified did not exist:\n\s*does_not_exist_here\.epp/m
expect { eppface.dump('does_not_exist_here.epp') }.to raise_exception(Puppet::Error, expected_message)
end
it "dumps the AST of STDIN when no files given and STDIN is not a tty" do
from_a_piped_input_of("hello world")
expect(eppface.dump()).to eq("(lambda (epp (block\n (render-s 'hello world')\n)))\n")
end
it "logs an error if the input cannot be parsed even if validation is off" do
from_a_piped_input_of("<% |$a $b| %> oh no")
expect(eppface.dump(:validate => false)).to eq("")
expect(@logs[0].message).to match(/Syntax error at 'b'/)
expect(@logs[0].level).to eq(:err)
end
context "using 'pn' format" do
it "prints the AST of the given expression in PN format" do
expect(eppface.dump({ :format => 'pn', :e => 'hello world' })).to eq(
'(lambda {:body [(epp (render-s "hello world"))]})')
end
it "pretty prints the AST of the given expression in PN format when --pretty is given" do
expect(eppface.dump({ :pretty => true, :format => 'pn', :e => 'hello world' })).to eq(<<-RESULT.unindent[0..-2])
(lambda
{
:body [
(epp
(render-s
"hello world"))]})
RESULT
end
end
context "using 'json' format" do
it "prints the AST of the given expression in JSON based on the PN format" do
expect(eppface.dump({ :format => 'json', :e => 'hello world' })).to eq(
'{"^":["lambda",{"#":["body",[{"^":["epp",{"^":["render-s","hello world"]}]}]]}]}')
end
it "pretty prints the AST of the given expression in JSON based on the PN format when --pretty is given" do
expect(eppface.dump({ :pretty => true, :format => 'json', :e => 'hello world' })).to eq(<<-RESULT.unindent[0..-2])
{
"^": [
"lambda",
{
"#": [
"body",
[
{
"^": [
"epp",
{
"^": [
"render-s",
"hello world"
]
}
]
}
]
]
}
]
}
RESULT
end
end
end
context "render" do
it "renders input from stdin" do
from_a_piped_input_of("hello world")
expect(eppface.render()).to eq("hello world")
end
it "renders input from command line" do
expect(eppface.render(:e => 'hello world')).to eq("hello world")
end
it "renders input from an absolute file" do
template_name = 'template1.epp'
dir = dir_containing('templates', { template_name => "absolute world" })
template = File.join(dir, template_name)
expect(eppface.render(template)).to eq("absolute world")
end
it "renders expressions" do
expect(eppface.render(:e => '<% $x = "mr X"%>hello <%= $x %>')).to eq("hello mr X")
end
it "adds values given in a puppet hash given on command line with --values" do
expect(eppface.render(:e => 'hello <%= $x %>', :values => '{x => "mr X"}')).to eq("hello mr X")
end
it "adds fully qualified values given in a puppet hash given on command line with --values" do
expect(eppface.render(:e => 'hello <%= $mr::x %>', :values => '{mr::x => "mr X"}')).to eq("hello mr X")
end
it "adds fully qualified values with leading :: given in a puppet hash given on command line with --values" do
expect(eppface.render(:e => 'hello <%= $::mr %>', :values => '{"::mr" => "mr X"}')).to eq("hello mr X")
end
it "adds values given in a puppet hash produced by a .pp file given with --values_file" do
file_name = 'values.pp'
dir = dir_containing('values', { file_name => '{x => "mr X"}' })
values_file = File.join(dir, file_name)
expect(eppface.render(:e => 'hello <%= $x %>', :values_file => values_file)).to eq("hello mr X")
end
it "adds values given in a yaml hash given with --values_file" do
file_name = 'values.yaml'
dir = dir_containing('values', { file_name => "---\n x: 'mr X'" })
values_file = File.join(dir, file_name)
expect(eppface.render(:e => 'hello <%= $x %>', :values_file => values_file)).to eq("hello mr X")
end
it "merges values from values file and command line with command line having higher precedence" do
file_name = 'values.yaml'
dir = dir_containing('values', { file_name => "---\n x: 'mr X'\n word: 'goodbye'" })
values_file = File.join(dir, file_name)
expect(eppface.render(:e => '<%= $word %> <%= $x %>',
:values_file => values_file,
:values => '{x => "mr Y"}')
).to eq("goodbye mr Y")
end
it "sets $facts" do
expect(eppface.render({ :e => 'facts is hash: <%= $facts =~ Hash %>' })).to eql("facts is hash: true")
end
it "sets $trusted" do
expect(eppface.render({ :e => 'trusted is hash: <%= $trusted =~ Hash %>' })).to eql("trusted is hash: true")
end
it 'initializes the 4x loader' do
expect(eppface.render({ :e => <<-EPP.unindent })).to eql("\nString\n\nInteger\n\nBoolean\n")
<% $data = [type('a',generalized), type(2,generalized), type(true,generalized)] -%>
<% $data.each |$value| { %>
<%= $value %>
<% } -%>
EPP
end
it "facts can be added to" do
expect(eppface.render({
:facts => {'the_crux' => 'biscuit'},
:e => '<%= $facts[the_crux] %>',
})).to eql("biscuit")
end
it "facts can be overridden" do
expect(eppface.render({
:facts => {'os' => {'name' => 'Merwin'} },
:e => '<%= $facts[os][name] %>',
})).to eql("Merwin")
end
context "in an environment with templates" do
let(:dir) do
dir_containing('environments', { 'production' => { 'modules' => {
'm1' => { 'templates' => {
'greetings.epp' => "<% |$subject = world| %>hello <%= $subject -%>",
'factshash.epp' => "fact = <%= $facts[the_fact] -%>",
'fact.epp' => "fact = <%= $the_fact -%>",
}},
'm2' => { 'templates' => {
'goodbye.epp' => "<% | $subject = world |%>goodbye <%= $subject -%>",
}}
},
'extra' => {
'facts.yaml' => "---\n the_fact: 42"
}
}})
end
around(:each) do |example|
Puppet.settings.initialize_global_settings
loader = Puppet::Environments::Directories.new(dir, [])
Puppet.override(:environments => loader) do
example.run
end
end
it "renders supplied template files in different modules of a directory environment" do
expect(eppface.render('m1/greetings.epp')).to eq("hello world")
expect(eppface.render('m2/goodbye.epp')).to eq("goodbye world")
end
it "makes facts available in $facts" do
facts_file = File.join(dir, 'production', 'extra', 'facts.yaml')
expect(eppface.render('m1/factshash.epp', :facts => facts_file)).to eq("fact = 42")
end
it "makes facts available individually" do
facts_file = File.join(dir, 'production', 'extra', 'facts.yaml')
expect(eppface.render('m1/fact.epp', :facts => facts_file)).to eq("fact = 42")
end
it "renders multiple files separated by headers by default" do
# chomp the last newline, it is put there by heredoc
expect(eppface.render('m1/greetings.epp', 'm2/goodbye.epp')).to eq(<<-EOT.chomp)
--- m1/greetings.epp
hello world
--- m2/goodbye.epp
goodbye world
EOT
end
it "outputs multiple files verbatim when --no-headers is given" do
expect(eppface.render('m1/greetings.epp', 'm2/goodbye.epp', :header => false)).to eq("hello worldgoodbye world")
end
end
end
def from_an_interactive_terminal
allow(STDIN).to receive(:tty?).and_return(true)
end
def from_a_piped_input_of(contents)
allow(STDIN).to receive(:tty?).and_return(false)
allow(STDIN).to receive(:read).and_return(contents)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/facts_spec.rb | spec/unit/face/facts_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/indirector/facts/facter'
require 'puppet/indirector/facts/rest'
describe Puppet::Face[:facts, '0.0.1'] do
describe "#find" do
it { is_expected.to be_action :find }
end
describe '#upload' do
let(:model) { Puppet::Node::Facts }
let(:test_data) { model.new('puppet.node.test', {test_fact: 'test value'}) }
let(:facter_terminus) { model.indirection.terminus(:facter) }
before(:each) do
Puppet[:facts_terminus] = :memory
Puppet::Node::Facts.indirection.save(test_data)
allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=).with(:facter)
Puppet.settings.parse_config(<<-CONF)
[main]
server=puppet.server.invalid
certname=puppet.node.invalid
[agent]
server=puppet.server.test
node_name_value=puppet.node.test
CONF
# Faces start in :user run mode
Puppet.settings.preferred_run_mode = :user
end
it "uploads facts as application/json" do
stub_request(:put, 'https://puppet.server.test:8140/puppet/v3/facts/puppet.node.test?environment=*root*')
.with(
headers: { 'Content-Type' => 'application/json' },
body: hash_including(
{
"name" => "puppet.node.test",
"values" => {
"test_fact" => "test value"
}
}
)
)
subject.upload
end
it "passes the current environment" do
stub_request(:put, 'https://puppet.server.test:8140/puppet/v3/facts/puppet.node.test?environment=qa')
Puppet.override(:current_environment => Puppet::Node::Environment.remote('qa')) do
subject.upload
end
end
it "uses settings from the agent section of puppet.conf to resolve the node name" do
stub_request(:put, /puppet.node.test/)
subject.upload
end
it "logs the name of the server that received the upload" do
stub_request(:put, 'https://puppet.server.test:8140/puppet/v3/facts/puppet.node.test?environment=*root*')
subject.upload
expect(@logs).to be_any {|log| log.level == :notice &&
log.message =~ /Uploading facts for '.*' to 'puppet\.server\.test'/}
end
end
describe "#show" do
it { is_expected.to be_action :show }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/plugin_spec.rb | spec/unit/face/plugin_spec.rb | require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:plugin, :current] do
let(:pluginface) { described_class }
let(:action) { pluginface.get_action(:download) }
def render(result)
action.when_rendering(:console).call(result)
end
context "download" do
around do |example|
Puppet.override(server_agent_version: "5.3.4") do
example.run
end
end
context "when i18n is enabled" do
before(:each) do
Puppet[:disable_i18n] = false
end
it "downloads plugins, external facts, and locales" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([])
pluginface.download
expect(receive_count).to eq(3)
end
it "renders 'No plugins downloaded' if nothing was downloaded" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([])
result = pluginface.download
expect(receive_count).to eq(3)
expect(render(result)).to eq('No plugins downloaded.')
end
it "renders comma separate list of downloaded file names" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
receive_count += 1
case receive_count
when 1
%w[/a]
when 2
%w[/b]
when 3
%w[/c]
end
end
result = pluginface.download
expect(receive_count).to eq(3)
expect(render(result)).to eq('Downloaded these plugins: /a, /b, /c')
end
end
context "when i18n is enabled" do
before(:each) do
Puppet[:disable_i18n] = true
end
it "downloads only plugins and external facts, no locales" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([])
pluginface.download
expect(receive_count).to eq(2)
end
it "renders 'No plugins downloaded' if nothing was downloaded, without checking for locales" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([])
result = pluginface.download
expect(receive_count).to eq(2)
expect(render(result)).to eq('No plugins downloaded.')
end
it "renders comma separate list of downloaded file names" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
receive_count += 1
case receive_count
when 1
%w[/a]
when 2
%w[/b]
when 3
%w[/c]
end
end
result = pluginface.download
expect(receive_count).to eq(2)
expect(render(result)).to eq('Downloaded these plugins: /a, /b')
end
end
end
context "download when server_agent_version is 5.3.3" do
around do |example|
Puppet.override(server_agent_version: "5.3.3") do
example.run
end
end
it "downloads plugins, and external facts, but not locales" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1}.and_return([])
pluginface.download
end
it "renders comma separate list of downloaded file names that does not include locales" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
receive_count += 1
receive_count == 1 ? %w[/a] : %w[/b]
end
result = pluginface.download
expect(receive_count).to eq(2)
expect(render(result)).to eq('Downloaded these plugins: /a, /b')
end
end
context "download when server_agent_version is blank" do
around do |example|
Puppet.override(server_agent_version: "") do
example.run
end
end
it "downloads plugins, and external facts, but not locales" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([])
pluginface.download
expect(receive_count).to eq(2)
end
it "renders comma separate list of downloaded file names that does not include locales" do
receive_count = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
receive_count += 1
receive_count == 1 ? %w[/a] : %w[/b]
end
result = pluginface.download
expect(receive_count).to eq(2)
expect(render(result)).to eq('Downloaded these plugins: /a, /b')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/help_spec.rb | spec/unit/face/help_spec.rb | require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:help, '0.0.1'] do
it 'has a help action' do
expect(subject).to be_action :help
end
it 'has a default action of help' do
expect(subject.get_action('help')).to be_default
end
it 'accepts a call with no arguments' do
expect {
subject.help()
}.to_not raise_error
end
it 'accepts a face name' do
expect { subject.help(:help) }.to_not raise_error
end
it 'accepts a face and action name' do
expect { subject.help(:help, :help) }.to_not raise_error
end
it 'fails if more than a face and action are given' do
expect { subject.help(:help, :help, :for_the_love_of_god) }.to raise_error ArgumentError
end
it "treats :current and 'current' identically" do
expect(subject.help(:help, :version => :current)).to eq(
subject.help(:help, :version => 'current')
)
end
it 'raises an error when the face is unavailable' do
expect {
subject.help(:huzzah, :bar, :version => '17.0.0')
}.to raise_error(ArgumentError, /Could not find version 17\.0\.0/)
end
it 'finds a face by version' do
face = Puppet::Face[:huzzah, :current]
expect(subject.help(:huzzah, :version => face.version)).
to eq(subject.help(:huzzah, :version => :current))
end
context 'rendering has an error' do
it 'raises an ArgumentError if the face raises a StandardError' do
face = Puppet::Face[:module, :current]
allow(face).to receive(:short_description).and_raise(StandardError, 'whoops')
expect {
subject.help(:module)
}.to raise_error(ArgumentError, /Detail: "whoops"/)
end
it 'raises an ArgumentError if the face raises a LoadError' do
face = Puppet::Face[:module, :current]
allow(face).to receive(:short_description).and_raise(LoadError, 'cannot load such file -- yard')
expect {
subject.help(:module)
}.to raise_error(ArgumentError, /Detail: "cannot load such file -- yard"/)
end
context 'with face actions' do
it 'returns an error if we can not get an action for the module' do
face = Puppet::Face[:module, :current]
allow(face).to receive(:get_action).and_return(nil)
expect {subject.help('module', 'list')}.to raise_error(ArgumentError, /Unable to load action list from Puppet::Face/)
end
end
end
context 'when listing subcommands' do
subject { Puppet::Face[:help, :current].help }
RSpec::Matchers.define :have_a_summary do
match do |instance|
instance.summary.is_a?(String)
end
end
# Check a precondition for the next block; if this fails you have
# something odd in your set of face, and we skip testing things that
# matter. --daniel 2011-04-10
it 'has at least one face with a summary' do
expect(Puppet::Face.faces).to be_any do |name|
Puppet::Face[name, :current].summary
end
end
it 'lists all faces which are runnable from the command line' do
help_face = Puppet::Face[:help, :current]
# The main purpose of the help face is to provide documentation for
# command line users. It shouldn't show documentation for faces
# that can't be run from the command line, so, rather than iterating
# over all available faces, we need to iterate over the subcommands
# that are available from the command line.
Puppet::Application.available_application_names.each do |name|
next unless help_face.is_face_app?(name)
next if help_face.exclude_from_docs?(name)
face = Puppet::Face[name, :current]
summary = face.summary
expect(subject).to match(%r{ #{name} })
summary and expect(subject).to match(%r{ #{name} +#{summary}})
end
end
context 'face summaries' do
it 'can generate face summaries' do
faces = Puppet::Face.faces
expect(faces.length).to be > 0
faces.each do |name|
expect(Puppet::Face[name, :current]).to have_a_summary
end
end
end
it 'lists all legacy applications' do
Puppet::Face[:help, :current].legacy_applications.each do |appname|
expect(subject).to match(%r{ #{appname} })
summary = Puppet::Face[:help, :current].horribly_extract_summary_from(appname)
summary_regex = Regexp.escape(summary)
summary and expect(subject).to match(%r{ #{summary_regex}$})
end
end
end
context 'deprecated faces' do
it 'prints a deprecation warning for deprecated faces' do
allow(Puppet::Face[:module, :current]).to receive(:deprecated?).and_return(true)
expect(Puppet::Face[:help, :current].help(:module)).to match(/Warning: 'puppet module' is deprecated/)
end
end
context '#all_application_summaries' do
it 'appends a deprecation warning for deprecated faces' do
# Stub the module face as deprecated
expect(Puppet::Face[:module, :current]).to receive(:deprecated?).and_return(true)
Puppet::Face[:help, :current].all_application_summaries.each do |appname,summary|
expect(summary).to match(/Deprecated/) if appname == 'module'
end
end
end
context '#legacy_applications' do
subject { Puppet::Face[:help, :current].legacy_applications }
# If we don't, these tests are ... less than useful, because they assume
# it. When this breaks you should consider ditching the entire feature
# and tests, but if not work out how to fake one. --daniel 2011-04-11
it { expect(subject.count).to be > 1 }
# Meh. This is nasty, but we can't control the other list; the specific
# bug that caused these to be listed is annoyingly subtle and has a nasty
# fix, so better to have a "fail if you do something daft" trigger in
# place here, I think. --daniel 2011-04-11
%w{face_base indirection_base}.each do |name|
it { is_expected.not_to include name }
end
end
context 'help for legacy applications' do
subject { Puppet::Face[:help, :current] }
let :appname do subject.legacy_applications.first end
# This test is purposely generic, so that as we eliminate legacy commands
# we don't get into a loop where we either test a face-based replacement
# and fail to notice breakage, or where we have to constantly rewrite this
# test and all. --daniel 2011-04-11
it 'returns the legacy help when given the subcommand' do
help = subject.help(appname)
expect(help).to match(/puppet-#{appname}/)
%w{SYNOPSIS USAGE DESCRIPTION OPTIONS COPYRIGHT}.each do |heading|
expect(help).to match(/^#{heading}$/)
end
end
it 'fails when asked for an action on a legacy command' do
expect { subject.help(appname, :whatever) }.
to raise_error(ArgumentError, /The legacy subcommand '#{appname}' does not support supplying an action/)
end
context 'rendering has an error' do
it 'raises an ArgumentError if a legacy application raises a StandardError' do
allow_any_instance_of(Puppet::Application[appname].class).to receive(:help).and_raise(StandardError, 'whoops')
expect {
subject.help(appname)
}.to raise_error(ArgumentError, /Detail: "whoops"/)
end
it 'raises an ArgumentError if a legacy application raises a LoadError' do
allow_any_instance_of(Puppet::Application[appname].class).to receive(:help).and_raise(LoadError, 'cannot load such file -- yard')
expect {
subject.help(appname)
}.to raise_error(ArgumentError, /Detail: "cannot load such file -- yard"/)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/parser_spec.rb | spec/unit/face/parser_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/face'
require 'puppet/application/parser'
describe Puppet::Face[:parser, :current] do
include PuppetSpec::Files
let(:parser) { Puppet::Face[:parser, :current] }
context "validate" do
let(:validate_app) do
Puppet::Application::Parser.new.tap do |app|
allow(app).to receive(:action).and_return(parser.get_action(:validate))
end
end
context "from an interactive terminal" do
before :each do
from_an_interactive_terminal
end
after(:each) do
# Reset cache of loaders (many examples run in the *root* environment
# which exists in "eternity")
Puppet.lookup(:current_environment).loaders = nil
end
it "validates the configured site manifest when no files are given" do
manifest = file_containing('site.pp', "{ invalid =>")
configured_environment = Puppet::Node::Environment.create(:default, [], manifest)
Puppet.override(:current_environment => configured_environment) do
parse_errors = parser.validate()
expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue)
end
end
it "validates the given file" do
manifest = file_containing('site.pp', "{ invalid =>")
parse_errors = parser.validate(manifest)
expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue)
end
it "validates static heredoc with specified syntax" do
manifest = file_containing('site.pp', "@(EOT:pp)
{ invalid =>
EOT
")
parse_errors = parser.validate(manifest)
expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue)
end
it "does not validates dynamic heredoc with specified syntax" do
manifest = file_containing('site.pp', "@(\"EOT\":pp)
{invalid => ${1+1}
EOT")
parse_errors = parser.validate(manifest)
expect(parse_errors).to be_empty
end
it "runs error free when there are no validation errors" do
manifest = file_containing('site.pp', "notify { valid: }")
parse_errors = parser.validate(manifest)
expect(parse_errors).to be_empty
end
it "runs error free when there is a puppet function in manifest being validated" do
manifest = file_containing('site.pp', "function valid() { 'valid' } notify{ valid(): }")
parse_errors = parser.validate(manifest)
expect(parse_errors).to be_empty
end
it "runs error free when there is a type alias in a manifest that requires type resolution" do
manifest = file_containing('site.pp',
"type A = String; type B = Array[A]; function valid(B $x) { $x } notify{ valid([valid]): }")
parse_errors = parser.validate(manifest)
expect(parse_errors).to be_empty
end
it "reports missing files" do
expect do
parser.validate("missing.pp")
end.to raise_error(Puppet::Error, /One or more file\(s\) specified did not exist.*missing\.pp/m)
end
it "parses supplied manifest files in the context of a directory environment" do
manifest = file_containing('test.pp', "{ invalid =>")
env = Puppet::Node::Environment.create(:special, [])
env_loader = Puppet::Environments::Static.new(env)
Puppet.override({:environments => env_loader, :current_environment => env}) do
parse_errors = parser.validate(manifest)
expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue)
end
end
end
context "when no files given and STDIN is not a tty" do
it "validates the contents of STDIN" do
from_a_piped_input_of("{ invalid =>")
Puppet.override(:current_environment => Puppet::Node::Environment.create(:special, [])) do
parse_errors = parser.validate()
expect(parse_errors['STDIN']).to be_a_kind_of(Puppet::ParseErrorWithIssue)
end
end
it "runs error free when contents of STDIN is valid" do
from_a_piped_input_of("notify { valid: }")
Puppet.override(:current_environment => Puppet::Node::Environment.create(:special, [])) do
parse_errors = parser.validate()
expect(parse_errors).to be_empty
end
end
end
context "when invoked with console output renderer" do
before(:each) do
validate_app.render_as = :console
end
it "logs errors using Puppet.log_exception" do
manifest = file_containing('test.pp', "{ invalid =>")
results = parser.validate(manifest)
results.each do |_, error|
expect(Puppet).to receive(:log_exception).with(error)
end
expect { validate_app.render(results, nil) }.to raise_error(SystemExit)
end
end
context "when invoked with --render-as=json" do
before(:each) do
validate_app.render_as = :json
end
it "outputs errors in a JSON document to stdout" do
manifest = file_containing('test.pp', "{ invalid =>")
results = parser.validate(manifest)
expected_json = /\A{.*#{Regexp.escape('"message":')}\s*#{Regexp.escape('"Syntax error at end of input"')}.*}\Z/m
expect { validate_app.render(results, nil) }.to output(expected_json).to_stdout.and raise_error(SystemExit)
end
end
end
context "dump" do
it "prints the AST of the passed expression" do
expect(parser.dump({ :e => 'notice hi' })).to eq("(invoke notice hi)\n")
end
it "prints the AST of the code read from the passed files" do
first_manifest = file_containing('site.pp', "notice hi")
second_manifest = file_containing('site2.pp', "notice bye")
output = parser.dump(first_manifest, second_manifest)
expect(output).to match(/site\.pp.*\(invoke notice hi\)/)
expect(output).to match(/site2\.pp.*\(invoke notice bye\)/)
end
it "informs the user of files that don't exist" do
expect(parser.dump('does_not_exist_here.pp')).to match(/did not exist:\s*does_not_exist_here\.pp/m)
end
it "prints the AST of STDIN when no files given and STDIN is not a tty" do
from_a_piped_input_of("notice hi")
Puppet.override(:current_environment => Puppet::Node::Environment.create(:special, [])) do
expect(parser.dump()).to eq("(invoke notice hi)\n")
end
end
it "logs an error if the input cannot be parsed" do
output = parser.dump({ :e => '{ invalid =>' })
expect(output).to eq("")
expect(@logs[0].message).to eq("Syntax error at end of input")
expect(@logs[0].level).to eq(:err)
end
it "logs an error if the input begins with a UTF-8 BOM (Byte Order Mark)" do
utf8_bom_manifest = file_containing('utf8_bom.pp', "\uFEFFnotice hi")
output = parser.dump(utf8_bom_manifest)
expect(output).to eq("")
expect(@logs[1].message).to eq("Illegal UTF-8 Byte Order mark at beginning of input: [EF BB BF] - remove these from the puppet source")
expect(@logs[1].level).to eq(:err)
end
it "runs error free when there is a puppet function in manifest being dumped" do
expect {
manifest = file_containing('site.pp', "function valid() { 'valid' } notify{ valid(): }")
parser.dump(manifest)
}.to_not raise_error
end
it "runs error free when there is a type alias in a manifest that requires type resolution" do
expect {
manifest = file_containing('site.pp',
"type A = String; type B = Array[A]; function valid(B $x) { $x } notify{ valid([valid]): }")
parser.dump(manifest)
}.to_not raise_error
end
context "using 'pn' format" do
it "prints the AST of the given expression in PN format" do
expect(parser.dump({ :format => 'pn', :e => 'if $x { "hi ${x[2]}" }' })).to eq(
'(if {:test (var "x") :then [(concat "hi " (str (access (var "x") 2)))]})')
end
it "pretty prints the AST of the given expression in PN format when --pretty is given" do
expect(parser.dump({ :pretty => true, :format => 'pn', :e => 'if $x { "hi ${x[2]}" }' })).to eq(<<-RESULT.unindent[0..-2])
(if
{
:test (var
"x")
:then [
(concat
"hi "
(str
(access
(var
"x")
2)))]})
RESULT
end
end
context "using 'json' format" do
it "prints the AST of the given expression in JSON based on the PN format" do
expect(parser.dump({ :format => 'json', :e => 'if $x { "hi ${x[2]}" }' })).to eq(
'{"^":["if",{"#":["test",{"^":["var","x"]},"then",[{"^":["concat","hi ",{"^":["str",{"^":["access",{"^":["var","x"]},2]}]}]}]]}]}')
end
it "pretty prints the AST of the given expression in JSON based on the PN format when --pretty is given" do
expect(parser.dump({ :pretty => true, :format => 'json', :e => 'if $x { "hi ${x[2]}" }' })).to eq(<<-RESULT.unindent[0..-2])
{
"^": [
"if",
{
"#": [
"test",
{
"^": [
"var",
"x"
]
},
"then",
[
{
"^": [
"concat",
"hi ",
{
"^": [
"str",
{
"^": [
"access",
{
"^": [
"var",
"x"
]
},
2
]
}
]
}
]
}
]
]
}
]
}
RESULT
end
end
end
def from_an_interactive_terminal
allow(STDIN).to receive(:tty?).and_return(true)
end
def from_a_piped_input_of(contents)
allow(STDIN).to receive(:tty?).and_return(false)
allow(STDIN).to receive(:read).and_return(contents)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/config_spec.rb | spec/unit/face/config_spec.rb | require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:config, '0.0.1'] do
let(:config) { described_class }
def render(action, result)
config.get_action(action).when_rendering(:console).call(result)
end
FS = Puppet::FileSystem
it "prints a single setting without the name" do
Puppet[:trace] = true
result = subject.print("trace")
expect(render(:print, result)).to eq("true\n")
end
it "prints multiple settings with the names" do
Puppet[:trace] = true
Puppet[:syslogfacility] = "file"
result = subject.print("trace", "syslogfacility")
expect(render(:print, result)).to eq(<<-OUTPUT)
syslogfacility = file
trace = true
OUTPUT
end
it "prints environment_timeout=unlimited correctly" do
Puppet[:environment_timeout] = "unlimited"
result = subject.print("environment_timeout")
expect(render(:print, result)).to eq("unlimited\n")
end
it "prints arrays correctly" do
pending "Still doesn't print arrays like they would appear in config"
Puppet[:server_list] = %w{server1 server2}
result = subject.print("server_list")
expect(render(:print, result)).to eq("server1, server2\n")
end
it "prints the setting from the selected section" do
Puppet.settings.parse_config(<<-CONF)
[user]
syslogfacility = file
CONF
result = subject.print("syslogfacility", :section => "user")
expect(render(:print, result)).to eq("file\n")
end
it "prints the section and environment, and not a warning, when a section is given and verbose is set" do
Puppet.settings.parse_config(<<-CONF)
[user]
syslogfacility = file
CONF
#This has to be after the settings above, which resets the value
Puppet[:log_level] = 'info'
expect(Puppet).not_to receive(:warning)
expect {
result = subject.print("syslogfacility", :section => "user")
expect(render(:print, result)).to eq("file\n")
}.to output("\e[1;33mResolving settings from section 'user' in environment 'production'\e[0m\n").to_stderr
end
it "prints a warning and the section and environment when no section is given and verbose is set" do
Puppet[:log_level] = 'info'
Puppet[:trace] = true
expect(Puppet).to receive(:warning).with("No section specified; defaulting to 'main'.\nSet the config section " +
"by using the `--section` flag.\nFor example, `puppet config --section user print foo`.\nFor more " +
"information, see https://puppet.com/docs/puppet/latest/configuration.html")
expect {
result = subject.print("trace")
expect(render(:print, result)).to eq("true\n")
}.to output("\e[1;33mResolving settings from section 'main' in environment 'production'\e[0m\n").to_stderr
end
it "does not print a warning or the section and environment when no section is given and verbose is not set" do
Puppet[:log_level] = 'notice'
Puppet[:trace] = true
expect(Puppet).not_to receive(:warning)
expect {
result = subject.print("trace")
expect(render(:print, result)).to eq("true\n")
}.to_not output.to_stderr
end
it "defaults to all when no arguments are given" do
result = subject.print
expect(render(:print, result).lines.to_a.length).to eq(Puppet.settings.to_a.length)
end
it "prints out all of the settings when asked for 'all'" do
result = subject.print('all')
expect(render(:print, result).lines.to_a.length).to eq(Puppet.settings.to_a.length)
end
it "stringifies all keys for network format handlers to consume" do
Puppet[:syslogfacility] = "file"
result = subject.print
expect(result["syslogfacility"]).to eq("file")
expect(result.keys).to all(be_a(String))
end
it "stringifies multiple keys for network format handlers to consume" do
Puppet[:trace] = true
Puppet[:syslogfacility] = "file"
expect(subject.print("trace", "syslogfacility")).to eq({"syslogfacility" => "file", "trace" => true})
end
it "stringifies single key for network format handlers to consume" do
Puppet[:trace] = true
expect(subject.print("trace")).to eq({"trace" => true})
end
context "when setting config values" do
let(:config_file) { '/foo/puppet.conf' }
let(:path) { Pathname.new(config_file).expand_path }
before(:each) do
Puppet[:config] = config_file
allow(Puppet::FileSystem).to receive(:pathname).with(path.to_s).and_return(path)
allow(Puppet::FileSystem).to receive(:touch)
end
it "prints the section and environment when no section is given and verbose is set" do
Puppet[:log_level] = 'info'
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
expect {
subject.set('certname', 'bar')
}.to output("\e[1;33mResolving settings from section 'main' in environment 'production'\e[0m\n").to_stderr
end
it "prints the section and environment when a section is given and verbose is set" do
Puppet[:log_level] = 'info'
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
expect {
subject.set('certname', 'bar', {:section => "baz"})
}.to output("\e[1;33mResolving settings from section 'baz' in environment 'production'\e[0m\n").to_stderr
end
it "writes to the correct puppet config file" do
expect(Puppet::FileSystem).to receive(:open).with(path, anything, anything)
subject.set('certname', 'bar')
end
it "creates a config file if one does not exist" do
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
expect(Puppet::FileSystem).to receive(:touch).with(path)
subject.set('certname', 'bar')
end
it "sets the supplied config/value in the default section (main)" do
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new])
manipulator = Puppet::Settings::IniFile::Manipulator.new(config)
allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator)
expect(manipulator).to receive(:set).with("main", "certname", "bar")
subject.set('certname', 'bar')
end
it "sets the value in the supplied section" do
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new])
manipulator = Puppet::Settings::IniFile::Manipulator.new(config)
allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator)
expect(manipulator).to receive(:set).with("baz", "certname", "bar")
subject.set('certname', 'bar', {:section => "baz"})
end
it "does not duplicate an existing default section when a section is not specified" do
contents = <<-CONF
[main]
myport = 4444
CONF
myfile = StringIO.new(contents)
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(myfile)
subject.set('certname', 'bar')
expect(myfile.string).to match(/certname = bar/)
expect(myfile.string).not_to match(/main.*main/)
end
it "opens the file with UTF-8 encoding" do
expect(Puppet::FileSystem).to receive(:open).with(path, nil, 'r+:UTF-8')
subject.set('certname', 'bar')
end
it "sets settings into the [server] section when setting [master] section settings" do
initial_contents = <<~CONFIG
[master]
node_terminus = none
reports = log
CONFIG
myinitialfile = StringIO.new(initial_contents)
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(myinitialfile)
expect {
subject.set('node_terminus', 'exec', {:section => 'master'})
}.to output("Deleted setting from 'master': 'node_terminus = none', and adding it to 'server' section\n").to_stdout
expect(myinitialfile.string).to match(<<~CONFIG)
[master]
reports = log
[server]
node_terminus = exec
CONFIG
end
it "setting [master] section settings, sets settings into [server] section instead" do
myinitialfile = StringIO.new("")
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(myinitialfile)
subject.set('node_terminus', 'exec', {:section => 'master'})
expect(myinitialfile.string).to match(<<~CONFIG)
[server]
node_terminus = exec
CONFIG
end
end
context 'when the puppet.conf file does not exist' do
let(:config_file) { '/foo/puppet.conf' }
let(:path) { Pathname.new(config_file).expand_path }
before(:each) do
Puppet[:config] = config_file
allow(Puppet::FileSystem).to receive(:pathname).with(path.to_s).and_return(path)
end
it 'prints a message when the puppet.conf file does not exist' do
allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false)
expect(Puppet).to receive(:warning).with("The puppet.conf file does not exist #{path.to_s}")
subject.delete('setting', {:section => 'main'})
end
end
context 'when deleting config values' do
let(:config_file) { '/foo/puppet.conf' }
let(:path) { Pathname.new(config_file).expand_path }
before(:each) do
Puppet[:config] = config_file
allow(Puppet::FileSystem).to receive(:pathname).with(path.to_s).and_return(path)
allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
end
it 'prints a message about what was deleted' do
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new])
manipulator = Puppet::Settings::IniFile::Manipulator.new(config)
allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator)
expect(manipulator).to receive(:delete).with('main', 'setting').and_return(' setting=value')
expect {
subject.delete('setting', {:section => 'main'})
}.to output("Deleted setting from 'main': 'setting=value'\n").to_stdout
end
it 'prints a warning when a setting is not found to delete' do
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new])
manipulator = Puppet::Settings::IniFile::Manipulator.new(config)
allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator)
expect(manipulator).to receive(:delete).with('main', 'setting').and_return(nil)
expect(Puppet).to receive(:warning).with("No setting found in configuration file for section 'main' setting name 'setting'")
subject.delete('setting', {:section => 'main'})
end
['master', 'server'].each do |section|
describe "when deleting from [#{section}] section" do
it "deletes section values from both [server] and [master] sections" do
allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new)
config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new])
manipulator = Puppet::Settings::IniFile::Manipulator.new(config)
allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator)
expect(manipulator).to receive(:delete).with('master', 'setting').and_return('setting=value')
expect(manipulator).to receive(:delete).with('server', 'setting').and_return('setting=value')
expect {
subject.delete('setting', {:section => section})
}.to output(/Deleted setting from 'master': 'setting'\nDeleted setting from 'server': 'setting'\n/).to_stdout
end
end
end
end
shared_examples_for :config_printing_a_section do |section|
def add_section_option(args, section)
args << { :section => section } if section
args
end
it "prints directory env settings for an env that exists" do
FS.overlay(
FS::MemoryFile.a_directory(File.expand_path("/dev/null/environments"), [
FS::MemoryFile.a_directory("production", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
])
) do
args = "environmentpath","manifest","modulepath","environment","basemodulepath"
result = subject.print(*add_section_option(args, section))
expect(render(:print, result)).to eq(<<-OUTPUT)
basemodulepath = #{File.expand_path("/some/base")}
environment = production
environmentpath = #{File.expand_path("/dev/null/environments")}
manifest = #{File.expand_path("/dev/null/environments/production/manifests")}
modulepath = #{File.expand_path("/dev/null/environments/production/modules")}#{File::PATH_SEPARATOR}#{File.expand_path("/some/base")}
OUTPUT
end
end
it "interpolates settings in environment.conf" do
FS.overlay(
FS::MemoryFile.a_directory(File.expand_path("/dev/null/environments"), [
FS::MemoryFile.a_directory("production", [
FS::MemoryFile.a_regular_file_containing("environment.conf", <<-CONTENT),
modulepath=/custom/modules#{File::PATH_SEPARATOR}$basemodulepath
CONTENT
]),
])
) do
args = "environmentpath","manifest","modulepath","environment","basemodulepath"
result = subject.print(*add_section_option(args, section))
expect(render(:print, result)).to eq(<<-OUTPUT)
basemodulepath = #{File.expand_path("/some/base")}
environment = production
environmentpath = #{File.expand_path("/dev/null/environments")}
manifest = #{File.expand_path("/dev/null/environments/production/manifests")}
modulepath = #{File.expand_path("/custom/modules")}#{File::PATH_SEPARATOR}#{File.expand_path("/some/base")}
OUTPUT
end
end
it "prints the default configured env settings for an env that does not exist" do
Puppet[:environment] = 'doesnotexist'
FS.overlay(
FS::MemoryFile.a_directory(File.expand_path("/dev/null/environments"), [
FS::MemoryFile.a_missing_file("doesnotexist")
])
) do
args = "environmentpath","manifest","modulepath","environment","basemodulepath"
result = subject.print(*add_section_option(args, section))
expect(render(:print, result)).to eq(<<-OUTPUT)
basemodulepath = #{File.expand_path("/some/base")}
environment = doesnotexist
environmentpath = #{File.expand_path("/dev/null/environments")}
manifest =
modulepath =
OUTPUT
end
end
end
context "when printing environment settings" do
context "from main section" do
before(:each) do
Puppet.settings.parse_config(<<-CONF)
[main]
environmentpath=$confdir/environments
basemodulepath=/some/base
CONF
end
it_behaves_like :config_printing_a_section, nil
end
context "from master section" do
before(:each) do
Puppet.settings.parse_config(<<-CONF)
[master]
environmentpath=$confdir/environments
basemodulepath=/some/base
CONF
end
it_behaves_like :config_printing_a_section, :master
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/catalog_spec.rb | spec/unit/face/catalog_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/indirector/facts/facter'
require 'puppet/indirector/facts/rest'
describe Puppet::Face[:catalog, '0.0.1'] do
describe '#download' do
let(:model) { Puppet::Node::Facts }
let(:test_data) { model.new('puppet.node.test', {test_fact: 'catalog_face_request_test_value'}) }
let(:catalog) { Puppet::Resource::Catalog.new('puppet.node.test', Puppet::Node::Environment.remote(Puppet[:environment].to_sym)) }
before(:each) do
Puppet[:facts_terminus] = :memory
Puppet::Node::Facts.indirection.save(test_data)
allow(Puppet::Face[:catalog, "0.0.1"]).to receive(:save).once
Puppet.settings.parse_config(<<-CONF)
[main]
server=puppet.server.test
certname=puppet.node.test
CONF
# Faces start in :user run mode
Puppet.settings.preferred_run_mode = :user
end
it "adds facts to the catalog request" do
stub_request(:post, 'https://puppet.server.test:8140/puppet/v3/catalog/puppet.node.test?environment=*root*')
.with(
headers: { 'Content-Type' => 'application/x-www-form-urlencoded' },
body: hash_including(facts: URI.encode_www_form_component(Puppet::Node::Facts.indirection.find('puppet.node.test').to_json))
).to_return(:status => 200, :body => catalog.render(:json), :headers => {'Content-Type' => 'application/json'})
subject.download
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/node_spec.rb | spec/unit/face/node_spec.rb | require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:node, '0.0.1'] do
describe '#cleanup' do
it "should clean everything" do
{
"cert" => ['hostname'],
"cached_facts" => ['hostname'],
"cached_node" => ['hostname'],
"reports" => ['hostname'],
}.each { |k, v| expect(subject).to receive("clean_#{k}".to_sym).with(*v) }
subject.cleanup('hostname')
end
end
describe 'when running #clean' do
it 'should invoke #cleanup' do
expect(subject).to receive(:cleanup).with('hostname')
subject.clean('hostname')
end
end
describe "clean action" do
before :each do
allow(subject).to receive(:cleanup)
end
it "should have a clean action" do
expect(subject).to be_action :clean
end
it "should not accept a call with no arguments" do
expect { subject.clean() }.to raise_error(RuntimeError, /At least one node should be passed/)
end
it "should accept a node name" do
expect { subject.clean('hostname') }.to_not raise_error
end
it "should accept more than one node name" do
expect do
subject.clean('hostname', 'hostname2', {})
end.to_not raise_error
expect do
subject.clean('hostname', 'hostname2', 'hostname3')
end.to_not raise_error
end
context "clean action" do
subject { Puppet::Face[:node, :current] }
before :each do
allow(Puppet::Util::Log).to receive(:newdestination)
allow(Puppet::Util::Log).to receive(:level=)
end
describe "during setup" do
it "should set facts terminus and cache class to yaml" do
expect(Puppet::Node::Facts.indirection).to receive(:terminus_class=).with(:yaml)
expect(Puppet::Node::Facts.indirection).to receive(:cache_class=).with(:yaml)
subject.clean('hostname')
end
it "should run in server mode" do
subject.clean('hostname')
expect(Puppet.run_mode).to be_server
end
it "should set node cache as yaml" do
expect(Puppet::Node.indirection).to receive(:terminus_class=).with(:yaml)
expect(Puppet::Node.indirection).to receive(:cache_class=).with(:yaml)
subject.clean('hostname')
end
end
describe "when cleaning certificate", :if => Puppet.features.puppetserver_ca? do
it "should call the CA CLI gem's clean action" do
expect_any_instance_of(Puppetserver::Ca::Action::Clean).
to receive(:clean_certs).
with(['hostname'], anything).
and_return(:success)
if Puppet[:cadir].start_with?(Puppet[:ssldir])
expect_any_instance_of(LoggerIO).
to receive(:warn).
with(/cadir is currently configured to be inside/)
end
expect(Puppet).not_to receive(:warning)
result = subject.clean_cert('hostname')
expect(result).to eq(0)
end
it "should not call the CA CLI gem's clean action if the gem is missing" do
expect(Puppet.features).to receive(:puppetserver_ca?).and_return(false)
expect_any_instance_of(Puppetserver::Ca::Action::Clean).not_to receive(:run)
subject.clean_cert("hostname")
end
end
describe "when cleaning cached facts" do
it "should destroy facts" do
@host = 'node'
expect(Puppet::Node::Facts.indirection).to receive(:destroy).with(@host)
subject.clean_cached_facts(@host)
end
end
describe "when cleaning cached node" do
it "should destroy the cached node" do
expect(Puppet::Node.indirection).to receive(:destroy).with(@host)
subject.clean_cached_node(@host)
end
end
describe "when cleaning archived reports" do
it "should tell the reports to remove themselves" do
allow(Puppet::Transaction::Report.indirection).to receive(:destroy).with(@host)
subject.clean_reports(@host)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/module/install_spec.rb | spec/unit/face/module/install_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/module_tool'
describe "puppet module install" do
include PuppetSpec::Files
describe "action" do
let(:name) { double(:name) }
let(:target_dir) { tmpdir('module install face action') }
let(:options) { { :target_dir => target_dir } }
it 'should invoke the Installer app' do
expect(Puppet::ModuleTool).to receive(:set_option_defaults).with(options)
expect(Puppet::ModuleTool::Applications::Installer).to receive(:run) do |mod, target, opts|
expect(mod).to eql(name)
expect(opts).to eql(options)
expect(target).to be_a(Puppet::ModuleTool::InstallDirectory)
expect(target.target).to eql(Pathname.new(target_dir))
end
Puppet::Face[:module, :current].install(name, options)
end
end
describe "inline documentation" do
subject { Puppet::Face.find_action(:module, :install) }
its(:summary) { should =~ /install.*module/im }
its(:description) { should =~ /install.*module/im }
its(:returns) { should =~ /pathname/i }
its(:examples) { should_not be_empty }
%w{ license copyright summary description returns examples }.each do |doc|
context "of the" do
its(doc.to_sym) { should_not =~ /(FIXME|REVISIT|TODO)/ }
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/module/upgrade_spec.rb | spec/unit/face/module/upgrade_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/module_tool'
describe "puppet module upgrade" do
subject { Puppet::Face[:module, :current] }
let(:options) do
{}
end
describe "inline documentation" do
subject { Puppet::Face[:module, :current].get_action :upgrade }
its(:summary) { should =~ /upgrade.*module/im }
its(:description) { should =~ /upgrade.*module/im }
its(:returns) { should =~ /hash/i }
its(:examples) { should_not be_empty }
%w{ license copyright summary description returns examples }.each do |doc|
context "of the" do
its(doc.to_sym) { should_not =~ /(FIXME|REVISIT|TODO)/ }
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/module/list_spec.rb | spec/unit/face/module/list_spec.rb | # encoding: UTF-8
require 'spec_helper'
require 'puppet/face'
require 'puppet/module_tool'
require 'puppet_spec/modules'
describe "puppet module list" do
include PuppetSpec::Files
around do |example|
dir = tmpdir("deep_path")
FileUtils.mkdir_p(@modpath1 = File.join(dir, "modpath1"))
FileUtils.mkdir_p(@modpath2 = File.join(dir, "modpath2"))
FileUtils.mkdir_p(@modpath3 = File.join(dir, "modpath3"))
env = Puppet::Node::Environment.create(:env, [@modpath1, @modpath2])
Puppet.override(:current_environment => env) do
example.run
end
end
it "should return an empty list per dir in path if there are no modules" do
expect(Puppet::Face[:module, :current].list[:modules_by_path]).to eq({
@modpath1 => [],
@modpath2 => []
})
end
it "should include modules separated by the environment's modulepath" do
foomod1 = PuppetSpec::Modules.create('foo', @modpath1)
barmod1 = PuppetSpec::Modules.create('bar', @modpath1)
foomod2 = PuppetSpec::Modules.create('foo', @modpath2)
usedenv = Puppet::Node::Environment.create(:useme, [@modpath1, @modpath2, @modpath3])
Puppet.override(:environments => Puppet::Environments::Static.new(usedenv)) do
expect(Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path]).to eq({
@modpath1 => [
Puppet::Module.new('bar', barmod1.path, usedenv),
Puppet::Module.new('foo', foomod1.path, usedenv)
],
@modpath2 => [Puppet::Module.new('foo', foomod2.path, usedenv)],
@modpath3 => [],
})
end
end
it "should use the specified environment" do
foomod = PuppetSpec::Modules.create('foo', @modpath1)
barmod = PuppetSpec::Modules.create('bar', @modpath1)
usedenv = Puppet::Node::Environment.create(:useme, [@modpath1, @modpath2, @modpath3])
Puppet.override(:environments => Puppet::Environments::Static.new(usedenv)) do
expect(Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path]).to eq({
@modpath1 => [
Puppet::Module.new('bar', barmod.path, usedenv),
Puppet::Module.new('foo', foomod.path, usedenv)
],
@modpath2 => [],
@modpath3 => [],
})
end
end
it "should use the specified modulepath" do
foomod = PuppetSpec::Modules.create('foo', @modpath1)
barmod = PuppetSpec::Modules.create('bar', @modpath2)
modules = Puppet::Face[:module, :current].list(:modulepath => "#{@modpath1}#{File::PATH_SEPARATOR}#{@modpath2}")[:modules_by_path]
expect(modules[@modpath1].first.name).to eq('foo')
expect(modules[@modpath1].first.path).to eq(foomod.path)
expect(modules[@modpath1].first.environment.modulepath).to eq([@modpath1, @modpath2])
expect(modules[@modpath2].first.name).to eq('bar')
expect(modules[@modpath2].first.path).to eq(barmod.path)
expect(modules[@modpath2].first.environment.modulepath).to eq([@modpath1, @modpath2])
end
it "prefers a given modulepath over the modulepath from the given environment" do
foomod = PuppetSpec::Modules.create('foo', @modpath1)
barmod = PuppetSpec::Modules.create('bar', @modpath2)
modules = Puppet::Face[:module, :current].list(:environment => 'myenv', :modulepath => "#{@modpath1}#{File::PATH_SEPARATOR}#{@modpath2}")[:modules_by_path]
expect(modules[@modpath1].first.name).to eq('foo')
expect(modules[@modpath1].first.path).to eq(foomod.path)
expect(modules[@modpath1].first.environment.modulepath).to eq([@modpath1, @modpath2])
expect(modules[@modpath1].first.environment.name).to_not eq(:myenv)
expect(modules[@modpath2].first.name).to eq('bar')
expect(modules[@modpath2].first.path).to eq(barmod.path)
expect(modules[@modpath2].first.environment.modulepath).to eq([@modpath1, @modpath2])
expect(modules[@modpath2].first.environment.name).to_not eq(:myenv)
end
describe "inline documentation" do
subject { Puppet::Face[:module, :current].get_action(:list) }
its(:summary) { should =~ /list.*module/im }
its(:description) { should =~ /list.*module/im }
its(:returns) { should =~ /hash of paths to module objects/i }
its(:examples) { should_not be_empty }
end
describe "when rendering to console" do
let(:face) { Puppet::Face[:module, :current] }
let(:action) { face.get_action(:list) }
def console_output(options={})
result = face.list(options)
action.when_rendering(:console).call(result, options)
end
it "should explicitly state when a modulepath is empty" do
empty_modpath = tmpdir('empty')
expected = <<-HEREDOC.gsub(' ', '')
#{empty_modpath} (no modules installed)
HEREDOC
expect(console_output(:modulepath => empty_modpath)).to eq(expected)
end
it "should print both modules with and without metadata" do
modpath = tmpdir('modpath')
PuppetSpec::Modules.create('nometadata', modpath)
PuppetSpec::Modules.create('metadata', modpath, :metadata => {:author => 'metaman'})
env = Puppet::Node::Environment.create(:environ, [modpath])
Puppet.override(:current_environment => env) do
expected = <<-HEREDOC.gsub(' ', '')
#{modpath}
├── metaman-metadata (\e[0;36mv9.9.9\e[0m)
└── nometadata (\e[0;36m???\e[0m)
HEREDOC
expect(console_output).to eq(expected)
end
end
it "should print the modulepaths in the order they are in the modulepath setting" do
path1 = tmpdir('b')
path2 = tmpdir('c')
path3 = tmpdir('a')
env = Puppet::Node::Environment.create(:environ, [path1, path2, path3])
Puppet.override(:current_environment => env) do
expected = <<-HEREDOC.gsub(' ', '')
#{path1} (no modules installed)
#{path2} (no modules installed)
#{path3} (no modules installed)
HEREDOC
expect(console_output).to eq(expected)
end
end
it "should print dependencies as a tree" do
PuppetSpec::Modules.create('dependable', @modpath1, :metadata => { :version => '0.0.5'})
PuppetSpec::Modules.create(
'other_mod',
@modpath1,
:metadata => {
:version => '1.0.0',
:dependencies => [{
"version_requirement" => ">= 0.0.5",
"name" => "puppetlabs/dependable"
}]
}
)
expected = <<-HEREDOC.gsub(' ', '')
#{@modpath1}
└─┬ puppetlabs-other_mod (\e[0;36mv1.0.0\e[0m)
└── puppetlabs-dependable (\e[0;36mv0.0.5\e[0m)
#{@modpath2} (no modules installed)
HEREDOC
expect(console_output(:tree => true)).to eq(expected)
end
it "should print both modules with and without metadata as a tree" do
PuppetSpec::Modules.create('nometadata', @modpath1)
PuppetSpec::Modules.create('metadata', @modpath1, :metadata => {:author => 'metaman'})
expected = <<-HEREDOC.gsub(' ', '')
#{@modpath1}
├── metaman-metadata (\e[0;36mv9.9.9\e[0m)
└── nometadata (\e[0;36m???\e[0m)
#{@modpath2} (no modules installed)
HEREDOC
expect(console_output).to eq(expected)
end
it "should warn about missing dependencies" do
PuppetSpec::Modules.create('depender', @modpath1, :metadata => {
:version => '1.0.0',
:dependencies => [{
"version_requirement" => ">= 0.0.5",
"name" => "puppetlabs/dependable"
}]
})
expect(Puppet).to receive(:warning).with(match(/Missing dependency 'puppetlabs-dependable'/).and match(/'puppetlabs-depender' \(v1\.0\.0\) requires 'puppetlabs-dependable' \(>= 0\.0\.5\)/))
console_output(:tree => true)
end
it "should warn about out of range dependencies" do
PuppetSpec::Modules.create('dependable', @modpath1, :metadata => { :version => '0.0.1'})
PuppetSpec::Modules.create('depender', @modpath1, :metadata => {
:version => '1.0.0',
:dependencies => [{
"version_requirement" => ">= 0.0.5",
"name" => "puppetlabs/dependable"
}]
})
expect(Puppet).to receive(:warning).with(match(/Module 'puppetlabs-dependable' \(v0\.0\.1\) fails to meet some dependencies/).and match(/'puppetlabs-depender' \(v1\.0\.0\) requires 'puppetlabs-dependable' \(>= 0\.0\.5\)/))
console_output(:tree => true)
end
end
describe "when rendering as json" do
let(:face) { Puppet::Face[:module, :current] }
let(:action) { face.get_action(:list) }
it "should warn about missing dependencies" do
PuppetSpec::Modules.create('depender', @modpath1, :metadata => {
:version => '1.0.0',
:dependencies => [{
"version_requirement" => ">= 0.0.5",
"name" => "puppetlabs/dependable"
}]
})
result = face.list
expect(result.dig(:unmet_dependencies, :missing)).to include(
"puppetlabs/dependable" => {
errors: ["'puppetlabs-depender' (v1.0.0) requires 'puppetlabs-dependable' (>= 0.0.5)"],
parent: {
name: "puppetlabs/depender", :version=>"v1.0.0"
},
version: nil
}
)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face/module/uninstall_spec.rb | spec/unit/face/module/uninstall_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/module_tool'
describe "puppet module uninstall" do
include PuppetSpec::Files
describe "action" do
let(:name) { 'module-name' }
let(:options) { Hash.new }
it 'should invoke the Uninstaller app' do
expect(Puppet::ModuleTool).to receive(:set_option_defaults).with(options)
expect(Puppet::ModuleTool::Applications::Uninstaller).to receive(:run).with(name, options)
Puppet::Face[:module, :current].uninstall(name, options)
end
context 'slash-separated module name' do
let(:name) { 'module/name' }
it 'should invoke the Uninstaller app' do
expect(Puppet::ModuleTool).to receive(:set_option_defaults).with(options)
expect(Puppet::ModuleTool::Applications::Uninstaller).to receive(:run).with('module-name', options)
Puppet::Face[:module, :current].uninstall(name, options)
end
end
end
describe "inline documentation" do
subject { Puppet::Face.find_action(:module, :uninstall) }
its(:summary) { should =~ /uninstall.*module/im }
its(:description) { should =~ /uninstall.*module/im }
its(:returns) { should =~ /uninstalled modules/i }
its(:examples) { should_not be_empty }
%w{ license copyright summary description returns examples }.each do |doc|
context "of the" do
its(doc.to_sym) { should_not =~ /(FIXME|REVISIT|TODO)/ }
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confine/exists_spec.rb | spec/unit/confine/exists_spec.rb | require 'spec_helper'
require 'puppet/confine/exists'
describe Puppet::Confine::Exists do
before do
@confine = Puppet::Confine::Exists.new("/my/file")
@confine.label = "eh"
end
it "should be named :exists" do
expect(Puppet::Confine::Exists.name).to eq(:exists)
end
it "should not pass if exists is nil" do
confine = Puppet::Confine::Exists.new(nil)
confine.label = ":exists => nil"
expect(confine).to receive(:pass?).with(nil)
expect(confine).not_to be_valid
end
it "should use the 'pass?' method to test validity" do
expect(@confine).to receive(:pass?).with("/my/file")
@confine.valid?
end
it "should return false if the value is false" do
expect(@confine.pass?(false)).to be_falsey
end
it "should return false if the value does not point to a file" do
expect(Puppet::FileSystem).to receive(:exist?).with("/my/file").and_return(false)
expect(@confine.pass?("/my/file")).to be_falsey
end
it "should return true if the value points to a file" do
expect(Puppet::FileSystem).to receive(:exist?).with("/my/file").and_return(true)
expect(@confine.pass?("/my/file")).to be_truthy
end
it "should produce a message saying that a file is missing" do
expect(@confine.message("/my/file")).to be_include("does not exist")
end
describe "and the confine is for binaries" do
before do
allow(@confine).to receive(:for_binary).and_return(true)
end
it "should use its 'which' method to look up the full path of the file" do
expect(@confine).to receive(:which).and_return(nil)
@confine.pass?("/my/file")
end
it "should return false if no executable can be found" do
expect(@confine).to receive(:which).with("/my/file").and_return(nil)
expect(@confine.pass?("/my/file")).to be_falsey
end
it "should return true if the executable can be found" do
expect(@confine).to receive(:which).with("/my/file").and_return("/my/file")
expect(@confine.pass?("/my/file")).to be_truthy
end
end
it "should produce a summary containing all missing files" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
expect(Puppet::FileSystem).to receive(:exist?).with("/two").and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with("/four").and_return(false)
confine = Puppet::Confine::Exists.new %w{/one /two /three /four}
expect(confine.summary).to eq(%w{/two /four})
end
it "should summarize multiple instances by returning a flattened array of their summaries" do
c1 = double('1', :summary => %w{one})
c2 = double('2', :summary => %w{two})
c3 = double('3', :summary => %w{three})
expect(Puppet::Confine::Exists.summarize([c1, c2, c3])).to eq(%w{one two three})
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confine/false_spec.rb | spec/unit/confine/false_spec.rb | require 'spec_helper'
require 'puppet/confine/false'
describe Puppet::Confine::False do
it "should be named :false" do
expect(Puppet::Confine::False.name).to eq(:false)
end
it "should require a value" do
expect { Puppet::Confine.new }.to raise_error(ArgumentError)
end
describe "when passing in a lambda as a value for lazy evaluation" do
it "should accept it" do
confine = Puppet::Confine::False.new(lambda { false })
expect(confine.values).to eql([false])
end
describe "when enforcing cache-positive behavior" do
def cached_value_of(confine)
confine.instance_variable_get(:@cached_value)
end
it "should cache a false value" do
confine = Puppet::Confine::False.new(lambda { false })
confine.values
expect(cached_value_of(confine)).to eql([false])
end
it "should not cache a true value" do
confine = Puppet::Confine::False.new(lambda { true })
confine.values
expect(cached_value_of(confine)).to be_nil
end
end
end
describe "when testing values" do
before { @confine = Puppet::Confine::False.new("foo") }
it "should use the 'pass?' method to test validity" do
@confine = Puppet::Confine::False.new("foo")
@confine.label = "eh"
expect(@confine).to receive(:pass?).with("foo")
@confine.valid?
end
it "should return true if the value is false" do
expect(@confine.pass?(false)).to be_truthy
end
it "should return false if the value is not false" do
expect(@confine.pass?("else")).to be_falsey
end
it "should produce a message that a value is true" do
@confine = Puppet::Confine::False.new("foo")
expect(@confine.message("eh")).to be_include("true")
end
end
it "should be able to produce a summary with the number of incorrectly true values" do
confine = Puppet::Confine::False.new %w{one two three four}
expect(confine).to receive(:pass?).exactly(4).times.and_return(true, false, true, false)
expect(confine.summary).to eq(2)
end
it "should summarize multiple instances by summing their summaries" do
c1 = double('1', :summary => 1)
c2 = double('2', :summary => 2)
c3 = double('3', :summary => 3)
expect(Puppet::Confine::False.summarize([c1, c2, c3])).to eq(6)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confine/variable_spec.rb | spec/unit/confine/variable_spec.rb | require 'spec_helper'
require 'puppet/confine/variable'
describe Puppet::Confine::Variable do
it "should be named :variable" do
expect(Puppet::Confine::Variable.name).to eq(:variable)
end
it "should require a value" do
expect { Puppet::Confine::Variable.new }.to raise_error(ArgumentError)
end
it "should always convert values to an array" do
expect(Puppet::Confine::Variable.new("/some/file").values).to be_instance_of(Array)
end
it "should have an accessor for its name" do
expect(Puppet::Confine::Variable.new(:bar)).to respond_to(:name)
end
describe "when testing values" do
before do
@confine = Puppet::Confine::Variable.new("foo")
@confine.name = :myvar
end
it "should use settings if the variable name is a valid setting" do
expect(Puppet.settings).to receive(:valid?).with(:myvar).and_return(true)
expect(Puppet.settings).to receive(:value).with(:myvar).and_return("foo")
@confine.valid?
end
it "should use Facter if the variable name is not a valid setting" do
expect(Puppet.settings).to receive(:valid?).with(:myvar).and_return(false)
expect(Facter).to receive(:value).with(:myvar).and_return("foo")
@confine.valid?
end
it "should be valid if the value matches the facter value" do
expect(@confine).to receive(:test_value).and_return("foo")
expect(@confine).to be_valid
end
it "should return false if the value does not match the facter value" do
expect(@confine).to receive(:test_value).and_return("fee")
expect(@confine).not_to be_valid
end
it "should be case insensitive" do
expect(@confine).to receive(:test_value).and_return("FOO")
expect(@confine).to be_valid
end
it "should not care whether the value is a string or symbol" do
expect(@confine).to receive(:test_value).and_return("FOO")
expect(@confine).to be_valid
end
it "should produce a message that the fact value is not correct" do
@confine = Puppet::Confine::Variable.new(%w{bar bee})
@confine.name = "eh"
message = @confine.message("value")
expect(message).to be_include("facter")
expect(message).to be_include("bar,bee")
end
it "should be valid if the test value matches any of the provided values" do
@confine = Puppet::Confine::Variable.new(%w{bar bee})
expect(@confine).to receive(:test_value).and_return("bee")
expect(@confine).to be_valid
end
end
describe "when summarizing multiple instances" do
it "should return a hash of failing variables and their values" do
c1 = Puppet::Confine::Variable.new("one")
c1.name = "uno"
expect(c1).to receive(:valid?).and_return(false)
c2 = Puppet::Confine::Variable.new("two")
c2.name = "dos"
expect(c2).to receive(:valid?).and_return(true)
c3 = Puppet::Confine::Variable.new("three")
c3.name = "tres"
expect(c3).to receive(:valid?).and_return(false)
expect(Puppet::Confine::Variable.summarize([c1, c2, c3])).to eq({"uno" => %w{one}, "tres" => %w{three}})
end
it "should combine the values of multiple confines with the same fact" do
c1 = Puppet::Confine::Variable.new("one")
c1.name = "uno"
expect(c1).to receive(:valid?).and_return(false)
c2 = Puppet::Confine::Variable.new("two")
c2.name = "uno"
expect(c2).to receive(:valid?).and_return(false)
expect(Puppet::Confine::Variable.summarize([c1, c2])).to eq({"uno" => %w{one two}})
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confine/true_spec.rb | spec/unit/confine/true_spec.rb | require 'spec_helper'
require 'puppet/confine/true'
describe Puppet::Confine::True do
it "should be named :true" do
expect(Puppet::Confine::True.name).to eq(:true)
end
it "should require a value" do
expect { Puppet::Confine::True.new }.to raise_error(ArgumentError)
end
describe "when passing in a lambda as a value for lazy evaluation" do
it "should accept it" do
confine = Puppet::Confine::True.new(lambda { true })
expect(confine.values).to eql([true])
end
describe "when enforcing cache-positive behavior" do
def cached_value_of(confine)
confine.instance_variable_get(:@cached_value)
end
it "should cache a true value" do
confine = Puppet::Confine::True.new(lambda { true })
confine.values
expect(cached_value_of(confine)).to eql([true])
end
it "should not cache a false value" do
confine = Puppet::Confine::True.new(lambda { false })
confine.values
expect(cached_value_of(confine)).to be_nil
end
end
end
describe "when testing values" do
before do
@confine = Puppet::Confine::True.new("foo")
@confine.label = "eh"
end
it "should use the 'pass?' method to test validity" do
expect(@confine).to receive(:pass?).with("foo")
@confine.valid?
end
it "should return true if the value is not false" do
expect(@confine.pass?("else")).to be_truthy
end
it "should return false if the value is false" do
expect(@confine.pass?(nil)).to be_falsey
end
it "should produce the message that a value is false" do
expect(@confine.message("eh")).to be_include("false")
end
end
it "should produce the number of false values when asked for a summary" do
@confine = Puppet::Confine::True.new %w{one two three four}
expect(@confine).to receive(:pass?).exactly(4).times.and_return(true, false, true, false)
expect(@confine.summary).to eq(2)
end
it "should summarize multiple instances by summing their summaries" do
c1 = double('1', :summary => 1)
c2 = double('2', :summary => 2)
c3 = double('3', :summary => 3)
expect(Puppet::Confine::True.summarize([c1, c2, c3])).to eq(6)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confine/feature_spec.rb | spec/unit/confine/feature_spec.rb | require 'spec_helper'
require 'puppet/confine/feature'
describe Puppet::Confine::Feature do
it "should be named :feature" do
expect(Puppet::Confine::Feature.name).to eq(:feature)
end
it "should require a value" do
expect { Puppet::Confine::Feature.new }.to raise_error(ArgumentError)
end
it "should always convert values to an array" do
expect(Puppet::Confine::Feature.new("/some/file").values).to be_instance_of(Array)
end
describe "when testing values" do
before do
@confine = Puppet::Confine::Feature.new("myfeature")
@confine.label = "eh"
end
it "should use the Puppet features instance to test validity" do
Puppet.features.add(:myfeature) do true end
@confine.valid?
end
it "should return true if the feature is present" do
Puppet.features.add(:myfeature) do true end
expect(@confine.pass?("myfeature")).to be_truthy
end
it "should return false if the value is false" do
Puppet.features.add(:myfeature) do false end
expect(@confine.pass?("myfeature")).to be_falsey
end
it "should log that a feature is missing" do
expect(@confine.message("myfeat")).to be_include("missing")
end
end
it "should summarize multiple instances by returning a flattened array of all missing features" do
confines = []
confines << Puppet::Confine::Feature.new(%w{one two})
confines << Puppet::Confine::Feature.new(%w{two})
confines << Puppet::Confine::Feature.new(%w{three four})
features = double('feature')
allow(features).to receive(:one?)
allow(features).to receive(:two?)
allow(features).to receive(:three?)
allow(features).to receive(:four?)
allow(Puppet).to receive(:features).and_return(features)
expect(Puppet::Confine::Feature.summarize(confines).sort).to eq(%w{one two three four}.sort)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/relationship_spec.rb | spec/unit/parser/relationship_spec.rb | require 'spec_helper'
require 'puppet/parser/relationship'
describe Puppet::Parser::Relationship do
before do
@source = Puppet::Resource.new(:mytype, "source")
@target = Puppet::Resource.new(:mytype, "target")
@extra_resource = Puppet::Resource.new(:mytype, "extra")
@extra_resource2 = Puppet::Resource.new(:mytype, "extra2")
@dep = Puppet::Parser::Relationship.new(@source, @target, :relationship)
end
describe "when evaluating" do
before do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@source)
@catalog.add_resource(@target)
@catalog.add_resource(@extra_resource)
@catalog.add_resource(@extra_resource2)
end
it "should fail if the source resource cannot be found" do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource @target
expect { @dep.evaluate(@catalog) }.to raise_error(ArgumentError)
end
it "should fail if the target resource cannot be found" do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource @source
expect { @dep.evaluate(@catalog) }.to raise_error(ArgumentError)
end
it "should add the target as a 'before' value if the type is 'relationship'" do
@dep.type = :relationship
@dep.evaluate(@catalog)
expect(@source[:before]).to be_include("Mytype[target]")
end
it "should add the target as a 'notify' value if the type is 'subscription'" do
@dep.type = :subscription
@dep.evaluate(@catalog)
expect(@source[:notify]).to be_include("Mytype[target]")
end
it "should supplement rather than clobber existing relationship values" do
@source[:before] = "File[/bar]"
@dep.evaluate(@catalog)
# this test did not work before. It was appending the resources
# together as a string
expect(@source[:before].class == Array).to be_truthy
expect(@source[:before]).to be_include("Mytype[target]")
expect(@source[:before]).to be_include("File[/bar]")
end
it "should supplement rather than clobber existing resource relationships" do
@source[:before] = @extra_resource
@dep.evaluate(@catalog)
expect(@source[:before].class == Array).to be_truthy
expect(@source[:before]).to be_include("Mytype[target]")
expect(@source[:before]).to be_include(@extra_resource)
end
it "should supplement rather than clobber multiple existing resource relationships" do
@source[:before] = [@extra_resource, @extra_resource2]
@dep.evaluate(@catalog)
expect(@source[:before].class == Array).to be_truthy
expect(@source[:before]).to be_include("Mytype[target]")
expect(@source[:before]).to be_include(@extra_resource)
expect(@source[:before]).to be_include(@extra_resource2)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/type_loader_spec.rb | spec/unit/parser/type_loader_spec.rb | require 'spec_helper'
require 'puppet/parser/type_loader'
require 'puppet/parser/parser_factory'
require 'puppet_spec/modules'
require 'puppet_spec/files'
describe Puppet::Parser::TypeLoader do
include PuppetSpec::Modules
include PuppetSpec::Files
let(:empty_hostclass) { Puppet::Parser::AST::Hostclass.new('') }
let(:loader) { Puppet::Parser::TypeLoader.new(:myenv) }
let(:my_env) { Puppet::Node::Environment.create(:myenv, []) }
around do |example|
envs = Puppet::Environments::Static.new(my_env)
Puppet.override(:environments => envs) do
example.run
end
end
it "should support an environment" do
loader = Puppet::Parser::TypeLoader.new(:myenv)
expect(loader.environment.name).to eq(:myenv)
end
it "should delegate its known resource types to its environment" do
expect(loader.known_resource_types).to be_instance_of(Puppet::Resource::TypeCollection)
end
describe "when loading names from namespaces" do
it "should do nothing if the name to import is an empty string" do
expect(loader.try_load_fqname(:hostclass, "")).to be_nil
end
it "should attempt to import each generated name" do
expect(loader).to receive(:import_from_modules).with("foo/bar").and_return([])
expect(loader).to receive(:import_from_modules).with("foo").and_return([])
loader.try_load_fqname(:hostclass, "foo::bar")
end
it "should attempt to load each possible name going from most to least specific" do
['foo/bar/baz', 'foo/bar', 'foo'].each do |path|
expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).with(path, anything).and_return([nil, []]).ordered
end
loader.try_load_fqname(:hostclass, 'foo::bar::baz')
end
end
describe "when importing" do
let(:stub_parser) { double('Parser', :file= => nil, :parse => empty_hostclass) }
before(:each) do
allow(Puppet::Parser::ParserFactory).to receive(:parser).and_return(stub_parser)
end
it "should find all manifests matching the file or pattern" do
expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).with("myfile", anything).and_return(["modname", %w{one}])
loader.import("myfile", "/path")
end
it "should pass the environment when looking for files" do
expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).with(anything, loader.environment).and_return(["modname", %w{one}])
loader.import("myfile", "/path")
end
it "should fail if no files are found" do
expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).and_return([nil, []])
expect { loader.import("myfile", "/path") }.to raise_error(/No file\(s\) found for import/)
end
it "should parse each found file" do
expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).and_return(["modname", [make_absolute("/one")]])
expect(loader).to receive(:parse_file).with(make_absolute("/one")).and_return(Puppet::Parser::AST::Hostclass.new(''))
loader.import("myfile", "/path")
end
it "should not attempt to import files that have already been imported" do
loader = Puppet::Parser::TypeLoader.new(:myenv)
expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).twice.and_return(["modname", %w{/one}])
expect(loader.import("myfile", "/path")).not_to be_empty
expect(loader.import("myfile", "/path")).to be_empty
end
end
describe "when importing all" do
let(:base) { tmpdir("base") }
let(:modulebase1) { File.join(base, "first") }
let(:modulebase2) { File.join(base, "second") }
let(:my_env) { Puppet::Node::Environment.create(:myenv, [modulebase1, modulebase2]) }
before do
# Create two module path directories
FileUtils.mkdir_p(modulebase1)
FileUtils.mkdir_p(modulebase2)
end
def mk_module(basedir, name)
PuppetSpec::Modules.create(name, basedir)
end
# We have to pass the base path so that we can
# write to modules that are in the second search path
def mk_manifests(base, mod, files)
files.collect do |file|
name = mod.name + "::" + file.gsub("/", "::")
path = File.join(base, mod.name, "manifests", file + ".pp")
FileUtils.mkdir_p(File.split(path)[0])
# write out the class
File.open(path, "w") { |f| f.print "class #{name} {}" }
name
end
end
it "should load all puppet manifests from all modules in the specified environment" do
module1 = mk_module(modulebase1, "one")
module2 = mk_module(modulebase2, "two")
mk_manifests(modulebase1, module1, %w{a b})
mk_manifests(modulebase2, module2, %w{c d})
loader.import_all
expect(loader.environment.known_resource_types.hostclass("one::a")).to be_instance_of(Puppet::Resource::Type)
expect(loader.environment.known_resource_types.hostclass("one::b")).to be_instance_of(Puppet::Resource::Type)
expect(loader.environment.known_resource_types.hostclass("two::c")).to be_instance_of(Puppet::Resource::Type)
expect(loader.environment.known_resource_types.hostclass("two::d")).to be_instance_of(Puppet::Resource::Type)
end
it "should not load manifests from duplicate modules later in the module path" do
module1 = mk_module(modulebase1, "one")
# duplicate
module2 = mk_module(modulebase2, "one")
mk_manifests(modulebase1, module1, %w{a})
mk_manifests(modulebase2, module2, %w{c})
loader.import_all
expect(loader.environment.known_resource_types.hostclass("one::c")).to be_nil
end
it "should load manifests from subdirectories" do
module1 = mk_module(modulebase1, "one")
mk_manifests(modulebase1, module1, %w{a a/b a/b/c})
loader.import_all
expect(loader.environment.known_resource_types.hostclass("one::a::b")).to be_instance_of(Puppet::Resource::Type)
expect(loader.environment.known_resource_types.hostclass("one::a::b::c")).to be_instance_of(Puppet::Resource::Type)
end
it "should skip modules that don't have manifests" do
mk_module(modulebase1, "one")
module2 = mk_module(modulebase2, "two")
mk_manifests(modulebase2, module2, %w{c d})
loader.import_all
expect(loader.environment.known_resource_types.hostclass("one::a")).to be_nil
expect(loader.environment.known_resource_types.hostclass("two::c")).to be_instance_of(Puppet::Resource::Type)
expect(loader.environment.known_resource_types.hostclass("two::d")).to be_instance_of(Puppet::Resource::Type)
end
end
describe "when parsing a file" do
it "requests a new parser instance for each file" do
parser = double('Parser', :file= => nil, :parse => empty_hostclass)
expect(Puppet::Parser::ParserFactory).to receive(:parser).twice.and_return(parser)
loader.parse_file("/my/file")
loader.parse_file("/my/other_file")
end
it "assigns the parser its file and then parses" do
parser = double('parser')
expect(Puppet::Parser::ParserFactory).to receive(:parser).and_return(parser)
expect(parser).to receive(:file=).with("/my/file")
expect(parser).to receive(:parse).and_return(empty_hostclass)
loader.parse_file("/my/file")
end
end
it "should be able to add classes to the current resource type collection" do
file = tmpfile("simple_file.pp")
File.open(file, "w") { |f| f.puts "class foo {}" }
loader.import(File.basename(file), File.dirname(file))
expect(loader.known_resource_types.hostclass("foo")).to be_instance_of(Puppet::Resource::Type)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/templatewrapper_spec.rb | spec/unit/parser/templatewrapper_spec.rb | require 'spec_helper'
require 'puppet/parser/templatewrapper'
describe Puppet::Parser::TemplateWrapper do
include PuppetSpec::Files
let(:known_resource_types) { Puppet::Resource::TypeCollection.new("env") }
let(:scope) do
compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("mynode"))
allow(compiler.environment).to receive(:known_resource_types).and_return(known_resource_types)
Puppet::Parser::Scope.new compiler
end
let(:tw) { Puppet::Parser::TemplateWrapper.new(scope) }
it "fails if a template cannot be found" do
expect(Puppet::Parser::Files).to receive(:find_template).and_return(nil)
expect { tw.file = "fake_template" }.to raise_error(Puppet::ParseError)
end
it "stringifies as template[<filename>] for a file based template" do
allow(Puppet::Parser::Files).to receive(:find_template).and_return("/tmp/fake_template")
tw.file = "fake_template"
expect(tw.to_s).to eql("template[/tmp/fake_template]")
end
it "stringifies as template[inline] for a string-based template" do
expect(tw.to_s).to eql("template[inline]")
end
it "reads and evaluates a file-based template" do
given_a_template_file("fake_template", "template contents")
tw.file = "fake_template"
expect(tw.result).to eql("template contents")
end
it "provides access to the name of the template via #file" do
full_file_name = given_a_template_file("fake_template", "<%= file %>")
tw.file = "fake_template"
expect(tw.result).to eq(full_file_name)
end
it "ignores a leading BOM" do
full_file_name = given_a_template_file("bom_template", "\uFEFF<%= file %>")
tw.file = "bom_template"
expect(tw.result).to eq(full_file_name)
end
it "evaluates a given string as a template" do
expect(tw.result("template contents")).to eql("template contents")
end
it "provides the defined classes with #classes" do
catalog = double('catalog', :classes => ["class1", "class2"])
expect(scope).to receive(:catalog).and_return(catalog)
expect(tw.classes).to eq(["class1", "class2"])
end
it "provides all the tags with #all_tags" do
catalog = double('catalog', :tags => ["tag1", "tag2"])
expect(scope).to receive(:catalog).and_return(catalog)
expect(tw.all_tags).to eq(["tag1","tag2"])
end
it "raises not implemented error" do
expect {
tw.tags
}.to raise_error(NotImplementedError, /Call 'all_tags' instead/)
end
it "raises error on access to removed in-scope variables via method calls" do
scope["in_scope_variable"] = "is good"
expect { tw.result("<%= in_scope_variable %>") }.to raise_error(/undefined local variable or method `in_scope_variable'/ )
end
it "reports that variable is available when it is in scope" do
scope["in_scope_variable"] = "is good"
expect(tw.result("<%= has_variable?('in_scope_variable') %>")).to eq("true")
end
it "reports that a variable is not available when it is not in scope" do
expect(tw.result("<%= has_variable?('not_in_scope_variable') %>")).to eq("false")
end
it "provides access to in-scope variables via instance variables" do
scope["one"] = "foo"
expect(tw.result("<%= @one %>")).to eq("foo")
end
%w{! . ; :}.each do |badchar|
it "translates #{badchar} to _ in instance variables" do
scope["one#{badchar}"] = "foo"
expect(tw.result("<%= @one_ %>")).to eq("foo")
end
end
def given_a_template_file(name, contents)
full_name = tmpfile("template_#{name}")
File.binwrite(full_name, contents)
allow(Puppet::Parser::Files).to receive(:find_template).
with(name, anything()).
and_return(full_name)
full_name
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/scope_spec.rb | spec/unit/parser/scope_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet_spec/scope'
describe Puppet::Parser::Scope do
include PuppetSpec::Scope
before :each do
@scope = Puppet::Parser::Scope.new(
Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
)
@scope.source = Puppet::Resource::Type.new(:node, :foo)
@topscope = @scope.compiler.topscope
@scope.parent = @topscope
end
describe "create_test_scope_for_node" do
let(:node_name) { "node_name_foo" }
let(:scope) { create_test_scope_for_node(node_name) }
it "should be a kind of Scope" do
expect(scope).to be_a_kind_of(Puppet::Parser::Scope)
end
it "should set the source to a node resource" do
expect(scope.source).to be_a_kind_of(Puppet::Resource::Type)
end
it "should have a compiler" do
expect(scope.compiler).to be_a_kind_of(Puppet::Parser::Compiler)
end
it "should set the parent to the compiler topscope" do
expect(scope.parent).to be(scope.compiler.topscope)
end
end
it "should generate a simple string when inspecting a scope" do
expect(@scope.inspect).to eq("Scope()")
end
it "should generate a simple string when inspecting a scope with a resource" do
@scope.resource="foo::bar"
expect(@scope.inspect).to eq("Scope(foo::bar)")
end
it "should generate a path if there is one on the puppet stack" do
result = Puppet::Pops::PuppetStack.stack('/tmp/kansas.pp', 42, @scope, 'inspect', [])
expect(result).to eq("Scope(/tmp/kansas.pp, 42)")
end
it "should generate an <env> shortened path if path points into the environment" do
env_path = @scope.environment.configuration.path_to_env
mocked_path = File.join(env_path, 'oz.pp')
result = Puppet::Pops::PuppetStack.stack(mocked_path, 42, @scope, 'inspect', [])
expect(result).to eq("Scope(<env>/oz.pp, 42)")
end
it "should generate a <module> shortened path if path points into a module" do
mocked_path = File.join(@scope.environment.full_modulepath[0], 'mymodule', 'oz.pp')
result = Puppet::Pops::PuppetStack.stack(mocked_path, 42, @scope, 'inspect', [])
expect(result).to eq("Scope(<module>/mymodule/oz.pp, 42)")
end
it "should return a scope for use in a test harness" do
expect(create_test_scope_for_node("node_name_foo")).to be_a_kind_of(Puppet::Parser::Scope)
end
it "should be able to retrieve class scopes by name" do
@scope.class_set "myname", "myscope"
expect(@scope.class_scope("myname")).to eq("myscope")
end
it "should be able to retrieve class scopes by object" do
klass = double('ast_class')
expect(klass).to receive(:name).and_return("myname")
@scope.class_set "myname", "myscope"
expect(@scope.class_scope(klass)).to eq("myscope")
end
it "should be able to retrieve its parent module name from the source of its parent type" do
@topscope.source = Puppet::Resource::Type.new(:hostclass, :foo, :module_name => "foo")
expect(@scope.parent_module_name).to eq("foo")
end
it "should return a nil parent module name if it has no parent" do
expect(@topscope.parent_module_name).to be_nil
end
it "should return a nil parent module name if its parent has no source" do
expect(@scope.parent_module_name).to be_nil
end
it "should get its environment from its compiler" do
env = Puppet::Node::Environment.create(:testing, [])
compiler = double('compiler', :environment => env, :is_a? => true)
scope = Puppet::Parser::Scope.new(compiler)
expect(scope.environment).to equal(env)
end
it "should fail if no compiler is supplied" do
expect {
Puppet::Parser::Scope.new
}.to raise_error(ArgumentError, /wrong number of arguments/)
end
it "should fail if something that isn't a compiler is supplied" do
expect {
Puppet::Parser::Scope.new(nil)
}.to raise_error(Puppet::DevError, /you must pass a compiler instance/)
end
describe "when custom functions are called" do
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new('foo', :environment => env)) }
let(:scope) { Puppet::Parser::Scope.new(compiler) }
it "calls methods prefixed with function_ as custom functions" do
expect(scope.function_sprintf(["%b", 123])).to eq("1111011")
end
it "raises an error when arguments are not passed in an Array" do
expect do
scope.function_sprintf("%b", 123)
end.to raise_error ArgumentError, /custom functions must be called with a single array that contains the arguments/
end
it "raises an error on subsequent calls when arguments are not passed in an Array" do
scope.function_sprintf(["first call"])
expect do
scope.function_sprintf("%b", 123)
end.to raise_error ArgumentError, /custom functions must be called with a single array that contains the arguments/
end
it "raises NoMethodError when the not prefixed" do
expect { scope.sprintf(["%b", 123]) }.to raise_error(NoMethodError)
end
it "raises NoMethodError when prefixed with function_ but it doesn't exist" do
expect { scope.function_fake_bs(['cows']) }.to raise_error(NoMethodError)
end
end
describe "when initializing" do
it "should extend itself with its environment's Functions module as well as the default" do
env = Puppet::Node::Environment.create(:myenv, [])
root = Puppet.lookup(:root_environment)
compiler = double('compiler', :environment => env, :is_a? => true)
scope = Puppet::Parser::Scope.new(compiler)
expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(env))
expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(root))
end
it "should extend itself with the default Functions module if its environment is the default" do
root = Puppet.lookup(:root_environment)
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
scope = Puppet::Parser::Scope.new(compiler)
expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(root))
end
end
describe "when looking up a variable" do
before :each do
Puppet[:strict] = :warning
end
it "should support :lookupvar and :setvar for backward compatibility" do
@scope.setvar("var", "yep")
expect(@scope.lookupvar("var")).to eq("yep")
end
it "should fail if invoked with a non-string name" do
expect { @scope[:foo] }.to raise_error(Puppet::ParseError, /Scope variable name .* not a string/)
expect { @scope[:foo] = 12 }.to raise_error(Puppet::ParseError, /Scope variable name .* not a string/)
end
it "should return nil for unset variables when --strict variables is not in effect" do
expect(@scope["var"]).to be_nil
end
it "answers exist? with boolean false for non existing variables" do
expect(@scope.exist?("var")).to be(false)
end
it "answers exist? with boolean false for non existing variables" do
@scope["var"] = "yep"
expect(@scope.exist?("var")).to be(true)
end
it "should be able to look up values" do
@scope["var"] = "yep"
expect(@scope["var"]).to eq("yep")
end
it "should be able to look up hashes" do
@scope["var"] = {"a" => "b"}
expect(@scope["var"]).to eq({"a" => "b"})
end
it "should be able to look up variables in parent scopes" do
@topscope["var"] = "parentval"
expect(@scope["var"]).to eq("parentval")
end
it "should prefer its own values to parent values" do
@topscope["var"] = "parentval"
@scope["var"] = "childval"
expect(@scope["var"]).to eq("childval")
end
it "should be able to detect when variables are set" do
@scope["var"] = "childval"
expect(@scope).to be_include("var")
end
it "does not allow changing a set value" do
@scope["var"] = "childval"
expect {
@scope["var"] = "change"
}.to raise_error(Puppet::Error, "Cannot reassign variable '$var'")
end
it "should be able to detect when variables are not set" do
expect(@scope).not_to be_include("var")
end
it "warns and return nil for non found unqualified variable" do
expect(Puppet).to receive(:warn_once)
expect(@scope["santa_clause"]).to be_nil
end
it "warns once for a non found variable" do
expect(Puppet).to receive(:send_log).with(:warning, be_a(String)).once
expect([@scope["santa_claus"],@scope["santa_claus"]]).to eq([nil, nil])
end
it "warns and return nil for non found qualified variable" do
expect(Puppet).to receive(:warn_once)
expect(@scope["north_pole::santa_clause"]).to be_nil
end
it "does not warn when a numeric variable is missing - they always exist" do
expect(Puppet).not_to receive(:warn_once)
expect(@scope["1"]).to be_nil
end
describe "and the variable is qualified" do
before :each do
@known_resource_types = @scope.environment.known_resource_types
node = Puppet::Node.new('localhost')
@compiler = Puppet::Parser::Compiler.new(node)
end
def newclass(name)
@known_resource_types.add Puppet::Resource::Type.new(:hostclass, name)
end
def create_class_scope(name)
klass = newclass(name)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => Puppet::Parser::Scope.new(@compiler)))
Puppet::Parser::Resource.new("class", name, :scope => @scope, :source => double('source'), :catalog => catalog).evaluate
@scope.class_scope(klass)
end
it "should be able to look up explicitly fully qualified variables from compiler's top scope" do
expect(Puppet).not_to receive(:deprecation_warning)
other_scope = @scope.compiler.topscope
other_scope["othervar"] = "otherval"
expect(@scope["::othervar"]).to eq("otherval")
end
it "should be able to look up explicitly fully qualified variables from other scopes" do
expect(Puppet).not_to receive(:deprecation_warning)
other_scope = create_class_scope("other")
other_scope["var"] = "otherval"
expect(@scope["::other::var"]).to eq("otherval")
end
it "should be able to look up deeply qualified variables" do
expect(Puppet).not_to receive(:deprecation_warning)
other_scope = create_class_scope("other::deep::klass")
other_scope["var"] = "otherval"
expect(@scope["other::deep::klass::var"]).to eq("otherval")
end
it "should return nil for qualified variables that cannot be found in other classes" do
create_class_scope("other::deep::klass")
expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should warn and return nil for qualified variables whose classes have not been evaluated" do
newclass("other::deep::klass")
expect(Puppet).to receive(:warn_once)
expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should warn and return nil for qualified variables whose classes do not exist" do
expect(Puppet).to receive(:warn_once)
expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should return nil when asked for a non-string qualified variable from a class that does not exist" do
expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should return nil when asked for a non-string qualified variable from a class that has not been evaluated" do
allow(@scope).to receive(:warning)
newclass("other::deep::klass")
expect(@scope["other::deep::klass::var"]).to be_nil
end
end
context "and strict_variables is true" do
before(:each) do
Puppet[:strict_variables] = true
end
it "should throw a symbol when unknown variable is looked up" do
expect { @scope['john_doe'] }.to throw_symbol(:undefined_variable)
end
it "should throw a symbol when unknown qualified variable is looked up" do
expect { @scope['nowhere::john_doe'] }.to throw_symbol(:undefined_variable)
end
it "should not raise an error when built in variable is looked up" do
expect { @scope['caller_module_name'] }.to_not raise_error
expect { @scope['module_name'] }.to_not raise_error
end
end
context "and strict_variables is false and --strict=off" do
before(:each) do
Puppet[:strict_variables] = false
Puppet[:strict] = :off
end
it "should not error when unknown variable is looked up and produce nil" do
expect(@scope['john_doe']).to be_nil
end
it "should not error when unknown qualified variable is looked up and produce nil" do
expect(@scope['nowhere::john_doe']).to be_nil
end
end
context "and strict_variables is false and --strict=warning" do
before(:each) do
Puppet[:strict_variables] = false
Puppet[:strict] = :warning
end
it "should not error when unknown variable is looked up" do
expect(@scope['john_doe']).to be_nil
end
it "should not error when unknown qualified variable is looked up" do
expect(@scope['nowhere::john_doe']).to be_nil
end
end
context "and strict_variables is false and --strict=error" do
before(:each) do
Puppet[:strict_variables] = false
Puppet[:strict] = :error
end
it "should raise error when unknown variable is looked up" do
expect { @scope['john_doe'] }.to raise_error(/Undefined variable/)
end
it "should not throw a symbol when unknown qualified variable is looked up" do
expect { @scope['nowhere::john_doe'] }.to raise_error(/Undefined variable/)
end
end
end
describe "when calling number?" do
it "should return nil if called with anything not a number" do
expect(Puppet::Parser::Scope.number?([2])).to be_nil
end
it "should return a Integer for an Integer" do
expect(Puppet::Parser::Scope.number?(2)).to be_a(Integer)
end
it "should return a Float for a Float" do
expect(Puppet::Parser::Scope.number?(2.34)).to be_an_instance_of(Float)
end
it "should return 234 for '234'" do
expect(Puppet::Parser::Scope.number?("234")).to eq(234)
end
it "should return nil for 'not a number'" do
expect(Puppet::Parser::Scope.number?("not a number")).to be_nil
end
it "should return 23.4 for '23.4'" do
expect(Puppet::Parser::Scope.number?("23.4")).to eq(23.4)
end
it "should return 23.4e13 for '23.4e13'" do
expect(Puppet::Parser::Scope.number?("23.4e13")).to eq(23.4e13)
end
it "should understand negative numbers" do
expect(Puppet::Parser::Scope.number?("-234")).to eq(-234)
end
it "should know how to convert exponential float numbers ala '23e13'" do
expect(Puppet::Parser::Scope.number?("23e13")).to eq(23e13)
end
it "should understand hexadecimal numbers" do
expect(Puppet::Parser::Scope.number?("0x234")).to eq(0x234)
end
it "should understand octal numbers" do
expect(Puppet::Parser::Scope.number?("0755")).to eq(0755)
end
it "should return nil on malformed integers" do
expect(Puppet::Parser::Scope.number?("0.24.5")).to be_nil
end
it "should convert strings with leading 0 to integer if they are not octal" do
expect(Puppet::Parser::Scope.number?("0788")).to eq(788)
end
it "should convert strings of negative integers" do
expect(Puppet::Parser::Scope.number?("-0788")).to eq(-788)
end
it "should return nil on malformed hexadecimal numbers" do
expect(Puppet::Parser::Scope.number?("0x89g")).to be_nil
end
end
describe "when using ephemeral variables" do
it "should store the variable value" do
@scope.set_match_data({1 => :value})
expect(@scope["1"]).to eq(:value)
end
it "should raise an error when setting numerical variable" do
expect {
@scope.setvar("1", :value3, :ephemeral => true)
}.to raise_error(Puppet::ParseError, /Cannot assign to a numeric match result variable/)
end
describe "with more than one level" do
it "should prefer latest ephemeral scopes" do
@scope.set_match_data({0 => :earliest})
@scope.new_ephemeral
@scope.set_match_data({0 => :latest})
expect(@scope["0"]).to eq(:latest)
end
it "should be able to report the current level" do
expect(@scope.ephemeral_level).to eq(1)
@scope.new_ephemeral
expect(@scope.ephemeral_level).to eq(2)
end
it "should not check presence of an ephemeral variable across multiple levels" do
@scope.new_ephemeral
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({0 => :value2})
@scope.new_ephemeral
expect(@scope.include?("1")).to be_falsey
end
it "should return false when an ephemeral variable doesn't exist in any ephemeral scope" do
@scope.new_ephemeral
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({0 => :value2})
@scope.new_ephemeral
expect(@scope.include?("2")).to be_falsey
end
it "should not get ephemeral values from earlier scope when not in later" do
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({0 => :value2})
expect(@scope.include?("1")).to be_falsey
end
describe "when using a guarded scope" do
it "should remove ephemeral scopes up to this level" do
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({1 => :value2})
@scope.with_guarded_scope do
@scope.new_ephemeral
@scope.set_match_data({1 => :value3})
end
expect(@scope["1"]).to eq(:value2)
end
end
end
end
context "when using ephemeral as local scope" do
it "should store all variables in local scope" do
@scope.new_ephemeral true
@scope.setvar("apple", :fruit)
expect(@scope["apple"]).to eq(:fruit)
end
it 'should store an undef in local scope and let it override parent scope' do
@scope['cloaked'] = 'Cloak me please'
@scope.new_ephemeral(true)
@scope['cloaked'] = nil
expect(@scope['cloaked']).to eq(nil)
end
it "should be created from a hash" do
@scope.ephemeral_from({ "apple" => :fruit, "strawberry" => :berry})
expect(@scope["apple"]).to eq(:fruit)
expect(@scope["strawberry"]).to eq(:berry)
end
end
describe "when setting ephemeral vars from matches" do
before :each do
@match = double('match', :is_a? => true)
allow(@match).to receive(:[]).with(0).and_return("this is a string")
allow(@match).to receive(:captures).and_return([])
allow(@scope).to receive(:setvar)
end
it "should accept only MatchData" do
expect {
@scope.ephemeral_from("match")
}.to raise_error(ArgumentError, /Invalid regex match data/)
end
it "should set $0 with the full match" do
# This is an internal impl detail test
expect(@scope).to receive(:new_match_scope) do |arg|
expect(arg[0]).to eq("this is a string")
end
@scope.ephemeral_from(@match)
end
it "should set every capture as ephemeral var" do
# This is an internal impl detail test
allow(@match).to receive(:[]).with(1).and_return(:capture1)
allow(@match).to receive(:[]).with(2).and_return(:capture2)
expect(@scope).to receive(:new_match_scope) do |arg|
expect(arg[1]).to eq(:capture1)
expect(arg[2]).to eq(:capture2)
end
@scope.ephemeral_from(@match)
end
it "should shadow previous match variables" do
# This is an internal impl detail test
allow(@match).to receive(:[]).with(1).and_return(:capture1)
allow(@match).to receive(:[]).with(2).and_return(:capture2)
@match2 = double('match', :is_a? => true)
allow(@match2).to receive(:[]).with(1).and_return(:capture2_1)
allow(@match2).to receive(:[]).with(2).and_return(nil)
@scope.ephemeral_from(@match)
@scope.ephemeral_from(@match2)
expect(@scope.lookupvar('2')).to eq(nil)
end
it "should create a new ephemeral level" do
level_before = @scope.ephemeral_level
@scope.ephemeral_from(@match)
expect(level_before < @scope.ephemeral_level)
end
end
describe "when managing defaults" do
it "should be able to set and lookup defaults" do
param = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source"))
@scope.define_settings(:mytype, param)
expect(@scope.lookupdefaults(:mytype)).to eq({:myparam => param})
end
it "should fail if a default is already defined and a new default is being defined" do
param = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source"))
@scope.define_settings(:mytype, param)
expect {
@scope.define_settings(:mytype, param)
}.to raise_error(Puppet::ParseError, /Default already defined .* cannot redefine/)
end
it "should return multiple defaults at once" do
param1 = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source"))
@scope.define_settings(:mytype, param1)
param2 = Puppet::Parser::Resource::Param.new(:name => :other, :value => "myvalue", :source => double("source"))
@scope.define_settings(:mytype, param2)
expect(@scope.lookupdefaults(:mytype)).to eq({:myparam => param1, :other => param2})
end
it "should look up defaults defined in parent scopes" do
param1 = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source"))
@scope.define_settings(:mytype, param1)
child_scope = @scope.newscope
param2 = Puppet::Parser::Resource::Param.new(:name => :other, :value => "myvalue", :source => double("source"))
child_scope.define_settings(:mytype, param2)
expect(child_scope.lookupdefaults(:mytype)).to eq({:myparam => param1, :other => param2})
end
end
context "#true?" do
{ "a string" => true,
"true" => true,
"false" => true,
true => true,
"" => false,
:undef => false,
nil => false
}.each do |input, output|
it "should treat #{input.inspect} as #{output}" do
expect(Puppet::Parser::Scope.true?(input)).to eq(output)
end
end
end
context "when producing a hash of all variables (as used in templates)" do
it "should contain all defined variables in the scope" do
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green })
end
it "should contain variables in all local scopes (#21508)" do
@scope.new_ephemeral true
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.new_ephemeral true
@scope.setvar("apple", :red)
expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green, 'apple' => :red })
end
it "should contain all defined variables in the scope and all local scopes" do
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.new_ephemeral true
@scope.setvar("apple", :red)
expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green, 'apple' => :red })
end
it "should not contain varaibles in match scopes (non local emphemeral)" do
@scope.new_ephemeral true
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.ephemeral_from(/(f)(o)(o)/.match('foo'))
expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green })
end
it "should delete values that are :undef in inner scope" do
@scope.new_ephemeral true
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.new_ephemeral true
@scope.setvar("apple", :red)
@scope.setvar("orange", :undef)
expect(@scope.to_hash).to eq({'pear' => :green, 'apple' => :red })
end
it "should not delete values that are :undef in inner scope when include_undef is true" do
@scope.new_ephemeral true
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.new_ephemeral true
@scope.setvar("apple", :red)
@scope.setvar("orange", :undef)
expect(@scope.to_hash(true, true)).to eq({'pear' => :green, 'apple' => :red, 'orange' => :undef })
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/files_spec.rb | spec/unit/parser/files_spec.rb | require 'spec_helper'
require 'puppet/parser/files'
describe Puppet::Parser::Files do
include PuppetSpec::Files
let(:modulepath) { tmpdir("modulepath") }
let(:environment) { Puppet::Node::Environment.create(:testing, [modulepath]) }
let(:mymod) { File.join(modulepath, "mymod") }
let(:mymod_files) { File.join(mymod, "files") }
let(:mymod_a_file) { File.join(mymod_files, "some.txt") }
let(:mymod_templates) { File.join(mymod, "templates") }
let(:mymod_a_template) { File.join(mymod_templates, "some.erb") }
let(:mymod_manifests) { File.join(mymod, "manifests") }
let(:mymod_init_manifest) { File.join(mymod_manifests, "init.pp") }
let(:mymod_another_manifest) { File.join(mymod_manifests, "another.pp") }
let(:an_absolute_file_path_outside_of_module) { make_absolute("afilenamesomewhere") }
before do
FileUtils.mkdir_p(mymod_files)
File.open(mymod_a_file, 'w') do |f|
f.puts('something')
end
FileUtils.mkdir_p(mymod_templates)
File.open(mymod_a_template, 'w') do |f|
f.puts('<%= "something" %>')
end
FileUtils.mkdir_p(mymod_manifests)
File.open(mymod_init_manifest, 'w') do |f|
f.puts('class mymod { }')
end
File.open(mymod_another_manifest, 'w') do |f|
f.puts('class mymod::another { }')
end
end
describe "when searching for files" do
it "returns fully-qualified file names directly" do
expect(Puppet::Parser::Files.find_file(an_absolute_file_path_outside_of_module, environment)).to eq(an_absolute_file_path_outside_of_module)
end
it "returns the full path to the file if given a modulename/relative_filepath selector " do
expect(Puppet::Parser::Files.find_file("mymod/some.txt", environment)).to eq(mymod_a_file)
end
it "returns nil if the module is not found" do
expect(Puppet::Parser::Files.find_file("mod_does_not_exist/myfile", environment)).to be_nil
end
it "also returns nil if the module is found, but the file is not" do
expect(Puppet::Parser::Files.find_file("mymod/file_does_not_exist", environment)).to be_nil
end
end
describe "when searching for templates" do
it "returns fully-qualified templates directly" do
expect(Puppet::Parser::Files.find_template(an_absolute_file_path_outside_of_module, environment)).to eq(an_absolute_file_path_outside_of_module)
end
it "returns the full path to the template if given a modulename/relative_templatepath selector" do
expect(Puppet::Parser::Files.find_template("mymod/some.erb", environment)).to eq(mymod_a_template)
end
it "returns nil if the module is not found" do
expect(Puppet::Parser::Files.find_template("module_does_not_exist/mytemplate", environment)).to be_nil
end
it "returns nil if the module is found, but the template is not " do
expect(Puppet::Parser::Files.find_template("mymod/template_does_not_exist", environment)).to be_nil
end
end
describe "when searching for manifests in a module" do
let(:no_manifests_found) { [nil, []] }
it "ignores invalid module names" do
expect(Puppet::Parser::Files.find_manifests_in_modules("mod.has.invalid.name/init.pp", environment)).to eq(no_manifests_found)
end
it "returns no files when no module is found" do
expect(Puppet::Parser::Files.find_manifests_in_modules("not_here_module/init.pp", environment)).to eq(no_manifests_found)
end
it "returns the name of the module and the manifests from the first found module" do
expect(Puppet::Parser::Files.find_manifests_in_modules("mymod/init.pp", environment)
).to eq(["mymod", [mymod_init_manifest]])
end
it "always includes init.pp if present" do
expect(Puppet::Parser::Files.find_manifests_in_modules("mymod/another.pp", environment)
).to eq(["mymod", [mymod_init_manifest, mymod_another_manifest]])
end
it "does not find the module when it is a different environment" do
different_env = Puppet::Node::Environment.create(:different, [])
expect(Puppet::Parser::Files.find_manifests_in_modules("mymod/init.pp", different_env)).to eq(no_manifests_found)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions_spec.rb | spec/unit/parser/functions_spec.rb | require 'spec_helper'
describe Puppet::Parser::Functions do
def callable_functions_from(mod)
Class.new { include mod }.new
end
let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) }
let(:environment) { Puppet::Node::Environment.create(:myenv, []) }
before do
Puppet::Parser::Functions.reset
end
it "should have a method for returning an environment-specific module" do
expect(Puppet::Parser::Functions.environment_module(environment)).to be_instance_of(Module)
end
describe "when calling newfunction" do
it "should create the function in the environment module" do
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
expect(function_module).to be_method_defined :function_name
end
it "should warn if the function already exists" do
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
expect(Puppet).to receive(:warning)
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
end
it "should raise an error if the function type is not correct" do
expect { Puppet::Parser::Functions.newfunction("name", :type => :unknown) { |args| } }.to raise_error Puppet::DevError, "Invalid statement type :unknown"
end
it "instruments the function to profile the execution" do
messages = []
Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::WallClock.new(proc { |msg| messages << msg }, "id"))
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
callable_functions_from(function_module).function_name([])
expect(messages.first).to match(/Called name/)
end
end
describe "when calling function to test function existence" do
before :each do
Puppet[:strict] = :error
end
it "emits a deprecation warning when loading all 3.x functions" do
allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:loadall)
Puppet::Parser::Functions.autoloader.loadall
expect(@logs.map(&:to_s)).to include(/The method 'Puppet::Parser::Functions.autoloader#loadall' is deprecated in favor of using 'Scope#call_function/)
end
it "emits a deprecation warning when loading a single 3.x function" do
allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:load)
Puppet::Parser::Functions.autoloader.load('beatles')
expect(@logs.map(&:to_s)).to include(/The method 'Puppet::Parser::Functions.autoloader#load\("beatles"\)' is deprecated in favor of using 'Scope#call_function'/)
end
it "emits a deprecation warning when checking if a 3x function is loaded" do
allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:loaded?).and_return(false)
Puppet::Parser::Functions.autoloader.loaded?('beatles')
expect(@logs.map(&:to_s)).to include(/The method 'Puppet::Parser::Functions.autoloader#loaded\?\(\"beatles\"\)' is deprecated in favor of using 'Scope#call_function'/)
end
it "should return false if the function doesn't exist" do
allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:load)
expect(Puppet::Parser::Functions.function("name")).to be_falsey
end
it "should return its name if the function exists" do
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
expect(Puppet::Parser::Functions.function("name")).to eq("function_name")
end
it "should try to autoload the function if it doesn't exist yet" do
expect(Puppet::Parser::Functions.autoloader.delegatee).to receive(:load)
Puppet::Parser::Functions.function("name")
end
it "combines functions from the root with those from the current environment" do
Puppet.override(:current_environment => Puppet.lookup(:root_environment)) do
Puppet::Parser::Functions.newfunction("onlyroot", :type => :rvalue) do |args|
end
end
Puppet.override(:current_environment => Puppet::Node::Environment.create(:other, [])) do
Puppet::Parser::Functions.newfunction("other_env", :type => :rvalue) do |args|
end
expect(Puppet::Parser::Functions.function("onlyroot")).to eq("function_onlyroot")
expect(Puppet::Parser::Functions.function("other_env")).to eq("function_other_env")
end
expect(Puppet::Parser::Functions.function("other_env")).to be_falsey
end
end
describe "when calling function to test arity" do
let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) }
it "should raise an error if the function is called with too many arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| }
expect { callable_functions_from(function_module).function_name([1,2,3]) }.to raise_error ArgumentError
end
it "should raise an error if the function is called with too few arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| }
expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError
end
it "should not raise an error if the function is called with correct number of arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| }
expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error
end
it "should raise an error if the variable arg function is called with too few arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| }
expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError
end
it "should not raise an error if the variable arg function is called with correct number of arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| }
expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error
end
it "should not raise an error if the variable arg function is called with more number of arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| }
expect { callable_functions_from(function_module).function_name([1,2,3]) }.to_not raise_error
end
end
describe "::arity" do
it "returns the given arity of a function" do
Puppet::Parser::Functions.newfunction("name", :arity => 4) { |args| }
expect(Puppet::Parser::Functions.arity(:name)).to eq(4)
end
it "returns -1 if no arity is given" do
Puppet::Parser::Functions.newfunction("name") { |args| }
expect(Puppet::Parser::Functions.arity(:name)).to eq(-1)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/resource_spec.rb | spec/unit/parser/resource_spec.rb | require 'spec_helper'
describe Puppet::Parser::Resource do
before do
environment = Puppet::Node::Environment.create(:testing, [])
@node = Puppet::Node.new("yaynode", :environment => environment)
@known_resource_types = environment.known_resource_types
@compiler = Puppet::Parser::Compiler.new(@node)
@source = newclass ""
@scope = @compiler.topscope
end
def mkresource(args = {})
args[:source] ||= @source
args[:scope] ||= @scope
params = args[:parameters] || {:one => "yay", :three => "rah"}
if args[:parameters] == :none
args.delete(:parameters)
elsif not args[:parameters].is_a? Array
args[:parameters] = paramify(args[:source], params)
end
Puppet::Parser::Resource.new("resource", "testing", args)
end
def param(name, value, source)
Puppet::Parser::Resource::Param.new(:name => name, :value => value, :source => source)
end
def paramify(source, hash)
hash.collect do |name, value|
Puppet::Parser::Resource::Param.new(
:name => name, :value => value, :source => source
)
end
end
def newclass(name)
@known_resource_types.add Puppet::Resource::Type.new(:hostclass, name)
end
def newdefine(name)
@known_resource_types.add Puppet::Resource::Type.new(:definition, name)
end
def newnode(name)
@known_resource_types.add Puppet::Resource::Type.new(:node, name)
end
it "should get its environment from its scope" do
scope = double('scope', :source => double("source"))
expect(scope).to receive(:environment).and_return("foo").at_least(:once)
expect(scope).to receive(:lookupdefaults).and_return({})
expect(Puppet::Parser::Resource.new("file", "whatever", :scope => scope).environment).to eq("foo")
end
it "should use the scope's environment as its environment" do
expect(@scope).to receive(:environment).and_return("myenv").at_least(:once)
expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope).environment).to eq("myenv")
end
it "should be isomorphic if it is builtin and models an isomorphic type" do
expect(Puppet::Type.type(:file)).to receive(:isomorphic?).and_return(true)
@resource = expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_truthy
end
it "should not be isomorphic if it is builtin and models a non-isomorphic type" do
expect(Puppet::Type.type(:file)).to receive(:isomorphic?).and_return(false)
@resource = expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_falsey
end
it "should be isomorphic if it is not builtin" do
newdefine "whatever"
@resource = expect(Puppet::Parser::Resource.new("whatever", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_truthy
end
it "should have an array-indexing method for retrieving parameter values" do
@resource = mkresource
expect(@resource[:one]).to eq("yay")
end
it "should use a Puppet::Resource for converting to a ral resource" do
trans = double('resource', :to_ral => "yay")
@resource = mkresource
expect(@resource).to receive(:copy_as_resource).and_return(trans)
expect(@resource.to_ral).to eq("yay")
end
it "should be able to use the indexing operator to access parameters" do
resource = Puppet::Parser::Resource.new("resource", "testing", :source => "source", :scope => @scope)
resource["foo"] = "bar"
expect(resource["foo"]).to eq("bar")
end
it "should return the title when asked for a parameter named 'title'" do
expect(Puppet::Parser::Resource.new("resource", "testing", :source => @source, :scope => @scope)[:title]).to eq("testing")
end
describe "when initializing" do
before do
@arguments = {:scope => @scope}
end
it "should fail unless hash is specified" do
expect {
Puppet::Parser::Resource.new('file', '/my/file', nil)
}.to raise_error(ArgumentError, /Resources require a hash as last argument/)
end
it "should attempt to externalize filepaths via the environment" do
environment = Puppet::Node::Environment.create(:testing, [])
expect(environment).to receive(:externalize_path).at_least(:once).and_return("foo")
Puppet[:code] = "notify { 'hello': }"
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone', environment: environment)
notify = catalog.resource('Notify[hello]')
expect(notify.file).to eq("foo")
end
it "should set the reference correctly" do
res = Puppet::Parser::Resource.new("resource", "testing", @arguments)
expect(res.ref).to eq("Resource[testing]")
end
it "should be tagged with user tags" do
tags = [ "tag1", "tag2" ]
@arguments[:parameters] = [ param(:tag, tags , :source) ]
res = Puppet::Parser::Resource.new("resource", "testing", @arguments)
expect(res).to be_tagged("tag1")
expect(res).to be_tagged("tag2")
end
end
describe "when evaluating" do
before do
@catalog = Puppet::Resource::Catalog.new
source = double('source')
allow(source).to receive(:module_name)
@scope = Puppet::Parser::Scope.new(@compiler, :source => source)
@catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => @scope))
end
it "should evaluate the associated AST definition" do
definition = newdefine "mydefine"
res = Puppet::Parser::Resource.new("mydefine", "whatever", :scope => @scope, :source => @source, :catalog => @catalog)
expect(definition).to receive(:evaluate_code).with(res)
res.evaluate
end
it "should evaluate the associated AST class" do
@class = newclass "myclass"
res = Puppet::Parser::Resource.new("class", "myclass", :scope => @scope, :source => @source, :catalog => @catalog)
expect(@class).to receive(:evaluate_code).with(res)
res.evaluate
end
it "should evaluate the associated AST node" do
nodedef = newnode("mynode")
res = Puppet::Parser::Resource.new("node", "mynode", :scope => @scope, :source => @source, :catalog => @catalog)
expect(nodedef).to receive(:evaluate_code).with(res)
res.evaluate
end
it "should add an edge to any specified stage for class resources" do
@compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
other_stage = Puppet::Parser::Resource.new(:stage, "other", :scope => @scope, :catalog => @catalog)
@compiler.add_resource(@scope, other_stage)
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
resource[:stage] = 'other'
@compiler.add_resource(@scope, resource)
resource.evaluate
expect(@compiler.catalog.edge?(other_stage, resource)).to be_truthy
end
it "should fail if an unknown stage is specified" do
@compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
resource[:stage] = 'other'
expect { resource.evaluate }.to raise_error(ArgumentError, /Could not find stage other specified by/)
end
it "should add edges from the class resources to the parent's stage if no stage is specified" do
foo_stage = Puppet::Parser::Resource.new(:stage, :foo_stage, :scope => @scope, :catalog => @catalog)
@compiler.add_resource(@scope, foo_stage)
@compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
resource[:stage] = 'foo_stage'
@compiler.add_resource(@scope, resource)
resource.evaluate
expect(@compiler.catalog).to be_edge(foo_stage, resource)
end
it 'should allow a resource reference to be undef' do
Puppet[:code] = "notify { 'hello': message=>'yo', notify => undef }"
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]}
expect(edges).to include(['Class[main]', 'Notify[hello]'])
end
it 'should evaluate class in the same file without include' do
Puppet[:code] = <<-MANIFEST
class a($myvar = 'hello') {}
class { 'a': myvar => 'goodbye' }
notify { $a::myvar: }
MANIFEST
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
expect(catalog.resource('Notify[goodbye]')).to be_a(Puppet::Resource)
end
it "should allow edges to propagate multiple levels down the scope hierarchy" do
Puppet[:code] = <<-MANIFEST
stage { before: before => Stage[main] }
class alpha {
include beta
}
class beta {
include gamma
}
class gamma { }
class { alpha: stage => before }
MANIFEST
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
# Stringify them to make for easier lookup
edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]}
expect(edges).to include(["Stage[before]", "Class[Alpha]"])
expect(edges).to include(["Stage[before]", "Class[Beta]"])
expect(edges).to include(["Stage[before]", "Class[Gamma]"])
end
it "should use the specified stage even if the parent scope specifies one" do
Puppet[:code] = <<-MANIFEST
stage { before: before => Stage[main], }
stage { after: require => Stage[main], }
class alpha {
class { beta: stage => after }
}
class beta { }
class { alpha: stage => before }
MANIFEST
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]}
expect(edges).to include(["Stage[before]", "Class[Alpha]"])
expect(edges).to include(["Stage[after]", "Class[Beta]"])
end
it "should add edges from top-level class resources to the main stage if no stage is specified" do
main = @compiler.catalog.resource(:stage, :main)
@compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
@compiler.add_resource(@scope, resource)
resource.evaluate
expect(@compiler.catalog).to be_edge(main, resource)
end
it 'should assign default value to generated resource' do
Puppet[:code] = <<-PUPPET
define one($var) {
notify { "${var} says hello": }
}
define two($x = $title) {
One {
var => $x
}
one { a: }
one { b: var => 'bill'}
}
two { 'bob': }
PUPPET
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]}
expect(edges).to include(['One[a]', 'Notify[bob says hello]'])
expect(edges).to include(['One[b]', 'Notify[bill says hello]'])
end
it 'should override default value with new value' do
Puppet[:code] = <<-PUPPET.unindent
class foo {
File {
ensure => file,
mode => '644',
owner => 'root',
group => 'root',
}
file { '/tmp/foo':
ensure => directory
}
File['/tmp/foo'] { mode => '0755' }
}
include foo
PUPPET
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
file = catalog.resource('File[/tmp/foo]')
expect(file).to be_a(Puppet::Resource)
expect(file['mode']).to eql('0755')
end
end
describe 'when evaluating resource defaults' do
let(:resource) { Puppet::Parser::Resource.new('file', 'whatever', :scope => @scope, :source => @source) }
it 'should add all defaults available from the scope' do
expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => param(:owner, 'default', @source))
expect(resource[:owner]).to eq('default')
end
it 'should not replace existing parameters with defaults' do
expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => param(:owner, 'replaced', @source))
r = Puppet::Parser::Resource.new('file', 'whatever', :scope => @scope, :source => @source, :parameters => [ param(:owner, 'oldvalue', @source) ])
expect(r[:owner]).to eq('oldvalue')
end
it 'should override defaults with new parameters' do
expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => param(:owner, 'replaced', @source))
resource.set_parameter(:owner, 'newvalue')
expect(resource[:owner]).to eq('newvalue')
end
it 'should add a copy of each default, rather than the actual default parameter instance' do
newparam = param(:owner, 'default', @source)
other = newparam.dup
other.value = "other"
expect(newparam).to receive(:dup).and_return(other)
expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => newparam)
expect(resource[:owner]).to eq('other')
end
it "should tag with value of default parameter named 'tag'" do
expect(@scope).to receive(:lookupdefaults).with('File').and_return(:tag => param(:tag, 'the_tag', @source))
expect(resource.tags).to include('the_tag')
end
end
describe "when finishing" do
before do
@resource = Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source)
end
it "should do nothing if it has already been finished" do
@resource.finish
expect(@resource).not_to receive(:add_scope_tags)
@resource.finish
end
it "converts parameters with Sensitive values to unwrapped values and metadata" do
@resource[:content] = Puppet::Pops::Types::PSensitiveType::Sensitive.new("hunter2")
@resource.finish
expect(@resource[:content]).to eq "hunter2"
expect(@resource.sensitive_parameters).to eq [:content]
end
end
describe "when being tagged" do
before do
@scope_resource = double('scope_resource', :tags => %w{srone srtwo})
allow(@scope).to receive(:resource).and_return(@scope_resource)
@resource = Puppet::Parser::Resource.new("file", "yay", :scope => @scope, :source => double('source'))
end
it "should get tagged with the resource type" do
expect(@resource.tags).to be_include("file")
end
it "should get tagged with the title" do
expect(@resource.tags).to be_include("yay")
end
it "should get tagged with each name in the title if the title is a qualified class name" do
resource = Puppet::Parser::Resource.new("file", "one::two", :scope => @scope, :source => double('source'))
expect(resource.tags).to be_include("one")
expect(resource.tags).to be_include("two")
end
it "should get tagged with each name in the type if the type is a qualified class name" do
resource = Puppet::Parser::Resource.new("one::two", "whatever", :scope => @scope, :source => double('source'))
expect(resource.tags).to be_include("one")
expect(resource.tags).to be_include("two")
end
it "should not get tagged with non-alphanumeric titles" do
resource = Puppet::Parser::Resource.new("file", "this is a test", :scope => @scope, :source => double('source'))
expect(resource.tags).not_to be_include("this is a test")
end
it "should fail on tags containing '*' characters" do
expect { @resource.tag("bad*tag") }.to raise_error(Puppet::ParseError)
end
it "should fail on tags starting with '-' characters" do
expect { @resource.tag("-badtag") }.to raise_error(Puppet::ParseError)
end
it "should fail on tags containing ' ' characters" do
expect { @resource.tag("bad tag") }.to raise_error(Puppet::ParseError)
end
it "should allow alpha tags" do
expect { @resource.tag("good_tag") }.to_not raise_error
end
end
describe "when merging overrides" do
def resource_type(name)
double(name, :child_of? => false)
end
before do
@source = resource_type("source1")
@resource = mkresource :source => @source
@override = mkresource :source => @source
end
it "should fail when the override was not created by a parent class" do
@override.source = resource_type("source2")
expect(@override.source).to receive(:child_of?).with(@source).and_return(false)
expect { @resource.merge(@override) }.to raise_error(Puppet::ParseError)
end
it "should succeed when the override was created in the current scope" do
@source3 = resource_type("source3")
@resource.source = @source3
@override.source = @resource.source
expect(@override.source).not_to receive(:child_of?).with(@source3)
params = {:a => :b, :c => :d}
expect(@override).to receive(:parameters).and_return(params)
expect(@resource).to receive(:override_parameter).with(:b)
expect(@resource).to receive(:override_parameter).with(:d)
@resource.merge(@override)
end
it "should succeed when a parent class created the override" do
@source3 = resource_type("source3")
@resource.source = @source3
@override.source = resource_type("source4")
expect(@override.source).to receive(:child_of?).with(@source3).and_return(true)
params = {:a => :b, :c => :d}
expect(@override).to receive(:parameters).and_return(params)
expect(@resource).to receive(:override_parameter).with(:b)
expect(@resource).to receive(:override_parameter).with(:d)
@resource.merge(@override)
end
it "should add new parameters when the parameter is not set" do
allow(@source).to receive(:child_of?).and_return(true)
@override.set_parameter(:testing, "value")
@resource.merge(@override)
expect(@resource[:testing]).to eq("value")
end
it "should replace existing parameter values" do
allow(@source).to receive(:child_of?).and_return(true)
@resource.set_parameter(:testing, "old")
@override.set_parameter(:testing, "value")
@resource.merge(@override)
expect(@resource[:testing]).to eq("value")
end
it "should add values to the parameter when the override was created with the '+>' syntax" do
allow(@source).to receive(:child_of?).and_return(true)
param = Puppet::Parser::Resource::Param.new(:name => :testing, :value => "testing", :source => @resource.source)
param.add = true
@override.set_parameter(param)
@resource.set_parameter(:testing, "other")
@resource.merge(@override)
expect(@resource[:testing]).to eq(%w{other testing})
end
it "should not merge parameter values when multiple resources are overriden with '+>' at once " do
@resource_2 = mkresource :source => @source
@resource. set_parameter(:testing, "old_val_1")
@resource_2.set_parameter(:testing, "old_val_2")
allow(@source).to receive(:child_of?).and_return(true)
param = Puppet::Parser::Resource::Param.new(:name => :testing, :value => "new_val", :source => @resource.source)
param.add = true
@override.set_parameter(param)
@resource. merge(@override)
@resource_2.merge(@override)
expect(@resource [:testing]).to eq(%w{old_val_1 new_val})
expect(@resource_2[:testing]).to eq(%w{old_val_2 new_val})
end
it "should promote tag overrides to real tags" do
allow(@source).to receive(:child_of?).and_return(true)
param = Puppet::Parser::Resource::Param.new(:name => :tag, :value => "testing", :source => @resource.source)
@override.set_parameter(param)
@resource.merge(@override)
expect(@resource.tagged?("testing")).to be_truthy
end
end
it "should be able to be converted to a normal resource" do
@source = double('scope', :name => "myscope")
@resource = mkresource :source => @source
expect(@resource).to respond_to(:copy_as_resource)
end
describe "when being converted to a resource" do
before do
@parser_resource = mkresource :scope => @scope, :parameters => {:foo => "bar", :fee => "fum"}
end
it "should create an instance of Puppet::Resource" do
expect(@parser_resource.copy_as_resource).to be_instance_of(Puppet::Resource)
end
it "should set the type correctly on the Puppet::Resource" do
expect(@parser_resource.copy_as_resource.type).to eq(@parser_resource.type)
end
it "should set the title correctly on the Puppet::Resource" do
expect(@parser_resource.copy_as_resource.title).to eq(@parser_resource.title)
end
it "should copy over all of the parameters" do
result = @parser_resource.copy_as_resource.to_hash
# The name will be in here, also.
expect(result[:foo]).to eq("bar")
expect(result[:fee]).to eq("fum")
end
it "should copy over the tags" do
@parser_resource.tag "foo"
@parser_resource.tag "bar"
expect(@parser_resource.copy_as_resource.tags).to eq(@parser_resource.tags)
end
it "should copy over the line" do
@parser_resource.line = 40
expect(@parser_resource.copy_as_resource.line).to eq(40)
end
it "should copy over the file" do
@parser_resource.file = "/my/file"
expect(@parser_resource.copy_as_resource.file).to eq("/my/file")
end
it "should copy over the 'exported' value" do
@parser_resource.exported = true
expect(@parser_resource.copy_as_resource.exported).to be_truthy
end
it "should copy over the 'virtual' value" do
@parser_resource.virtual = true
expect(@parser_resource.copy_as_resource.virtual).to be_truthy
end
it "should convert any parser resource references to Puppet::Resource instances" do
ref = Puppet::Resource.new("file", "/my/file")
@parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ref}
result = @parser_resource.copy_as_resource
expect(result[:fee]).to eq(Puppet::Resource.new(:file, "/my/file"))
end
it "should convert any parser resource references to Puppet::Resource instances even if they are in an array" do
ref = Puppet::Resource.new("file", "/my/file")
@parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ["a", ref]}
result = @parser_resource.copy_as_resource
expect(result[:fee]).to eq(["a", Puppet::Resource.new(:file, "/my/file")])
end
it "should convert any parser resource references to Puppet::Resource instances even if they are in an array of array, and even deeper" do
ref1 = Puppet::Resource.new("file", "/my/file1")
ref2 = Puppet::Resource.new("file", "/my/file2")
@parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ["a", [ref1,ref2]]}
result = @parser_resource.copy_as_resource
expect(result[:fee]).to eq(["a", Puppet::Resource.new(:file, "/my/file1"), Puppet::Resource.new(:file, "/my/file2")])
end
it "should fail if the same param is declared twice" do
expect do
@parser_resource = mkresource :source => @source, :parameters => [
Puppet::Parser::Resource::Param.new(
:name => :foo, :value => "bar", :source => @source
),
Puppet::Parser::Resource::Param.new(
:name => :foo, :value => "baz", :source => @source
)
]
end.to raise_error(Puppet::ParseError)
end
end
describe "when setting parameters" do
before do
@source = newclass "foobar"
@resource = Puppet::Parser::Resource.new :foo, "bar", :scope => @scope, :source => @source
end
it "should accept Param instances and add them to the parameter list" do
param = Puppet::Parser::Resource::Param.new :name => "foo", :value => "bar", :source => @source
@resource.set_parameter(param)
expect(@resource["foo"]).to eq("bar")
end
it "should allow parameters to be set to 'false'" do
@resource.set_parameter("myparam", false)
expect(@resource["myparam"]).to be_falsey
end
it "should use its source when provided a parameter name and value" do
@resource.set_parameter("myparam", "myvalue")
expect(@resource["myparam"]).to eq("myvalue")
end
end
# part of #629 -- the undef keyword. Make sure 'undef' params get skipped.
it "should not include 'undef' parameters when converting itself to a hash" do
resource = Puppet::Parser::Resource.new "file", "/tmp/testing", :source => double("source"), :scope => @scope
resource[:owner] = :undef
resource[:mode] = "755"
expect(resource.to_hash[:owner]).to be_nil
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/compiler_spec.rb | spec/unit/parser/compiler_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
class CompilerTestResource
attr_accessor :builtin, :virtual, :evaluated, :type, :title
def initialize(type, title)
@type = type
@title = title
end
def [](attr)
return nil if (attr == :stage || attr == :alias)
:main
end
def ref
"#{type.to_s.capitalize}[#{title}]"
end
def evaluated?
@evaluated
end
def builtin_type?
@builtin
end
def virtual?
@virtual
end
def class?
false
end
def stage?
false
end
def evaluate
end
def file
"/fake/file/goes/here"
end
def line
"42"
end
def resource_type
self.class
end
end
describe Puppet::Parser::Compiler do
include PuppetSpec::Files
include Matchers::Resource
def resource(type, title)
Puppet::Parser::Resource.new(type, title, :scope => @scope)
end
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
before :each do
# Push me faster, I wanna go back in time! (Specifically, freeze time
# across the test since we have a bunch of version == timestamp code
# hidden away in the implementation and we keep losing the race.)
# --daniel 2011-04-21
now = Time.now
allow(Time).to receive(:now).and_return(now)
@node = Puppet::Node.new("testnode",
:facts => Puppet::Node::Facts.new("facts", {}),
:environment => environment)
@known_resource_types = environment.known_resource_types
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = Puppet::Parser::Scope.new(@compiler, :source => double('source'))
@scope_resource = Puppet::Parser::Resource.new(:file, "/my/file", :scope => @scope)
@scope.resource = @scope_resource
end
it "should fail intelligently when a class-level compile fails" do
expect(Puppet::Parser::Compiler).to receive(:new).and_raise(ArgumentError)
expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error)
end
it "should use the node's environment as its environment" do
expect(@compiler.environment).to equal(@node.environment)
end
it "fails if the node's environment has validation errors" do
conflicted_environment = Puppet::Node::Environment.create(:testing, [], '/some/environment.conf/manifest.pp')
allow(conflicted_environment).to receive(:validation_errors).and_return(['bad environment'])
@node.environment = conflicted_environment
expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error, /Compilation has been halted because.*bad environment/)
end
it "should be able to return a class list containing all added classes" do
@compiler.add_class ""
@compiler.add_class "one"
@compiler.add_class "two"
expect(@compiler.classlist.sort).to eq(%w{one two}.sort)
end
describe "when initializing" do
it 'should not create the settings class more than once' do
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
Puppet[:code] = 'undef'
@compiler.compile
@compiler = Puppet::Parser::Compiler.new(@node)
Puppet[:code] = 'undef'
@compiler.compile
end
warnings = logs.select { |log| log.level == :warning }.map { |log| log.message }
expect(warnings).not_to include(/Class 'settings' is already defined/)
end
it "should set its node attribute" do
expect(@compiler.node).to equal(@node)
end
it "the set of ast_nodes should be empty" do
expect(@compiler.environment.known_resource_types.nodes?).to be_falsey
end
it "should copy the known_resource_types version to the catalog" do
expect(@compiler.catalog.version).to eq(@known_resource_types.version)
end
it "should copy any node classes into the class list" do
node = Puppet::Node.new("mynode")
node.classes = %w{foo bar}
compiler = Puppet::Parser::Compiler.new(node)
expect(compiler.classlist).to match_array(['foo', 'bar'])
end
it "should transform node class hashes into a class list" do
node = Puppet::Node.new("mynode")
node.classes = {'foo'=>{'one'=>'p1'}, 'bar'=>{'two'=>'p2'}}
compiler = Puppet::Parser::Compiler.new(node)
expect(compiler.classlist).to match_array(['foo', 'bar'])
end
it "should return a catalog with the specified code_id" do
node = Puppet::Node.new("mynode")
code_id = 'b59e5df0578ef411f773ee6c33d8073c50e7b8fe'
compiler = Puppet::Parser::Compiler.new(node, :code_id => code_id)
expect(compiler.catalog.code_id).to eq(code_id)
end
it "should add a 'main' stage to the catalog" do
expect(@compiler.catalog.resource(:stage, :main)).to be_instance_of(Puppet::Parser::Resource)
end
end
describe "sanitize_node" do
it "should delete trusted from parameters" do
node = Puppet::Node.new("mynode")
node.parameters['trusted'] = { :a => 42 }
node.parameters['preserve_me'] = 'other stuff'
compiler = Puppet::Parser::Compiler.new(node)
sanitized = compiler.node
expect(sanitized.parameters['trusted']).to eq(nil)
expect(sanitized.parameters['preserve_me']).to eq('other stuff')
end
it "should not report trusted_data if trusted is false" do
node = Puppet::Node.new("mynode")
node.parameters['trusted'] = false
compiler = Puppet::Parser::Compiler.new(node)
sanitized = compiler.node
expect(sanitized.trusted_data).to_not eq(false)
end
it "should not report trusted_data if trusted is not a hash" do
node = Puppet::Node.new("mynode")
node.parameters['trusted'] = 'not a hash'
compiler = Puppet::Parser::Compiler.new(node)
sanitized = compiler.node
expect(sanitized.trusted_data).to_not eq('not a hash')
end
it "should not report trusted_data if trusted hash doesn't include known keys" do
node = Puppet::Node.new("mynode")
node.parameters['trusted'] = { :a => 42 }
compiler = Puppet::Parser::Compiler.new(node)
sanitized = compiler.node
expect(sanitized.trusted_data).to_not eq({ :a => 42 })
end
it "should prefer trusted_data in the node above other plausible sources" do
node = Puppet::Node.new("mynode")
node.trusted_data = { 'authenticated' => true,
'certname' => 'the real deal',
'extensions' => 'things' }
node.parameters['trusted'] = { 'authenticated' => true,
'certname' => 'not me',
'extensions' => 'things' }
compiler = Puppet::Parser::Compiler.new(node)
sanitized = compiler.node
expect(sanitized.trusted_data).to eq({ 'authenticated' => true,
'certname' => 'the real deal',
'extensions' => 'things' })
end
end
describe "when managing scopes" do
it "should create a top scope" do
expect(@compiler.topscope).to be_instance_of(Puppet::Parser::Scope)
end
it "should be able to create new scopes" do
expect(@compiler.newscope(@compiler.topscope)).to be_instance_of(Puppet::Parser::Scope)
end
it "should set the parent scope of the new scope to be the passed-in parent" do
scope = double('scope')
newscope = @compiler.newscope(scope)
expect(newscope.parent).to equal(scope)
end
it "should set the parent scope of the new scope to its topscope if the parent passed in is nil" do
newscope = @compiler.newscope(nil)
expect(newscope.parent).to equal(@compiler.topscope)
end
end
describe "when compiling" do
it "should set node parameters as variables in the top scope" do
params = {"a" => "b", "c" => "d"}
allow(@node).to receive(:parameters).and_return(params)
@compiler.compile
expect(@compiler.topscope['a']).to eq("b")
expect(@compiler.topscope['c']).to eq("d")
end
it "should set node parameters that are of Symbol type as String variables in the top scope" do
params = {"a" => :b}
allow(@node).to receive(:parameters).and_return(params)
@compiler.compile
expect(@compiler.topscope['a']).to eq("b")
end
it "should set the node's environment as a string variable in top scope" do
@node.merge({'wat' => 'this is how the sausage is made'})
@compiler.compile
expect(@compiler.topscope['environment']).to eq("testing")
expect(@compiler.topscope['wat']).to eq('this is how the sausage is made')
end
it "sets the environment based on node.environment instead of the parameters" do
@node.parameters['environment'] = "Not actually #{@node.environment.name}"
@compiler.compile
expect(@compiler.topscope['environment']).to eq('testing')
end
it "should set the client and server versions on the catalog" do
params = {"clientversion" => "2", "serverversion" => "3"}
allow(@node).to receive(:parameters).and_return(params)
@compiler.compile
expect(@compiler.catalog.client_version).to eq("2")
expect(@compiler.catalog.server_version).to eq("3")
end
it "should evaluate the main class if it exists" do
main_class = @known_resource_types.add Puppet::Resource::Type.new(:hostclass, "")
@compiler.topscope.source = main_class
expect(main_class).to receive(:evaluate_code).with(be_a(Puppet::Parser::Resource))
@compiler.compile
end
it "should create a new, empty 'main' if no main class exists" do
@compiler.compile
expect(@known_resource_types.find_hostclass("")).to be_instance_of(Puppet::Resource::Type)
end
it "should add an edge between the main stage and main class" do
@compiler.compile
expect(stage = @compiler.catalog.resource(:stage, "main")).to be_instance_of(Puppet::Parser::Resource)
expect(klass = @compiler.catalog.resource(:class, "")).to be_instance_of(Puppet::Parser::Resource)
expect(@compiler.catalog.edge?(stage, klass)).to be_truthy
end
it "should evaluate all added collections" do
colls = []
# And when the collections fail to evaluate.
colls << double("coll1-false")
colls << double("coll2-false")
colls.each { |c| expect(c).to receive(:evaluate).and_return(false) }
@compiler.add_collection(colls[0])
@compiler.add_collection(colls[1])
allow(@compiler).to receive(:fail_on_unevaluated)
@compiler.compile
end
it "should ignore builtin resources" do
resource = resource(:file, "testing")
@compiler.add_resource(@scope, resource)
expect(resource).not_to receive(:evaluate)
@compiler.compile
end
it "should evaluate unevaluated resources" do
resource = CompilerTestResource.new(:file, "testing")
@compiler.add_resource(@scope, resource)
# We have to now mark the resource as evaluated
expect(resource).to receive(:evaluate) { resource.evaluated = true }
@compiler.compile
end
it "should not evaluate already-evaluated resources" do
resource = resource(:file, "testing")
allow(resource).to receive(:evaluated?).and_return(true)
@compiler.add_resource(@scope, resource)
expect(resource).not_to receive(:evaluate)
@compiler.compile
end
it "should evaluate unevaluated resources created by evaluating other resources" do
resource = CompilerTestResource.new(:file, "testing")
@compiler.add_resource(@scope, resource)
resource2 = CompilerTestResource.new(:file, "other")
# We have to now mark the resource as evaluated
expect(resource).to receive(:evaluate) { resource.evaluated = true; @compiler.add_resource(@scope, resource2) }
expect(resource2).to receive(:evaluate) { resource2.evaluated = true }
@compiler.compile
end
describe "when finishing" do
before do
@compiler.send(:evaluate_main)
@catalog = @compiler.catalog
end
def add_resource(name, parent = nil)
resource = Puppet::Parser::Resource.new "file", name, :scope => @scope
@compiler.add_resource(@scope, resource)
@catalog.add_edge(parent, resource) if parent
resource
end
it "should call finish() on all resources" do
# Add a resource that does respond to :finish
resource = Puppet::Parser::Resource.new "file", "finish", :scope => @scope
expect(resource).to receive(:finish)
@compiler.add_resource(@scope, resource)
# And one that does not
dnf_resource = double("dnf", :ref => "File[dnf]", :type => "file", :resource_type => nil, :[] => nil, :class? => nil, :stage? => nil)
@compiler.add_resource(@scope, dnf_resource)
@compiler.send(:finish)
end
it "should call finish() in add_resource order" do
resource1 = add_resource("finish1")
expect(resource1).to receive(:finish).ordered
resource2 = add_resource("finish2")
expect(resource2).to receive(:finish).ordered
@compiler.send(:finish)
end
it "should add each container's metaparams to its contained resources" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
@compiler.send(:finish)
expect(resource1[:noop]).to be_truthy
end
it "should add metaparams recursively" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
expect(resource2[:noop]).to be_truthy
end
it "should prefer metaparams from immediate parents" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
resource2 = add_resource("foo", resource1)
resource1[:noop] = false
@compiler.send(:finish)
expect(resource2[:noop]).to be_falsey
end
it "should merge tags downward" do
main = @catalog.resource(:class, :main)
main.tag("one")
resource1 = add_resource("meh", main)
resource1.tag "two"
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
expect(resource2.tags).to be_include("one")
expect(resource2.tags).to be_include("two")
end
it "should work if only middle resources have metaparams set" do
main = @catalog.resource(:class, :main)
resource1 = add_resource("meh", main)
resource1[:noop] = true
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
expect(resource2[:noop]).to be_truthy
end
end
it "should return added resources in add order" do
resource1 = resource(:file, "yay")
@compiler.add_resource(@scope, resource1)
resource2 = resource(:file, "youpi")
@compiler.add_resource(@scope, resource2)
expect(@compiler.resources).to eq([resource1, resource2])
end
it "should add resources that do not conflict with existing resources" do
resource = resource(:file, "yay")
@compiler.add_resource(@scope, resource)
expect(@compiler.catalog).to be_vertex(resource)
end
it "should fail to add resources that conflict with existing resources" do
path = make_absolute("/foo")
file1 = resource(:file, path)
file2 = resource(:file, path)
@compiler.add_resource(@scope, file1)
expect { @compiler.add_resource(@scope, file2) }.to raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
end
it "should add an edge from the scope resource to the added resource" do
resource = resource(:file, "yay")
@compiler.add_resource(@scope, resource)
expect(@compiler.catalog).to be_edge(@scope.resource, resource)
end
it "should not add non-class resources that don't specify a stage to the 'main' stage" do
main = @compiler.catalog.resource(:stage, :main)
resource = resource(:file, "foo")
@compiler.add_resource(@scope, resource)
expect(@compiler.catalog).not_to be_edge(main, resource)
end
it "should not add any parent-edges to stages" do
stage = resource(:stage, "other")
@compiler.add_resource(@scope, stage)
@scope.resource = resource(:class, "foo")
expect(@compiler.catalog.edge?(@scope.resource, stage)).to be_falsey
end
it "should not attempt to add stages to other stages" do
other_stage = resource(:stage, "other")
second_stage = resource(:stage, "second")
@compiler.add_resource(@scope, other_stage)
@compiler.add_resource(@scope, second_stage)
second_stage[:stage] = "other"
expect(@compiler.catalog.edge?(other_stage, second_stage)).to be_falsey
end
it "should have a method for looking up resources" do
resource = resource(:yay, "foo")
@compiler.add_resource(@scope, resource)
expect(@compiler.findresource("Yay[foo]")).to equal(resource)
end
it "should be able to look resources up by type and title" do
resource = resource(:yay, "foo")
@compiler.add_resource(@scope, resource)
expect(@compiler.findresource("Yay", "foo")).to equal(resource)
end
it "should not evaluate virtual defined resources" do
resource = resource(:file, "testing")
resource.virtual = true
@compiler.add_resource(@scope, resource)
expect(resource).not_to receive(:evaluate)
@compiler.compile
end
end
describe "when evaluating collections" do
it "should evaluate each collection" do
2.times { |i|
coll = double('coll%s' % i)
@compiler.add_collection(coll)
# This is the hard part -- we have to emulate the fact that
# collections delete themselves if they are done evaluating.
expect(coll).to receive(:evaluate) do
@compiler.delete_collection(coll)
end
}
@compiler.compile
end
it "should not fail when there are unevaluated resource collections that do not refer to specific resources" do
coll = double('coll', :evaluate => false)
expect(coll).to receive(:unresolved_resources).and_return(nil)
@compiler.add_collection(coll)
expect { @compiler.compile }.not_to raise_error
end
it "should fail when there are unevaluated resource collections that refer to a specific resource" do
coll = double('coll', :evaluate => false)
expect(coll).to receive(:unresolved_resources).and_return(:something)
@compiler.add_collection(coll)
expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources something')
end
it "should fail when there are unevaluated resource collections that refer to multiple specific resources" do
coll = double('coll', :evaluate => false)
expect(coll).to receive(:unresolved_resources).and_return([:one, :two])
@compiler.add_collection(coll)
expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources one, two')
end
end
describe "when evaluating relationships" do
it "should evaluate each relationship with its catalog" do
dep = double('dep')
expect(dep).to receive(:evaluate).with(@compiler.catalog)
@compiler.add_relationship dep
@compiler.evaluate_relationships
end
end
describe "when told to evaluate missing classes" do
it "should fail if there's no source listed for the scope" do
scope = double('scope', :source => nil)
expect { @compiler.evaluate_classes(%w{one two}, scope) }.to raise_error(Puppet::DevError)
end
it "should raise an error if a class is not found" do
expect(@scope.environment.known_resource_types).to receive(:find_hostclass).with("notfound").and_return(nil)
expect{ @compiler.evaluate_classes(%w{notfound}, @scope) }.to raise_error(Puppet::Error, /Could not find class/)
end
it "should raise an error when it can't find class" do
klasses = {'foo'=>nil}
@node.classes = klasses
expect{ @compiler.compile }.to raise_error(Puppet::Error, /Could not find class foo for testnode/)
end
end
describe "when evaluating found classes" do
before do
Puppet.settings[:data_binding_terminus] = "none"
@class = @known_resource_types.add Puppet::Resource::Type.new(:hostclass, "myclass")
@resource = double('resource', :ref => "Class[myclass]", :type => "file")
end
around do |example|
Puppet.override(
:environments => Puppet::Environments::Static.new(environment),
:description => "Static loader for specs"
) do
example.run
end
end
it "should evaluate each class" do
allow(@compiler.catalog).to receive(:tag)
expect(@class).to receive(:ensure_in_catalog).with(@scope)
allow(@scope).to receive(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope)
end
describe "and the classes are specified as a hash with parameters" do
before do
@node.classes = {}
@ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo')
end
# Define the given class with default parameters
def define_class(name, parameters)
@node.classes[name] = parameters
klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => @ast_obj, 'p2' => @ast_obj})
@compiler.environment.known_resource_types.add klass
end
def compile
@catalog = @compiler.compile
end
it "should record which classes are evaluated" do
classes = {'foo'=>{}, 'bar::foo'=>{}, 'bar'=>{}}
classes.each { |c, params| define_class(c, params) }
compile()
classes.each { |name, p| expect(@catalog.classes).to include(name) }
end
it "should provide default values for parameters that have no values specified" do
define_class('foo', {})
compile()
expect(@catalog.resource(:class, 'foo')['p1']).to eq("foo")
end
it "should use any provided values" do
define_class('foo', {'p1' => 'real_value'})
compile()
expect(@catalog.resource(:class, 'foo')['p1']).to eq("real_value")
end
it "should support providing some but not all values" do
define_class('foo', {'p1' => 'real_value'})
compile()
expect(@catalog.resource(:class, 'Foo')['p1']).to eq("real_value")
expect(@catalog.resource(:class, 'Foo')['p2']).to eq("foo")
end
it "should ensure each node class is in catalog and has appropriate tags" do
klasses = ['bar::foo']
@node.classes = klasses
ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo')
klasses.each do |name|
klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => ast_obj, 'p2' => ast_obj})
@compiler.environment.known_resource_types.add klass
end
catalog = @compiler.compile
r2 = catalog.resources.detect {|r| r.title == 'Bar::Foo' }
expect(r2.tags).to eq(Puppet::Util::TagSet.new(['bar::foo', 'class', 'bar', 'foo']))
end
end
it "should fail if required parameters are missing" do
klass = {'foo'=>{'a'=>'one'}}
@node.classes = klass
klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {'a' => nil, 'b' => nil})
@compiler.environment.known_resource_types.add klass
expect { @compiler.compile }.to raise_error(Puppet::PreformattedError, /Class\[Foo\]: expects a value for parameter 'b'/)
end
it "should fail if invalid parameters are passed" do
klass = {'foo'=>{'3'=>'one'}}
@node.classes = klass
klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {})
@compiler.environment.known_resource_types.add klass
expect { @compiler.compile }.to raise_error(Puppet::PreformattedError, /Class\[Foo\]: has no parameter named '3'/)
end
it "should ensure class is in catalog without params" do
@node.classes = {'foo'=>nil}
foo = Puppet::Resource::Type.new(:hostclass, 'foo')
@compiler.environment.known_resource_types.add foo
catalog = @compiler.compile
expect(catalog.classes).to include 'foo'
end
it "should not evaluate the resources created for found classes unless asked" do
allow(@compiler.catalog).to receive(:tag)
expect(@resource).not_to receive(:evaluate)
expect(@class).to receive(:ensure_in_catalog).and_return(@resource)
allow(@scope).to receive(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope)
end
it "should immediately evaluate the resources created for found classes when asked" do
allow(@compiler.catalog).to receive(:tag)
expect(@resource).to receive(:evaluate)
expect(@class).to receive(:ensure_in_catalog).and_return(@resource)
allow(@scope).to receive(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope, false)
end
it "should skip classes that have already been evaluated" do
allow(@compiler.catalog).to receive(:tag)
allow(@scope).to receive(:class_scope).with(@class).and_return(@scope)
expect(@compiler).not_to receive(:add_resource)
expect(@resource).not_to receive(:evaluate)
expect(Puppet::Parser::Resource).not_to receive(:new)
@compiler.evaluate_classes(%w{myclass}, @scope, false)
end
it "should skip classes previously evaluated with different capitalization" do
allow(@compiler.catalog).to receive(:tag)
allow(@scope.environment.known_resource_types).to receive(:find_hostclass).with("MyClass").and_return(@class)
allow(@scope).to receive(:class_scope).with(@class).and_return(@scope)
expect(@compiler).not_to receive(:add_resource)
expect(@resource).not_to receive(:evaluate)
expect(Puppet::Parser::Resource).not_to receive(:new)
@compiler.evaluate_classes(%w{MyClass}, @scope, false)
end
end
describe "when evaluating AST nodes with no AST nodes present" do
it "should do nothing" do
allow(@compiler.environment.known_resource_types).to receive(:nodes).and_return(false)
expect(Puppet::Parser::Resource).not_to receive(:new)
@compiler.send(:evaluate_ast_node)
end
end
describe "when evaluating AST nodes with AST nodes present" do
before do
allow(@compiler.environment.known_resource_types).to receive(:nodes?).and_return(true)
# Set some names for our test
allow(@node).to receive(:names).and_return(%w{a b c})
allow(@compiler.environment.known_resource_types).to receive(:node).with("a").and_return(nil)
allow(@compiler.environment.known_resource_types).to receive(:node).with("b").and_return(nil)
allow(@compiler.environment.known_resource_types).to receive(:node).with("c").and_return(nil)
# It should check this last, of course.
allow(@compiler.environment.known_resource_types).to receive(:node).with("default").and_return(nil)
end
it "should fail if the named node cannot be found" do
expect { @compiler.send(:evaluate_ast_node) }.to raise_error(Puppet::ParseError)
end
it "should evaluate the first node class matching the node name" do
node_class = double('node', :name => "c", :evaluate_code => nil)
allow(@compiler.environment.known_resource_types).to receive(:node).with("c").and_return(node_class)
node_resource = double('node resource', :ref => "Node[c]", :evaluate => nil, :type => "node")
expect(node_class).to receive(:ensure_in_catalog).and_return(node_resource)
@compiler.compile
end
it "should match the default node if no matching node can be found" do
node_class = double('node', :name => "default", :evaluate_code => nil)
allow(@compiler.environment.known_resource_types).to receive(:node).with("default").and_return(node_class)
node_resource = double('node resource', :ref => "Node[default]", :evaluate => nil, :type => "node")
expect(node_class).to receive(:ensure_in_catalog).and_return(node_resource)
@compiler.compile
end
it "should evaluate the node resource immediately rather than using lazy evaluation" do
node_class = double('node', :name => "c")
allow(@compiler.environment.known_resource_types).to receive(:node).with("c").and_return(node_class)
node_resource = double('node resource', :ref => "Node[c]", :type => "node")
expect(node_class).to receive(:ensure_in_catalog).and_return(node_resource)
expect(node_resource).to receive(:evaluate)
@compiler.send(:evaluate_ast_node)
end
end
describe 'when using meta parameters to form relationships' do
include PuppetSpec::Compiler
[:before, :subscribe, :notify, :require].each do | meta_p |
it "an entry consisting of nested empty arrays is flattened for parameter #{meta_p}" do
expect {
node = Puppet::Node.new('someone')
manifest = <<-"MANIFEST"
notify{hello_kitty: message => meow, #{meta_p} => [[],[]]}
notify{hello_kitty2: message => meow, #{meta_p} => [[],[[]],[]]}
MANIFEST
catalog = compile_to_catalog(manifest, node)
catalog.to_ral
}.not_to raise_error
end
end
end
describe "when evaluating node classes" do
include PuppetSpec::Compiler
describe "when provided classes in array format" do
let(:node) { Puppet::Node.new('someone', :classes => ['something']) }
describe "when the class exists" do
it "should succeed if the class is already included" do
manifest = <<-MANIFEST
class something {}
include something
MANIFEST
catalog = compile_to_catalog(manifest, node)
expect(catalog.resource('Class', 'Something')).not_to be_nil
end
it "should evaluate the class without parameters if it's not already included" do
manifest = "class something {}"
catalog = compile_to_catalog(manifest, node)
expect(catalog.resource('Class', 'Something')).not_to be_nil
end
it "raises if the class name is the same as the node definition" do
name = node.name
node.classes = [name]
expect {
compile_to_catalog(<<-MANIFEST, node)
class #{name} {}
node #{name} {
include #{name}
}
MANIFEST
}.to raise_error(Puppet::Error, /Class '#{name}' is already defined \(line: 1\); cannot be redefined as a node \(line: 2\) on node #{name}/)
end
it "evaluates the class if the node definition uses a regexp" do
name = node.name
node.classes = [name]
catalog = compile_to_catalog(<<-MANIFEST, node)
class #{name} {}
node /#{name}/ {
include #{name}
}
MANIFEST
expect(@logs).to be_empty
expect(catalog.resource('Class', node.name.capitalize)).to_not be_nil
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
end
describe "when provided classes in hash format" do
describe "for classes without parameters" do
let(:node) { Puppet::Node.new('someone', :classes => {'something' => {}}) }
describe "when the class exists" do
it "should succeed if the class is already included" do
manifest = <<-MANIFEST
class something {}
include something
MANIFEST
catalog = compile_to_catalog(manifest, node)
expect(catalog.resource('Class', 'Something')).not_to be_nil
end
it "should evaluate the class if it's not already included" do
manifest = <<-MANIFEST
class something {}
MANIFEST
catalog = compile_to_catalog(manifest, node)
expect(catalog.resource('Class', 'Something')).not_to be_nil
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/resource/param_spec.rb | spec/unit/parser/resource/param_spec.rb | require 'spec_helper'
describe Puppet::Parser::Resource::Param do
it "has readers for all of the attributes" do
param = Puppet::Parser::Resource::Param.new(:name => 'myparam', :value => 'foo', :file => 'foo.pp', :line => 42)
expect(param.name).to eq(:myparam)
expect(param.value).to eq('foo')
expect(param.file).to eq('foo.pp')
expect(param.line).to eq(42)
end
context "parameter validation" do
it "throws an error when instantiated without a name" do
expect {
Puppet::Parser::Resource::Param.new(:value => 'foo')
}.to raise_error(Puppet::Error, /'name' is a required option/)
end
it "does not require a value" do
param = Puppet::Parser::Resource::Param.new(:name => 'myparam')
expect(param.value).to be_nil
end
it "includes file/line context in errors" do
expect {
Puppet::Parser::Resource::Param.new(:file => 'foo.pp', :line => 42)
}.to raise_error(Puppet::Error, /\(file: foo.pp, line: 42\)/)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/file_spec.rb | spec/unit/parser/functions/file_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
describe "the 'file' function" do
include PuppetSpec::Files
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
def with_file_content(content)
path = tmpfile('file-function')
file = File.new(path, 'wb')
file.sync = true
file.print content
yield path
end
it "should read a file" do
with_file_content('file content') do |name|
expect(scope.function_file([name])).to eq("file content")
end
end
it "should read a file keeping line endings intact" do
with_file_content("file content\r\n") do |name|
expect(scope.function_file([name])).to eq("file content\r\n")
end
end
it "should read a file from a module path" do
with_file_content('file content') do |name|
mod = double('module')
allow(mod).to receive(:file).with('myfile').and_return(name)
allow(compiler.environment).to receive(:module).with('mymod').and_return(mod)
expect(scope.function_file(['mymod/myfile'])).to eq('file content')
end
end
it "should return the first file if given two files with absolute paths" do
with_file_content('one') do |one|
with_file_content('two') do |two|
expect(scope.function_file([one, two])).to eq("one")
end
end
end
it "should return the first file if given two files with module paths" do
with_file_content('one') do |one|
with_file_content('two') do |two|
mod = double('module')
expect(compiler.environment).to receive(:module).with('mymod').and_return(mod)
expect(mod).to receive(:file).with('one').and_return(one)
allow(mod).to receive(:file).with('two').and_return(two)
expect(scope.function_file(['mymod/one','mymod/two'])).to eq('one')
end
end
end
it "should return the first file if given two files with mixed paths, absolute first" do
with_file_content('one') do |one|
with_file_content('two') do |two|
mod = double('module')
allow(compiler.environment).to receive(:module).with('mymod').and_return(mod)
allow(mod).to receive(:file).with('two').and_return(two)
expect(scope.function_file([one,'mymod/two'])).to eq('one')
end
end
end
it "should return the first file if given two files with mixed paths, module first" do
with_file_content('one') do |one|
with_file_content('two') do |two|
mod = double('module')
expect(compiler.environment).to receive(:module).with('mymod').and_return(mod)
allow(mod).to receive(:file).with('two').and_return(two)
expect(scope.function_file(['mymod/two',one])).to eq('two')
end
end
end
it "should not fail when some files are absent" do
expect {
with_file_content('one') do |one|
expect(scope.function_file([make_absolute("/should-not-exist"), one])).to eq('one')
end
}.to_not raise_error
end
it "should fail when all files are absent" do
expect {
scope.function_file([File.expand_path('one')])
}.to raise_error(Puppet::ParseError, /Could not find any files/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/shellquote_spec.rb | spec/unit/parser/functions/shellquote_spec.rb | require 'spec_helper'
describe "the shellquote function" do
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
it "should exist" do
expect(Puppet::Parser::Functions.function("shellquote")).to eq("function_shellquote")
end
it "should handle no arguments" do
expect(scope.function_shellquote([])).to eq("")
end
it "should handle several simple arguments" do
expect(scope.function_shellquote(
['foo', 'bar@example.com', 'localhost:/dev/null', 'xyzzy+-4711,23']
)).to eq('foo bar@example.com localhost:/dev/null xyzzy+-4711,23')
end
it "should handle array arguments" do
expect(scope.function_shellquote(
['foo', ['bar@example.com', 'localhost:/dev/null'],
'xyzzy+-4711,23']
)).to eq('foo bar@example.com localhost:/dev/null xyzzy+-4711,23')
end
it "should quote unsafe characters" do
expect(scope.function_shellquote(['/etc/passwd ', '(ls)', '*', '[?]', "'&'"])).
to eq('"/etc/passwd " "(ls)" "*" "[?]" "\'&\'"')
end
it "should deal with double quotes" do
expect(scope.function_shellquote(['"foo"bar"'])).to eq('\'"foo"bar"\'')
end
it "should cope with dollar signs" do
expect(scope.function_shellquote(['$PATH', 'foo$bar', '"x$"'])).
to eq("'$PATH' 'foo$bar' '\"x$\"'")
end
it "should deal with apostrophes (single quotes)" do
expect(scope.function_shellquote(["'foo'bar'", "`$'EDITOR'`"])).
to eq('"\'foo\'bar\'" "\\`\\$\'EDITOR\'\\`"')
end
it "should cope with grave accents (backquotes)" do
expect(scope.function_shellquote(['`echo *`', '`ls "$MAILPATH"`'])).
to eq("'`echo *`' '`ls \"$MAILPATH\"`'")
end
it "should deal with both single and double quotes" do
expect(scope.function_shellquote(['\'foo"bar"xyzzy\'', '"foo\'bar\'xyzzy"'])).
to eq('"\'foo\\"bar\\"xyzzy\'" "\\"foo\'bar\'xyzzy\\""')
end
it "should handle multiple quotes *and* dollars and backquotes" do
expect(scope.function_shellquote(['\'foo"$x`bar`"xyzzy\''])).
to eq('"\'foo\\"\\$x\\`bar\\`\\"xyzzy\'"')
end
it "should handle linefeeds" do
expect(scope.function_shellquote(["foo \n bar"])).to eq("\"foo \n bar\"")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/sprintf_spec.rb | spec/unit/parser/functions/sprintf_spec.rb | require 'spec_helper'
describe "the sprintf function" do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
expect(Puppet::Parser::Functions.function("sprintf")).to eq("function_sprintf")
end
it "should raise an ArgumentError if there is less than 1 argument" do
expect { @scope.function_sprintf([]) }.to( raise_error(ArgumentError))
end
it "should format integers" do
result = @scope.function_sprintf(["%+05d", "23"])
expect(result).to(eql("+0023"))
end
it "should format floats" do
result = @scope.function_sprintf(["%+.2f", "2.7182818284590451"])
expect(result).to(eql("+2.72"))
end
it "should format large floats" do
result = @scope.function_sprintf(["%+.2e", "27182818284590451"])
str =
"+2.72e+16"
expect(result).to(eql(str))
end
it "should perform more complex formatting" do
result = @scope.function_sprintf(
[ "<%.8s:%#5o %#8X (%-8s)>",
"overlongstring", "23", "48879", "foo" ])
expect(result).to(eql("<overlong: 027 0XBEEF (foo )>"))
end
it 'does not attempt to mutate its arguments' do
args = ['%d', 1].freeze
expect { @scope.function_sprintf(args) }.to_not raise_error
end
it 'support named arguments in a hash with string keys' do
result = @scope.function_sprintf(["%<foo>d : %<bar>f", {'foo' => 1, 'bar' => 2}])
expect(result).to eq("1 : 2.000000")
end
it 'raises a key error if a key is not present' do
expect do
@scope.function_sprintf(["%<foo>d : %<zanzibar>f", {'foo' => 1, 'bar' => 2}])
end.to raise_error(KeyError, /key<zanzibar> not found/)
end
it 'a hash with string keys that is output formats as strings' do
result = @scope.function_sprintf(["%s", {'foo' => 1, 'bar' => 2}])
expect(result).to eq("{\"foo\"=>1, \"bar\"=>2}")
end
it 'named arguments hash with non string keys are tolerated' do
result = @scope.function_sprintf(["%<foo>d : %<bar>f", {'foo' => 1, 'bar' => 2, 1 => 2, [1] => 2, false => true, {} => {}}])
expect(result).to eq("1 : 2.000000")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/generate_spec.rb | spec/unit/parser/functions/generate_spec.rb | require 'spec_helper'
def with_executor
return yield unless Puppet::Util::Platform.jruby?
begin
Puppet::Util::ExecutionStub.set do |command, options, stdin, stdout, stderr|
require 'open3'
# simulate what puppetserver does
Dir.chdir(options[:cwd]) do
out, err, _status = Open3.capture3(*command)
stdout.write(out)
stderr.write(err)
# execution api expects stdout to be returned
out
end
end
yield
ensure
Puppet::Util::ExecutionStub.reset
end
end
describe "the generate function" do
include PuppetSpec::Files
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
let :cwd do tmpdir('generate') end
it "should exist" do
expect(Puppet::Parser::Functions.function("generate")).to eq("function_generate")
end
it "accept a fully-qualified path as a command" do
command = File.expand_path('/command/foo')
expect(Puppet::Util::Execution).to receive(:execute).with([command], anything).and_return("yay")
expect(scope.function_generate([command])).to eq("yay")
end
it "should not accept a relative path as a command" do
expect { scope.function_generate(["command"]) }.to raise_error(Puppet::ParseError)
end
it "should not accept a command containing illegal characters" do
expect { scope.function_generate([File.expand_path('/##/command')]) }.to raise_error(Puppet::ParseError)
end
it "should not accept a command containing spaces" do
expect { scope.function_generate([File.expand_path('/com mand')]) }.to raise_error(Puppet::ParseError)
end
it "should not accept a command containing '..'", :unless => RUBY_PLATFORM == 'java' do
command = File.expand_path("/command/../")
expect { scope.function_generate([command]) }.to raise_error(Puppet::ParseError)
end
it "should execute the generate script with the correct working directory" do
command = File.expand_path("/usr/local/command")
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: %r{/usr/local})).and_return("yay")
scope.function_generate([command])
end
it "should execute the generate script with failonfail" do
command = File.expand_path("/usr/local/command")
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(failonfail: true)).and_return("yay")
scope.function_generate([command])
end
it "should execute the generate script with combine" do
command = File.expand_path("/usr/local/command")
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(combine: true)).and_return("yay")
scope.function_generate([command])
end
it "executes a command in a working directory" do
if Puppet::Util::Platform.windows?
command = File.join(cwd, 'echo.bat')
File.write(command, <<~END)
@echo off
echo %CD%
END
expect(scope.function_generate([command]).chomp).to match(cwd.gsub('/', '\\'))
else
with_executor do
command = File.join(cwd, 'echo.sh')
File.write(command, <<~END)
#!/bin/sh
echo $PWD
END
Puppet::FileSystem.chmod(0755, command)
expect(scope.function_generate([command]).chomp).to eq(cwd)
end
end
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
it "should accept the tilde in the path" do
command = "C:/DOCUME~1/ADMINI~1/foo.bat"
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: "C:/DOCUME~1/ADMINI~1")).and_return("yay")
expect(scope.function_generate([command])).to eq('yay')
end
it "should accept lower-case drive letters" do
command = 'd:/command/foo'
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: "d:/command")).and_return("yay")
expect(scope.function_generate([command])).to eq('yay')
end
it "should accept upper-case drive letters" do
command = 'D:/command/foo'
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: "D:/command")).and_return("yay")
expect(scope.function_generate([command])).to eq('yay')
end
it "should accept forward and backslashes in the path" do
command = 'D:\command/foo\bar'
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: 'D:\command/foo')).and_return("yay")
expect(scope.function_generate([command])).to eq('yay')
end
it "should reject colons when not part of the drive letter" do
expect { scope.function_generate(['C:/com:mand']) }.to raise_error(Puppet::ParseError)
end
it "should reject root drives" do
expect { scope.function_generate(['C:/']) }.to raise_error(Puppet::ParseError)
end
end
describe "on POSIX", :if => Puppet.features.posix? do
it "should reject backslashes" do
expect { scope.function_generate(['/com\\mand']) }.to raise_error(Puppet::ParseError)
end
it "should accept plus and dash" do
command = "/var/folders/9z/9zXImgchH8CZJh6SgiqS2U+++TM/-Tmp-/foo"
expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: '/var/folders/9z/9zXImgchH8CZJh6SgiqS2U+++TM/-Tmp-')).and_return("yay")
expect(scope.function_generate([command])).to eq('yay')
end
end
describe "function_generate", :unless => RUBY_PLATFORM == 'java' do
let :command do
script_containing('function_generate',
:windows => '@echo off' + "\n" + 'echo a-%1 b-%2',
:posix => '#!/bin/sh' + "\n" + 'echo a-$1 b-$2')
end
after :each do
File.delete(command) if Puppet::FileSystem.exist?(command)
end
it "returns the output as a String" do
expect(scope.function_generate([command]).class).to eq(String)
end
it "should call generator with no arguments" do
expect(scope.function_generate([command])).to eq("a- b-\n")
end
it "should call generator with one argument" do
expect(scope.function_generate([command, 'one'])).to eq("a-one b-\n")
end
it "should call generator with wo arguments" do
expect(scope.function_generate([command, 'one', 'two'])).to eq("a-one b-two\n")
end
it "should fail if generator is not absolute" do
expect { scope.function_generate(['boo']) }.to raise_error(Puppet::ParseError)
end
it "should fail if generator fails" do
expect { scope.function_generate(['/boo']) }.to raise_error(Puppet::ParseError)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/hiera_spec.rb | spec/unit/parser/functions/hiera_spec.rb | require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera' do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
it 'should raise an error since this function is converted to 4x API)' do
expect { scope.function_hiera(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/fail_spec.rb | spec/unit/parser/functions/fail_spec.rb | require 'spec_helper'
describe "the 'fail' parser function" do
let :scope do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
scope = Puppet::Parser::Scope.new(compiler)
allow(scope).to receive(:environment).and_return(nil)
scope
end
it "should exist" do
expect(Puppet::Parser::Functions.function(:fail)).to eq("function_fail")
end
it "should raise a parse error if invoked" do
expect { scope.function_fail([]) }.to raise_error Puppet::ParseError
end
it "should join arguments into a string in the error" do
expect { scope.function_fail(["hello", "world"]) }.to raise_error(/hello world/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/hiera_array_spec.rb | spec/unit/parser/functions/hiera_array_spec.rb | require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera_array' do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
it 'should raise an error since this function is converted to 4x API)' do
expect { scope.function_hiera_array(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/versioncmp_spec.rb | spec/unit/parser/functions/versioncmp_spec.rb | require 'spec_helper'
describe "the versioncmp function" do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
expect(Puppet::Parser::Functions.function("versioncmp")).to eq("function_versioncmp")
end
it "should raise an ArgumentError if there is less than 2 arguments" do
expect { @scope.function_versioncmp(["1.2"]) }.to raise_error(ArgumentError)
end
it "should raise an ArgumentError if there is more than 2 arguments" do
expect { @scope.function_versioncmp(["1.2", "2.4.5", "3.5.6"]) }.to raise_error(ArgumentError)
end
it "should call Puppet::Util::Package.versioncmp (included in scope)" do
expect(Puppet::Util::Package).to receive(:versioncmp).with("1.2", "1.3").and_return(-1)
@scope.function_versioncmp(["1.2", "1.3"])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/hiera_include_spec.rb | spec/unit/parser/functions/hiera_include_spec.rb | require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera_include' do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
it 'should raise an error since this function is converted to 4x API)' do
expect { scope.function_hiera_include(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/hiera_hash_spec.rb | spec/unit/parser/functions/hiera_hash_spec.rb | require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera_hash' do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
it 'should raise an error since this function is converted to 4x API)' do
expect { scope.function_hiera_hash(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/scanf_spec.rb | spec/unit/parser/functions/scanf_spec.rb | require 'spec_helper'
describe "the scanf function" do
let(:node) { Puppet::Node.new('localhost') }
let(:compiler) { Puppet::Parser::Compiler.new(node) }
let(:scope) { Puppet::Parser::Scope.new(compiler) }
it 'scans a value and returns an array' do
expect(scope.function_scanf(['42', '%i'])[0] == 42)
end
it 'returns empty array if nothing was scanned' do
expect(scope.function_scanf(['no', '%i']) == [])
end
it 'produces result up to first unsuccessful scan' do
expect(scope.function_scanf(['42 no', '%i'])[0] == 42)
end
it 'errors when not given enough arguments' do
expect do
scope.function_scanf(['42'])
end.to raise_error(/.*scanf\(\): Wrong number of arguments given/m)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/create_resources_spec.rb | spec/unit/parser/functions/create_resources_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet_spec/files'
describe 'function for dynamically creating resources' do
include PuppetSpec::Compiler
include PuppetSpec::Files
before :each do
node = Puppet::Node.new("floppy", :environment => 'production')
@compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(@compiler)
@topscope = @scope.compiler.topscope
@scope.parent = @topscope
Puppet::Parser::Functions.function(:create_resources)
end
it "should exist" do
expect(Puppet::Parser::Functions.function(:create_resources)).to eq("function_create_resources")
end
it 'should require two or three arguments' do
expect { @scope.function_create_resources(['foo']) }.to raise_error(ArgumentError, 'create_resources(): Wrong number of arguments given (1 for minimum 2)')
expect { @scope.function_create_resources(['foo', 'bar', 'blah', 'baz']) }.to raise_error(ArgumentError, 'create_resources(): wrong number of arguments (4; must be 2 or 3)')
end
it 'should require second argument to be a hash' do
expect { @scope.function_create_resources(['foo','bar']) }.to raise_error(ArgumentError, 'create_resources(): second argument must be a hash')
end
it 'should require optional third argument to be a hash' do
expect { @scope.function_create_resources(['foo',{},'foo']) }.to raise_error(ArgumentError, 'create_resources(): third argument, if provided, must be a hash')
end
context 'when being called from a manifest in a file' do
let(:dir) do
dir_containing('manifests', {
'site.pp' => <<-EOF
# comment here to make the call be on a particular
# source line (3)
create_resources('notify', {
'a' => { 'message'=>'message a'},
'b' => { 'message'=>'message b'},
}
)
EOF
}
)
end
it 'file and line information where call originates is written to all resources created in one call' do
node = Puppet::Node.new('test')
file = File.join(dir, 'site.pp')
Puppet[:manifest] = file
catalog = Puppet::Parser::Compiler.compile(node).filter { |r| r.virtual? }
expect(catalog.resource(:notify, 'a').file).to eq(file)
expect(catalog.resource(:notify, 'a').line).to eq(3)
expect(catalog.resource(:notify, 'b').file).to eq(file)
expect(catalog.resource(:notify, 'b').line).to eq(3)
end
end
describe 'when creating native types' do
it 'empty hash should not cause resources to be added' do
noop_catalog = compile_to_catalog("create_resources('file', {})")
empty_catalog = compile_to_catalog("")
expect(noop_catalog.resources.size).to eq(empty_catalog.resources.size)
end
it 'should be able to add' do
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}})")
expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present')
end
it 'should pick up and pass on file and line information' do
# mock location as the compile_to_catalog sets Puppet[:code} which does not
# have file/line support.
expect(Puppet::Pops::PuppetStack).to receive(:top_of_stack).once.and_return(['test.pp', 1234])
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}})")
r = catalog.resource(:file, "/etc/foo")
expect(r.file).to eq('test.pp')
expect(r.line).to eq(1234)
end
it 'should be able to add virtual resources' do
catalog = compile_to_catalog("create_resources('@file', {'/etc/foo'=>{'ensure'=>'present'}})\nrealize(File['/etc/foo'])")
expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present')
end
it 'unrealized exported resources should not be added' do
# a compiled catalog is normally filtered on virtual resources
# here the compilation is performed unfiltered to be able to find the exported resource
# it is then asserted that the exported resource is also virtual (and therefore filtered out by a real compilation).
catalog = compile_to_catalog_unfiltered("create_resources('@@file', {'/etc/foo'=>{'ensure'=>'present'}})")
expect(catalog.resource(:file, "/etc/foo").exported).to eq(true)
expect(catalog.resource(:file, "/etc/foo").virtual).to eq(true)
end
it 'should be able to add exported resources' do
catalog = compile_to_catalog("create_resources('@@file', {'/etc/foo'=>{'ensure'=>'present'}}) realize(File['/etc/foo'])")
expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present')
expect(catalog.resource(:file, "/etc/foo").exported).to eq(true)
end
it 'should accept multiple resources' do
catalog = compile_to_catalog("create_resources('notify', {'foo'=>{'message'=>'one'}, 'bar'=>{'message'=>'two'}})")
expect(catalog.resource(:notify, "foo")['message']).to eq('one')
expect(catalog.resource(:notify, "bar")['message']).to eq('two')
end
it 'should fail to add non-existing resource type' do
expect do
@scope.function_create_resources(['create-resource-foo', { 'foo' => {} }])
end.to raise_error(/Unknown resource type: 'create-resource-foo'/)
end
it 'should be able to add edges' do
rg = compile_to_relationship_graph("notify { test: }\n create_resources('notify', {'foo'=>{'require'=>'Notify[test]'}})")
test = rg.vertices.find { |v| v.title == 'test' }
foo = rg.vertices.find { |v| v.title == 'foo' }
expect(test).to be
expect(foo).to be
expect(rg.path_between(test,foo)).to be
end
it 'should filter out undefined edges as they cause errors' do
rg = compile_to_relationship_graph("notify { test: }\n create_resources('notify', {'foo'=>{'require'=>undef}})")
test = rg.vertices.find { |v| v.title == 'test' }
foo = rg.vertices.find { |v| v.title == 'foo' }
expect(test).to be
expect(foo).to be
expect(rg.path_between(foo,nil)).to_not be
end
it 'should filter out undefined edges in an array as they cause errors' do
rg = compile_to_relationship_graph("notify { test: }\n create_resources('notify', {'foo'=>{'require'=>[undef]}})")
test = rg.vertices.find { |v| v.title == 'test' }
foo = rg.vertices.find { |v| v.title == 'foo' }
expect(test).to be
expect(foo).to be
expect(rg.path_between(foo,nil)).to_not be
end
it 'should account for default values' do
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}, '/etc/baz'=>{'group'=>'food'}}, {'group' => 'bar'})")
expect(catalog.resource(:file, "/etc/foo")['group']).to eq('bar')
expect(catalog.resource(:file, "/etc/baz")['group']).to eq('food')
end
end
describe 'when dynamically creating resource types' do
it 'should be able to create defined resource types' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{'one'=>'two'}})
MANIFEST
expect(catalog.resource(:notify, "blah")['message']).to eq('two')
end
it 'should fail if defines are missing params' do
expect {
compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{}})
MANIFEST
}.to raise_error(Puppet::Error, /Foocreateresource\[blah\]: expects a value for parameter 'one'/)
end
it 'should accept undef as explicit value when parameter has no default value' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => "aaa${one}bbb" }
}
create_resources('foocreateresource', {'blah'=>{ one => undef}})
MANIFEST
expect(catalog.resource(:notify, "blah")['message']).to eq('aaabbb')
end
it 'should use default value expression if given value is undef' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one = 'xx') {
notify { $name: message => "aaa${one}bbb" }
}
create_resources('foocreateresource', {'blah'=>{ one => undef}})
MANIFEST
expect(catalog.resource(:notify, "blah")['message']).to eq('aaaxxbbb')
end
it 'should be able to add multiple defines' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{'one'=>'two'}, 'blaz'=>{'one'=>'three'}})
MANIFEST
expect(catalog.resource(:notify, "blah")['message']).to eq('two')
expect(catalog.resource(:notify, "blaz")['message']).to eq('three')
end
it 'should be able to add edges' do
rg = compile_to_relationship_graph(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
notify { test: }
create_resources('foocreateresource', {'blah'=>{'one'=>'two', 'require' => 'Notify[test]'}})
MANIFEST
test = rg.vertices.find { |v| v.title == 'test' }
blah = rg.vertices.find { |v| v.title == 'blah' }
expect(test).to be
expect(blah).to be
expect(rg.path_between(test,blah)).to be
end
it 'should account for default values' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{}}, {'one' => 'two'})
MANIFEST
expect(catalog.resource(:notify, "blah")['message']).to eq('two')
end
end
describe 'when creating classes' do
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
it 'should be able to create classes' do
catalog = compile_to_catalog(<<-MANIFEST)
class bar($one) {
notify { test: message => $one }
}
create_resources('class', {'bar'=>{'one'=>'two'}})
MANIFEST
expect(catalog.resource(:notify, "test")['message']).to eq('two')
expect(catalog.resource(:class, "bar")).not_to be_nil
end
it 'should error if class is exported' do
expect{
compile_to_catalog('class test{} create_resources("@@class", {test => {}})')
}.to raise_error(/Classes are not virtualizable/)
end
it 'should error if class is virtual' do
expect{
compile_to_catalog('class test{} create_resources("@class", {test => {}})')
}.to raise_error(/Classes are not virtualizable/)
end
it 'should be able to add edges' do
rg = compile_to_relationship_graph(<<-MANIFEST)
class bar($one) {
notify { test: message => $one }
}
notify { tester: }
create_resources('class', {'bar'=>{'one'=>'two', 'require' => 'Notify[tester]'}})
MANIFEST
test = rg.vertices.find { |v| v.title == 'test' }
tester = rg.vertices.find { |v| v.title == 'tester' }
expect(test).to be
expect(tester).to be
expect(rg.path_between(tester,test)).to be
end
it 'should account for default values' do
catalog = compile_to_catalog(<<-MANIFEST)
class bar($one) {
notify { test: message => $one }
}
create_resources('class', {'bar'=>{}}, {'one' => 'two'})
MANIFEST
expect(catalog.resource(:notify, "test")['message']).to eq('two')
expect(catalog.resource(:class, "bar")).not_to be_nil
end
it 'should fail with a correct error message if the syntax of an imported file is incorrect' do
expect{
Puppet[:modulepath] = my_fixture_dir
compile_to_catalog('include foo')
}.to raise_error(Puppet::Error, /Syntax error at.*/)
end
it 'is not available when --tasks is on' do
Puppet[:tasks] = true
expect do
compile_to_catalog(<<-MANIFEST)
create_resources('class', {'bar'=>{}}, {'one' => 'two'})
MANIFEST
end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/)
end
end
def collect_notices(code)
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
compile_to_catalog(code)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/fqdn_rand_spec.rb | spec/unit/parser/functions/fqdn_rand_spec.rb | require 'spec_helper'
require 'puppet_spec/scope'
describe "the fqdn_rand function" do
include PuppetSpec::Scope
it "returns an integer" do
expect(fqdn_rand(3)).to be_an(Integer)
end
it "provides a random number strictly less than the given max" do
expect(fqdn_rand(3)).to satisfy {|n| n < 3 }
end
it "provides the same 'random' value on subsequent calls for the same host" do
expect(fqdn_rand(3)).to eql(fqdn_rand(3))
end
it "considers the same host and same extra arguments to have the same random sequence" do
first_random = fqdn_rand(3, :extra_identifier => [1, "same", "host"])
second_random = fqdn_rand(3, :extra_identifier => [1, "same", "host"])
expect(first_random).to eql(second_random)
end
it "allows extra arguments to control the random value on a single host" do
first_random = fqdn_rand(10000, :extra_identifier => [1, "different", "host"])
second_different_random = fqdn_rand(10000, :extra_identifier => [2, "different", "host"])
expect(first_random).not_to eql(second_different_random)
end
it "should return different sequences of value for different hosts" do
val1 = fqdn_rand(1000000000, :host => "first.host.com")
val2 = fqdn_rand(1000000000, :host => "second.host.com")
expect(val1).not_to eql(val2)
end
it "should return a specific value with given set of inputs on non-fips enabled host" do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false)
expect(fqdn_rand(3000, :host => 'dummy.fqdn.net')).to eql(338)
end
it "should return a specific value with given set of inputs on fips enabled host" do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect(fqdn_rand(3000, :host => 'dummy.fqdn.net')).to eql(278)
end
it "should return a specific value with given seed on a non-fips enabled host" do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false)
expect(fqdn_rand(5000, :extra_identifier => ['expensive job 33'])).to eql(3374)
end
it "should return a specific value with given seed on a fips enabled host" do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect(fqdn_rand(5000, :extra_identifier => ['expensive job 33'])).to eql(2389)
end
it "returns the same value if only host differs by case" do
val1 = fqdn_rand(1000000000, :host => "host.example.com", :extra_identifier => [nil, true])
val2 = fqdn_rand(1000000000, :host => "HOST.example.com", :extra_identifier => [nil, true])
expect(val1).to eql(val2)
end
it "returns the same value if only host differs by case and an initial seed is given" do
val1 = fqdn_rand(1000000000, :host => "host.example.com", :extra_identifier => ['a seed', true])
val2 = fqdn_rand(1000000000, :host => "HOST.example.com", :extra_identifier => ['a seed', true])
expect(val1).to eql(val2)
end
def fqdn_rand(max, args = {})
host = args[:host] || '127.0.0.1'
extra = args[:extra_identifier] || []
scope = create_test_scope_for_node('localhost')
scope.set_facts({ 'networking' => { 'fqdn' => host }})
scope.function_fqdn_rand([max] + extra)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/split_spec.rb | spec/unit/parser/functions/split_spec.rb | require 'spec_helper'
describe "the split function" do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it 'should raise a ParseError' do
expect { @scope.function_split([ '130;236;254;10', ';']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/inline_template_spec.rb | spec/unit/parser/functions/inline_template_spec.rb | require 'spec_helper'
describe "the inline_template function" do
let(:node) { Puppet::Node.new('localhost') }
let(:compiler) { Puppet::Parser::Compiler.new(node) }
let(:scope) { Puppet::Parser::Scope.new(compiler) }
it "should concatenate template wrapper outputs for multiple templates" do
expect(inline_template("template1", "template2")).to eq("template1template2")
end
it "should raise an error if the template raises an error" do
expect { inline_template("<% raise 'error' %>") }.to raise_error(Puppet::ParseError)
end
it "is not interfered with by a variable called 'string' (#14093)" do
scope['string'] = "this is a variable"
expect(inline_template("this is a template")).to eq("this is a template")
end
it "has access to a variable called 'string' (#14093)" do
scope['string'] = "this is a variable"
expect(inline_template("string was: <%= @string %>")).to eq("string was: this is a variable")
end
it 'is not available when --tasks is on' do
Puppet[:tasks] = true
expect {
inline_template("<%= lookupvar('myvar') %>")
}.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/)
end
def inline_template(*templates)
scope.function_inline_template(templates)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/tagged_spec.rb | spec/unit/parser/functions/tagged_spec.rb | require 'spec_helper'
describe "the 'tagged' function" do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
expect(Puppet::Parser::Functions.function(:tagged)).to eq("function_tagged")
end
it 'is not available when --tasks is on' do
Puppet[:tasks] = true
expect do
@scope.function_tagged(['one', 'two'])
end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/)
end
it 'should be case-insensitive' do
resource = Puppet::Parser::Resource.new(:file, "/file", :scope => @scope)
allow(@scope).to receive(:resource).and_return(resource)
@scope.function_tag ["one"]
expect(@scope.function_tagged(['One'])).to eq(true)
end
it 'should check if all specified tags are included' do
resource = Puppet::Parser::Resource.new(:file, "/file", :scope => @scope)
allow(@scope).to receive(:resource).and_return(resource)
@scope.function_tag ["one"]
expect(@scope.function_tagged(['one', 'two'])).to eq(false)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/digest_spec.rb | spec/unit/parser/functions/digest_spec.rb | require 'spec_helper'
describe "the digest function", :uses_checksums => true do
before :each do
n = Puppet::Node.new('unnamed')
c = Puppet::Parser::Compiler.new(n)
@scope = Puppet::Parser::Scope.new(c)
end
it "should exist" do
expect(Puppet::Parser::Functions.function("digest")).to eq("function_digest")
end
with_digest_algorithms do
it "should use the proper digest function" do
result = @scope.function_digest([plaintext])
expect(result).to(eql( checksum ))
end
it "should only accept one parameter" do
expect do
@scope.function_digest(['foo', 'bar'])
end.to raise_error(ArgumentError)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/lookup_spec.rb | spec/unit/parser/functions/lookup_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'stringio'
require 'puppet_spec/scope'
describe "lookup function" do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
it 'should raise an error since this function is converted to 4x API)' do
expect { scope.function_lookup(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/tag_spec.rb | spec/unit/parser/functions/tag_spec.rb | require 'spec_helper'
describe "the 'tag' function" do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
expect(Puppet::Parser::Functions.function(:tag)).to eq("function_tag")
end
it "should tag the resource with any provided tags" do
resource = Puppet::Parser::Resource.new(:file, "/file", :scope => @scope)
expect(@scope).to receive(:resource).and_return(resource)
@scope.function_tag ["one", "two"]
expect(resource).to be_tagged("one")
expect(resource).to be_tagged("two")
end
it 'is not available when --tasks is on' do
Puppet[:tasks] = true
expect do
@scope.function_tag(['one', 'two'])
end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/realize_spec.rb | spec/unit/parser/functions/realize_spec.rb | require 'spec_helper'
require 'matchers/resource'
require 'puppet_spec/compiler'
describe "the realize function" do
include Matchers::Resource
include PuppetSpec::Compiler
it "realizes a single, referenced resource" do
catalog = compile_to_catalog(<<-EOM)
@notify { testing: }
realize(Notify[testing])
EOM
expect(catalog).to have_resource("Notify[testing]")
end
it "realizes multiple resources" do
catalog = compile_to_catalog(<<-EOM)
@notify { testing: }
@notify { other: }
realize(Notify[testing], Notify[other])
EOM
expect(catalog).to have_resource("Notify[testing]")
expect(catalog).to have_resource("Notify[other]")
end
it "realizes resources provided in arrays" do
catalog = compile_to_catalog(<<-EOM)
@notify { testing: }
@notify { other: }
realize([Notify[testing], [Notify[other]]])
EOM
expect(catalog).to have_resource("Notify[testing]")
expect(catalog).to have_resource("Notify[other]")
end
it "fails when the resource does not exist" do
expect do
compile_to_catalog(<<-EOM)
realize(Notify[missing])
EOM
end.to raise_error(Puppet::Error, /Failed to realize/)
end
it "fails when no parameters given" do
expect do
compile_to_catalog(<<-EOM)
realize()
EOM
end.to raise_error(Puppet::Error, /Wrong number of arguments/)
end
it "silently does nothing when an empty array of resources is given" do
compile_to_catalog(<<-EOM)
realize([])
EOM
end
it 'is not available when --tasks is on' do
Puppet[:tasks] = true
expect do
compile_to_catalog(<<-MANIFEST)
realize([])
MANIFEST
end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/template_spec.rb | spec/unit/parser/functions/template_spec.rb | require 'spec_helper'
describe "the template function" do
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
it "concatenates outputs for multiple templates" do
tw1 = double("template_wrapper1")
tw2 = double("template_wrapper2")
allow(Puppet::Parser::TemplateWrapper).to receive(:new).and_return(tw1,tw2)
allow(tw1).to receive(:file=).with("1")
allow(tw2).to receive(:file=).with("2")
allow(tw1).to receive(:result).and_return("result1")
allow(tw2).to receive(:result).and_return("result2")
expect(scope.function_template(["1","2"])).to eq("result1result2")
end
it "raises an error if the template raises an error" do
tw = double('template_wrapper')
allow(tw).to receive(:file=).with("1")
allow(Puppet::Parser::TemplateWrapper).to receive(:new).and_return(tw)
allow(tw).to receive(:result).and_raise
expect {
scope.function_template(["1"])
}.to raise_error(Puppet::ParseError, /Failed to parse template/)
end
context "when accessing scope variables via method calls (deprecated)" do
it "raises an error when accessing an undefined variable" do
expect {
eval_template("template <%= deprecated %>")
}.to raise_error(Puppet::ParseError, /undefined local variable or method `deprecated'/)
end
it "looks up the value from the scope" do
scope["deprecated"] = "deprecated value"
expect { eval_template("template <%= deprecated %>")}.to raise_error(/undefined local variable or method `deprecated'/)
end
it "still has access to Kernel methods" do
expect { eval_template("<%= binding %>") }.to_not raise_error
end
end
context "when accessing scope variables as instance variables" do
it "has access to values" do
scope['scope_var'] = "value"
expect(eval_template("<%= @scope_var %>")).to eq("value")
end
it "get nil accessing a variable that does not exist" do
expect(eval_template("<%= @not_defined.nil? %>")).to eq("true")
end
it "get nil accessing a variable that is undef" do
scope['undef_var'] = :undef
expect(eval_template("<%= @undef_var.nil? %>")).to eq("true")
end
end
it "is not interfered with by having a variable named 'string' (#14093)" do
scope['string'] = "this output should not be seen"
expect(eval_template("some text that is static")).to eq("some text that is static")
end
it "has access to a variable named 'string' (#14093)" do
scope['string'] = "the string value"
expect(eval_template("string was: <%= @string %>")).to eq("string was: the string value")
end
it "does not have direct access to Scope#lookupvar" do
expect {
eval_template("<%= lookupvar('myvar') %>")
}.to raise_error(Puppet::ParseError, /undefined method `lookupvar'/)
end
it 'is not available when --tasks is on' do
Puppet[:tasks] = true
expect {
eval_template("<%= lookupvar('myvar') %>")
}.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/)
end
def eval_template(content)
allow(Puppet::FileSystem).to receive(:read_preserve_line_endings).with("template").and_return(content)
allow(Puppet::Parser::Files).to receive(:find_template).and_return("template")
scope.function_template(['template'])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/functions/regsubst_spec.rb | spec/unit/parser/functions/regsubst_spec.rb | require 'spec_helper'
describe "the regsubst function" do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it 'should raise an ParseError' do
expect do
@scope.function_regsubst(
[ 'the monkey breaks banana trees',
'b[an]*a',
'coconut'
])
end.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/ast/block_expression_spec.rb | spec/unit/parser/ast/block_expression_spec.rb | require 'spec_helper'
require 'puppet/parser/ast/block_expression'
describe 'Puppet::Parser::AST::BlockExpression' do
class StackDepthAST < Puppet::Parser::AST
attr_reader :call_depth
def evaluate(*options)
@call_depth = caller.length
end
end
NO_SCOPE = nil
def depth_probe
StackDepthAST.new
end
def sequence_probe(name)
probe = double("Sequence Probe #{name}")
expect(probe).to receive(:safeevaluate).ordered
probe
end
def block_of(children)
Puppet::Parser::AST::BlockExpression.new(:children => children)
end
def assert_all_at_same_depth(*probes)
depth0 = probes[0].call_depth
probes.drop(1).each do |p|
expect(p.call_depth).to eq(depth0)
end
end
it "evaluates all its children at the same stack depth" do
depth_probes = [depth_probe, depth_probe]
expr = block_of(depth_probes)
expr.evaluate(NO_SCOPE)
assert_all_at_same_depth(*depth_probes)
end
it "evaluates sequenced children at the same stack depth" do
depth1 = depth_probe
depth2 = depth_probe
depth3 = depth_probe
expr1 = block_of([depth1])
expr2 = block_of([depth2])
expr3 = block_of([depth3])
expr1.sequence_with(expr2).sequence_with(expr3).evaluate(NO_SCOPE)
assert_all_at_same_depth(depth1, depth2, depth3)
end
it "evaluates sequenced children in order" do
expr1 = block_of([sequence_probe("Step 1")])
expr2 = block_of([sequence_probe("Step 2")])
expr3 = block_of([sequence_probe("Step 3")])
expr1.sequence_with(expr2).sequence_with(expr3).evaluate(NO_SCOPE)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parser/ast/leaf_spec.rb | spec/unit/parser/ast/leaf_spec.rb | require 'spec_helper'
describe Puppet::Parser::AST::Leaf do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
@value = double('value')
@leaf = Puppet::Parser::AST::Leaf.new(:value => @value)
end
describe "when converting to string" do
it "should transform its value to string" do
value = double('value', :is_a? => true)
expect(value).to receive(:to_s)
Puppet::Parser::AST::Leaf.new( :value => value ).to_s
end
end
it "should have a match method" do
expect(@leaf).to respond_to(:match)
end
it "should delegate match to ==" do
expect(@value).to receive(:==).with("value")
@leaf.match("value")
end
end
describe Puppet::Parser::AST::Regex do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
describe "when initializing" do
it "should create a Regexp with its content when value is not a Regexp" do
expect(Regexp).to receive(:new).with("/ab/")
Puppet::Parser::AST::Regex.new :value => "/ab/"
end
it "should not create a Regexp with its content when value is a Regexp" do
value = Regexp.new("/ab/")
expect(Regexp).not_to receive(:new).with("/ab/")
Puppet::Parser::AST::Regex.new :value => value
end
end
describe "when evaluating" do
it "should return self" do
val = Puppet::Parser::AST::Regex.new :value => "/ab/"
expect(val.evaluate(@scope)).to be === val
end
end
it 'should return the PRegexpType#regexp_to_s_with_delimiters with to_s' do
regex = double('regex')
allow(Regexp).to receive(:new).and_return(regex)
val = Puppet::Parser::AST::Regex.new :value => '/ab/'
expect(Puppet::Pops::Types::PRegexpType).to receive(:regexp_to_s_with_delimiters)
val.to_s
end
it "should delegate match to the underlying regexp match method" do
regex = Regexp.new("/ab/")
val = Puppet::Parser::AST::Regex.new :value => regex
expect(regex).to receive(:match).with("value")
val.match("value")
end
end
describe Puppet::Parser::AST::HostName do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
@value = 'value'
allow(@value).to receive(:to_s).and_return(@value)
allow(@value).to receive(:downcase).and_return(@value)
@host = Puppet::Parser::AST::HostName.new(:value => @value)
end
it "should raise an error if hostname is not valid" do
expect { Puppet::Parser::AST::HostName.new( :value => "not a hostname!" ) }.to raise_error(Puppet::DevError, /'not a hostname!' is not a valid hostname/)
end
it "should not raise an error if hostname is a regex" do
expect { Puppet::Parser::AST::HostName.new( :value => Puppet::Parser::AST::Regex.new(:value => "/test/") ) }.not_to raise_error
end
it "should stringify the value" do
value = double('value', :=~ => false)
expect(value).to receive(:to_s).and_return("test")
Puppet::Parser::AST::HostName.new(:value => value)
end
it "should downcase the value" do
value = double('value', :=~ => false)
allow(value).to receive(:to_s).and_return("UPCASED")
host = Puppet::Parser::AST::HostName.new(:value => value)
host.value == "upcased"
end
it "should evaluate to its value" do
expect(@host.evaluate(@scope)).to eq(@value)
end
it "should delegate eql? to the underlying value if it is an HostName" do
expect(@value).to receive(:eql?).with("value")
@host.eql?("value")
end
it "should delegate eql? to the underlying value if it is not an HostName" do
value = double('compared', :is_a? => true, :value => "value")
expect(@value).to receive(:eql?).with("value")
@host.eql?(value)
end
it "should delegate hash to the underlying value" do
expect(@value).to receive(:hash)
@host.hash
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/other/selinux_spec.rb | spec/unit/other/selinux_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file), " when manipulating file contexts" do
include PuppetSpec::Files
before :each do
@file = Puppet::Type::File.new(
:name => make_absolute("/tmp/foo"),
:ensure => "file",
:seluser => "user_u",
:selrole => "role_r",
:seltype => "type_t")
end
it "should use :seluser to get/set an SELinux user file context attribute" do
expect(@file[:seluser]).to eq("user_u")
end
it "should use :selrole to get/set an SELinux role file context attribute" do
expect(@file[:selrole]).to eq("role_r")
end
it "should use :seltype to get/set an SELinux user file context attribute" do
expect(@file[:seltype]).to eq("type_t")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/context/trusted_information_spec.rb | spec/unit/context/trusted_information_spec.rb | require 'spec_helper'
require 'puppet/certificate_factory'
require 'puppet/context/trusted_information'
describe Puppet::Context::TrustedInformation, :unless => RUBY_PLATFORM == 'java' do
let(:key) { OpenSSL::PKey::RSA.new(Puppet[:keylength]) }
let(:csr) do
csr = Puppet::SSL::CertificateRequest.new("csr")
csr.generate(key, :extension_requests => {
'1.3.6.1.4.1.15.1.2.1' => 'Ignored CSR extension',
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
})
csr
end
let(:cert) do
cert = Puppet::SSL::Certificate.from_instance(Puppet::CertificateFactory.build('ca', csr, csr.content, 1))
# The cert must be signed so that it can be successfully be DER-decoded later
signer = Puppet::SSL::CertificateSigner.new
signer.sign(cert.content, key)
cert
end
let(:external_data) {
{
'string' => 'a',
'integer' => 1,
'boolean' => true,
'hash' => { 'one' => 'two' },
'array' => ['b', 2, {}]
}
}
def allow_external_trusted_data(certname, data)
command = 'generate_data.sh'
Puppet[:trusted_external_command] = command
# The expand_path bit is necessary b/c :trusted_external_command is a
# file_or_directory setting, and file_or_directory settings automatically
# expand the given path.
allow(Puppet::Util::Execution).to receive(:execute).with([File.expand_path(command), certname], anything).and_return(JSON.dump(data))
end
it "defaults external to an empty hash" do
trusted = Puppet::Context::TrustedInformation.new(false, 'ignored', nil)
expect(trusted.external).to eq({})
end
context "when remote" do
it "has no cert information when it isn't authenticated" do
trusted = Puppet::Context::TrustedInformation.remote(false, 'ignored', nil)
expect(trusted.authenticated).to eq(false)
expect(trusted.certname).to be_nil
expect(trusted.extensions).to eq({})
end
it "is remote and has certificate information when it is authenticated" do
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
expect(trusted.authenticated).to eq('remote')
expect(trusted.certname).to eq('cert name')
expect(trusted.extensions).to eq({
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
})
expect(trusted.hostname).to eq('cert name')
expect(trusted.domain).to be_nil
end
it "is remote but lacks certificate information when it is authenticated" do
expect(Puppet).to receive(:info).once.with("TrustedInformation expected a certificate, but none was given.")
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', nil)
expect(trusted.authenticated).to eq('remote')
expect(trusted.certname).to eq('cert name')
expect(trusted.extensions).to eq({})
end
it 'contains external trusted data' do
allow_external_trusted_data('cert name', external_data)
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', nil)
expect(trusted.external).to eq(external_data)
end
it 'does not run the trusted external command when creating a trusted context' do
Puppet[:trusted_external_command] = '/usr/bin/generate_data.sh'
expect(Puppet::Util::Execution).to receive(:execute).never
Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
end
it 'only runs the trusted external command the first time it is invoked' do
command = 'generate_data.sh'
Puppet[:trusted_external_command] = command
# See allow_external_trusted_data to understand why expand_path is necessary
expect(Puppet::Util::Execution).to receive(:execute).with([File.expand_path(command), 'cert name'], anything).and_return(JSON.dump(external_data)).once
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
trusted.external
trusted.external
end
end
context "when local" do
it "is authenticated local with the nodes clientcert" do
node = Puppet::Node.new('testing', :parameters => { 'clientcert' => 'cert name' })
trusted = Puppet::Context::TrustedInformation.local(node)
expect(trusted.authenticated).to eq('local')
expect(trusted.certname).to eq('cert name')
expect(trusted.extensions).to eq({})
expect(trusted.hostname).to eq('cert name')
expect(trusted.domain).to be_nil
end
it "is authenticated local with no clientcert when there is no node" do
trusted = Puppet::Context::TrustedInformation.local(nil)
expect(trusted.authenticated).to eq('local')
expect(trusted.certname).to be_nil
expect(trusted.extensions).to eq({})
expect(trusted.hostname).to be_nil
expect(trusted.domain).to be_nil
end
it 'contains external trusted data' do
allow_external_trusted_data('cert name', external_data)
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', nil)
expect(trusted.external).to eq(external_data)
end
end
it "converts itself to a hash" do
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
expect(trusted.to_h).to eq({
'authenticated' => 'remote',
'certname' => 'cert name',
'extensions' => {
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
},
'hostname' => 'cert name',
'domain' => nil,
'external' => {},
})
end
it "extracts domain and hostname from certname" do
trusted = Puppet::Context::TrustedInformation.remote(true, 'hostname.domain.long', cert)
expect(trusted.to_h).to eq({
'authenticated' => 'remote',
'certname' => 'hostname.domain.long',
'extensions' => {
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
},
'hostname' => 'hostname',
'domain' => 'domain.long',
'external' => {},
})
end
it "freezes the hash" do
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
expect(trusted.to_h).to be_deeply_frozen
end
matcher :be_deeply_frozen do
match do |actual|
unfrozen_items(actual).empty?
end
failure_message do |actual|
"expected all items to be frozen but <#{unfrozen_items(actual).join(', ')}> was not"
end
define_method :unfrozen_items do |actual|
unfrozen = []
stack = [actual]
while item = stack.pop
if !item.frozen?
unfrozen.push(item)
end
case item
when Hash
stack.concat(item.keys)
stack.concat(item.values)
when Array
stack.concat(item)
end
end
unfrozen
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/external_client_spec.rb | spec/unit/http/external_client_spec.rb | require 'spec_helper'
require 'puppet/http'
# Simple "external" client to make get & post requests. This is used
# to test the old HTTP API, such as requiring use_ssl and basic_auth
# to be passed as options.
class Puppet::HTTP::TestExternal
def initialize(host, port, options = {})
@host = host
@port = port
@options = options
@factory = Puppet::HTTP::Factory.new
end
def get(path, headers = {}, options = {})
request = Net::HTTP::Get.new(path, headers)
do_request(request, options)
end
def post(path, data, headers = nil, options = {})
request = Net::HTTP::Post.new(path, headers)
do_request(request, options)
end
def do_request(request, options)
if options[:basic_auth]
request.basic_auth(options[:basic_auth][:user], options[:basic_auth][:password])
end
site = Puppet::HTTP::Site.new(@options[:use_ssl] ? 'https' : 'http', @host, @port)
http = @factory.create_connection(site)
http.start
begin
http.request(request)
ensure
http.finish
end
end
end
describe Puppet::HTTP::ExternalClient do
let(:uri) { URI.parse('https://www.example.com') }
let(:http_client_class) { Puppet::HTTP::TestExternal }
let(:client) { described_class.new(http_client_class) }
let(:credentials) { ['user', 'pass'] }
context "for GET requests" do
it "stringifies keys and encodes values in the query" do
stub_request(:get, uri).with(query: "foo=bar%3Dbaz")
client.get(uri, params: {:foo => "bar=baz"})
end
it "fails if a user passes in an invalid param type" do
environment = Puppet::Node::Environment.create(:testing, [])
expect{client.get(uri, params: {environment: environment})}.to raise_error(Puppet::HTTP::SerializationError, /HTTP REST queries cannot handle values of type/)
end
it "returns the response" do
stub_request(:get, uri)
response = client.get(uri)
expect(response).to be_a(Puppet::HTTP::Response)
expect(response).to be_success
expect(response.code).to eq(200)
end
it "returns the entire response body" do
stub_request(:get, uri).to_return(body: "abc")
expect(client.get(uri).body).to eq("abc")
end
it "streams the response body when a block is given" do
stub_request(:get, uri).to_return(body: "abc")
io = StringIO.new
client.get(uri) do |response|
response.read_body do |data|
io.write(data)
end
end
expect(io.string).to eq("abc")
end
context 'when connecting' do
it 'accepts an ssl context' do
stub_request(:get, uri).to_return(body: "abc")
other_context = Puppet::SSL::SSLContext.new
client.get(uri, options: {ssl_context: other_context})
end
it 'accepts include_system_store' do
stub_request(:get, uri).to_return(body: "abc")
client.get(uri, options: {include_system_store: true})
end
end
end
context "for POST requests" do
it "stringifies keys and encodes values in the query" do
stub_request(:post, "https://www.example.com").with(query: "foo=bar%3Dbaz")
client.post(uri, "", params: {:foo => "bar=baz"}, headers: {'Content-Type' => 'text/plain'})
end
it "returns the response" do
stub_request(:post, uri)
response = client.post(uri, "", headers: {'Content-Type' => 'text/plain'})
expect(response).to be_a(Puppet::HTTP::Response)
expect(response).to be_success
expect(response.code).to eq(200)
end
it "sets content-type for the body" do
stub_request(:post, uri).with(headers: {"Content-Type" => "text/plain"})
client.post(uri, "hello", headers: {'Content-Type' => 'text/plain'})
end
it "streams the response body when a block is given" do
stub_request(:post, uri).to_return(body: "abc")
io = StringIO.new
client.post(uri, "", headers: {'Content-Type' => 'text/plain'}) do |response|
response.read_body do |data|
io.write(data)
end
end
expect(io.string).to eq("abc")
end
it 'raises an ArgumentError if `body` is missing' do
expect {
client.post(uri, nil, headers: {'Content-Type' => 'text/plain'})
}.to raise_error(ArgumentError, /'post' requires a string 'body' argument/)
end
context 'when connecting' do
it 'accepts an ssl context' do
stub_request(:post, uri)
other_context = Puppet::SSL::SSLContext.new
client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: other_context})
end
it 'accepts include_system_store' do
stub_request(:post, uri)
client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {include_system_store: true})
end
end
end
context "Basic Auth" do
it "submits credentials for GET requests" do
stub_request(:get, uri).with(basic_auth: credentials)
client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}})
end
it "submits credentials for POST requests" do
stub_request(:post, uri).with(basic_auth: credentials)
client.post(uri, "", options: {content_type: 'text/plain', basic_auth: {user: 'user', password: 'pass'}})
end
it "returns response containing access denied" do
stub_request(:get, uri).with(basic_auth: credentials).to_return(status: [403, "Ye Shall Not Pass"])
response = client.get(uri, options: { basic_auth: {user: 'user', password: 'pass'}})
expect(response.code).to eq(403)
expect(response.reason).to eq("Ye Shall Not Pass")
expect(response).to_not be_success
end
it 'includes basic auth if user is nil' do
stub_request(:get, uri).with do |req|
expect(req.headers).to include('Authorization')
end
client.get(uri, options: {basic_auth: {user: nil, password: 'pass'}})
end
it 'includes basic auth if password is nil' do
stub_request(:get, uri).with do |req|
expect(req.headers).to include('Authorization')
end
client.get(uri, options: {basic_auth: {user: 'user', password: nil}})
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/response_spec.rb | spec/unit/http/response_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Response do
let(:uri) { URI.parse('https://www.example.com') }
let(:client) { Puppet::HTTP::Client.new }
it "returns the request URL" do
stub_request(:get, uri)
response = client.get(uri)
expect(response.url).to eq(uri)
end
it "returns the HTTP code" do
stub_request(:get, uri)
response = client.get(uri)
expect(response.code).to eq(200)
end
it "returns the HTTP reason string" do
stub_request(:get, uri).to_return(status: [418, "I'm a teapot"])
response = client.get(uri)
expect(response.reason).to eq("I'm a teapot")
end
it "returns the response body" do
stub_request(:get, uri).to_return(status: 200, body: "I'm the body")
response = client.get(uri)
expect(response.body).to eq("I'm the body")
end
it "streams the response body" do
stub_request(:get, uri).to_return(status: 200, body: "I'm the streaming body")
content = StringIO.new
client.get(uri) do |response|
response.read_body do |data|
content << data
end
end
expect(content.string).to eq("I'm the streaming body")
end
it "raises if a block isn't given when streaming" do
stub_request(:get, uri).to_return(status: 200, body: "")
expect {
client.get(uri) do |response|
response.read_body
end
}.to raise_error(Puppet::HTTP::HTTPError, %r{Request to https://www.example.com failed after .* seconds: A block is required})
end
it "returns success for all 2xx codes" do
stub_request(:get, uri).to_return(status: 202)
expect(client.get(uri)).to be_success
end
it "returns a header value" do
stub_request(:get, uri).to_return(status: 200, headers: { 'Content-Encoding' => 'gzip' })
expect(client.get(uri)['Content-Encoding']).to eq('gzip')
end
it "enumerates headers" do
stub_request(:get, uri).to_return(status: 200, headers: { 'Content-Encoding' => 'gzip' })
expect(client.get(uri).each_header.to_a).to eq([['content-encoding', 'gzip']])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/site_spec.rb | spec/unit/http/site_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Site do
let(:scheme) { 'https' }
let(:host) { 'rubygems.org' }
let(:port) { 443 }
def create_site(scheme, host, port)
described_class.new(scheme, host, port)
end
it 'accepts scheme, host, and port' do
site = create_site(scheme, host, port)
expect(site.scheme).to eq(scheme)
expect(site.host).to eq(host)
expect(site.port).to eq(port)
end
it 'generates an external URI string' do
site = create_site(scheme, host, port)
expect(site.addr).to eq("https://rubygems.org:443")
end
it 'considers sites to be different when the scheme is different' do
https_site = create_site('https', host, port)
http_site = create_site('http', host, port)
expect(https_site).to_not eq(http_site)
end
it 'considers sites to be different when the host is different' do
rubygems_site = create_site(scheme, 'rubygems.org', port)
github_site = create_site(scheme, 'github.com', port)
expect(rubygems_site).to_not eq(github_site)
end
it 'considers sites to be different when the port is different' do
site_443 = create_site(scheme, host, 443)
site_80 = create_site(scheme, host, 80)
expect(site_443).to_not eq(site_80)
end
it 'compares values when determining equality' do
site = create_site(scheme, host, port)
sites = {}
sites[site] = site
another_site = create_site(scheme, host, port)
expect(sites.include?(another_site)).to be_truthy
end
it 'computes the same hash code for equivalent objects' do
site = create_site(scheme, host, port)
same_site = create_site(scheme, host, port)
expect(site.hash).to eq(same_site.hash)
end
it 'uses ssl with https' do
site = create_site('https', host, port)
expect(site).to be_use_ssl
end
it 'does not use ssl with http' do
site = create_site('http', host, port)
expect(site).to_not be_use_ssl
end
it 'moves to a new URI location' do
site = create_site('http', 'host1', 80)
uri = URI.parse('https://host2:443/some/where/else')
new_site = site.move_to(uri)
expect(new_site.scheme).to eq('https')
expect(new_site.host).to eq('host2')
expect(new_site.port).to eq(443)
end
it 'creates a site from a URI' do
site = create_site('https', 'rubygems.org', 443)
uri = URI.parse('https://rubygems.org/gems/puppet/')
expect(described_class.from_uri(uri)).to eq(site)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/client_spec.rb | spec/unit/http/client_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Client do
let(:uri) { URI.parse('https://www.example.com') }
let(:puppet_context) { Puppet::SSL::SSLContext.new }
let(:system_context) { Puppet::SSL::SSLContext.new }
let(:client) { described_class.new(ssl_context: puppet_context, system_ssl_context: system_context) }
let(:credentials) { ['user', 'pass'] }
it 'creates unique sessions' do
expect(client.create_session).to_not eq(client.create_session)
end
context "when connecting" do
it 'connects to HTTP URLs' do
uri = URI.parse('http://www.example.com')
client.connect(uri) do |http|
expect(http.address).to eq('www.example.com')
expect(http.port).to eq(80)
expect(http).to_not be_use_ssl
end
end
it 'connects to HTTPS URLs' do
client.connect(uri) do |http|
expect(http.address).to eq('www.example.com')
expect(http.port).to eq(443)
expect(http).to be_use_ssl
end
end
it 'raises ConnectionError if the connection is refused' do
allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Errno::ECONNREFUSED)
expect {
client.connect(uri)
}.to raise_error(Puppet::HTTP::ConnectionError, %r{^Request to https://www.example.com failed after .* seconds: (Connection refused|No connection could be made because the target machine actively refused it)})
end
it 'raises ConnectionError if the connect times out' do
allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Net::OpenTimeout)
expect {
client.connect(uri)
}.to raise_error(Puppet::HTTP::ConnectionError, %r{^Request to https://www.example.com timed out connect operation after .* seconds})
end
it 'connects using the default ssl context' do
expect(client.pool).to receive(:with_connection) do |_, verifier|
expect(verifier.ssl_context).to equal(puppet_context)
end
client.connect(uri)
end
it 'connects using a specified ssl context' do
other_context = Puppet::SSL::SSLContext.new
expect(client.pool).to receive(:with_connection) do |_, verifier|
expect(verifier.ssl_context).to equal(other_context)
end
client.connect(uri, options: {ssl_context: other_context})
end
it 'connects using the system store' do
expect(client.pool).to receive(:with_connection) do |_, verifier|
expect(verifier.ssl_context).to equal(system_context)
end
client.connect(uri, options: {include_system_store: true})
end
it 'does not create a verifier for HTTP connections' do
expect(client.pool).to receive(:with_connection) do |_, verifier|
expect(verifier).to be_nil
end
client.connect(URI.parse('http://www.example.com'))
end
it 'raises an HTTPError if both are specified' do
expect {
client.connect(uri, options: {ssl_context: puppet_context, include_system_store: true})
}.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/)
end
end
context 'after connecting' do
def expect_http_error(cause, expected_message)
expect {
client.connect(uri) do |_|
raise cause, 'whoops'
end
}.to raise_error(Puppet::HTTP::HTTPError, expected_message)
end
it 're-raises HTTPError' do
expect_http_error(Puppet::HTTP::HTTPError, 'whoops')
end
it 'raises HTTPError if connection is interrupted while reading' do
expect_http_error(EOFError, %r{^Request to https://www.example.com interrupted after .* seconds})
end
it 'raises HTTPError if connection times out' do
expect_http_error(Net::ReadTimeout, %r{^Request to https://www.example.com timed out read operation after .* seconds})
end
it 'raises HTTPError if connection fails' do
expect_http_error(ArgumentError, %r{^Request to https://www.example.com failed after .* seconds})
end
end
context "when closing" do
it "closes all connections in the pool" do
expect(client.pool).to receive(:close)
client.close
end
it 'reloads the default ssl context' do
expect(client.pool).to receive(:with_connection) do |_, verifier|
expect(verifier.ssl_context).to_not equal(puppet_context)
end
client.close
client.connect(uri)
end
it 'reloads the default system ssl context' do
expect(client.pool).to receive(:with_connection) do |_, verifier|
expect(verifier.ssl_context).to_not equal(system_context)
end
client.close
client.connect(uri, options: {include_system_store: true})
end
end
context "for GET requests" do
it "includes default HTTP headers" do
stub_request(:get, uri).with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end
client.get(uri)
end
it "stringifies keys and encodes values in the query" do
stub_request(:get, uri).with(query: "foo=bar%3Dbaz")
client.get(uri, params: {:foo => "bar=baz"})
end
it "fails if a user passes in an invalid param type" do
environment = Puppet::Node::Environment.create(:testing, [])
expect{client.get(uri, params: {environment: environment})}.to raise_error(Puppet::HTTP::SerializationError, /HTTP REST queries cannot handle values of type/)
end
it "merges custom headers with default ones" do
stub_request(:get, uri).with(headers: { 'X-Foo' => 'Bar', 'X-Puppet-Version' => /./, 'User-Agent' => /./ })
client.get(uri, headers: {'X-Foo' => 'Bar'})
end
it "returns the response" do
stub_request(:get, uri)
response = client.get(uri)
expect(response).to be_a(Puppet::HTTP::Response)
expect(response).to be_success
expect(response.code).to eq(200)
end
it "returns the entire response body" do
stub_request(:get, uri).to_return(body: "abc")
expect(client.get(uri).body).to eq("abc")
end
it "streams the response body when a block is given" do
stub_request(:get, uri).to_return(body: "abc")
io = StringIO.new
client.get(uri) do |response|
response.read_body do |data|
io.write(data)
end
end
expect(io.string).to eq("abc")
end
context 'when connecting' do
it 'uses a specified ssl context' do
stub_request(:get, uri).to_return(body: "abc")
other_context = Puppet::SSL::SSLContext.new
client.get(uri, options: {ssl_context: other_context})
end
it 'uses the system store' do
stub_request(:get, uri).to_return(body: "abc")
client.get(uri, options: {include_system_store: true})
end
it 'raises an HTTPError if both are specified' do
expect {
client.get(uri, options: {ssl_context: puppet_context, include_system_store: true})
}.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/)
end
end
end
context "for HEAD requests" do
it "includes default HTTP headers" do
stub_request(:head, uri).with(headers: {'X-Puppet-Version' => /./, 'User-Agent' => /./})
client.head(uri)
end
it "stringifies keys and encodes values in the query" do
stub_request(:head, uri).with(query: "foo=bar%3Dbaz")
client.head(uri, params: {:foo => "bar=baz"})
end
it "merges custom headers with default ones" do
stub_request(:head, uri).with(headers: { 'X-Foo' => 'Bar', 'X-Puppet-Version' => /./, 'User-Agent' => /./ })
client.head(uri, headers: {'X-Foo' => 'Bar'})
end
it "returns the response" do
stub_request(:head, uri)
response = client.head(uri)
expect(response).to be_a(Puppet::HTTP::Response)
expect(response).to be_success
expect(response.code).to eq(200)
end
it "returns the entire response body" do
stub_request(:head, uri).to_return(body: "abc")
expect(client.head(uri).body).to eq("abc")
end
context 'when connecting' do
it 'uses a specified ssl context' do
stub_request(:head, uri)
other_context = Puppet::SSL::SSLContext.new
client.head(uri, options: {ssl_context: other_context})
end
it 'uses the system store' do
stub_request(:head, uri)
client.head(uri, options: {include_system_store: true})
end
it 'raises an HTTPError if both are specified' do
expect {
client.head(uri, options: {ssl_context: puppet_context, include_system_store: true})
}.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/)
end
end
end
context "for PUT requests" do
it "includes default HTTP headers" do
stub_request(:put, uri).with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end
client.put(uri, "", headers: {'Content-Type' => 'text/plain'})
end
it "stringifies keys and encodes values in the query" do
stub_request(:put, "https://www.example.com").with(query: "foo=bar%3Dbaz")
client.put(uri, "", params: {:foo => "bar=baz"}, headers: {'Content-Type' => 'text/plain'})
end
it "includes custom headers" do
stub_request(:put, "https://www.example.com").with(headers: { 'X-Foo' => 'Bar' })
client.put(uri, "", headers: {'X-Foo' => 'Bar', 'Content-Type' => 'text/plain'})
end
it "returns the response" do
stub_request(:put, uri)
response = client.put(uri, "", headers: {'Content-Type' => 'text/plain'})
expect(response).to be_a(Puppet::HTTP::Response)
expect(response).to be_success
expect(response.code).to eq(200)
end
it "sets content-length and content-type for the body" do
stub_request(:put, uri).with(headers: {"Content-Length" => "5", "Content-Type" => "text/plain"})
client.put(uri, "hello", headers: {'Content-Type' => 'text/plain'})
end
it 'raises an ArgumentError if `body` is missing' do
expect {
client.put(uri, nil, headers: {'Content-Type' => 'text/plain'})
}.to raise_error(ArgumentError, /'put' requires a string 'body' argument/)
end
it 'raises an ArgumentError if `content_type` is missing from the headers hash' do
expect {
client.put(uri, '')
}.to raise_error(ArgumentError, /'put' requires a 'content-type' header/)
end
context 'when connecting' do
it 'uses a specified ssl context' do
stub_request(:put, uri)
other_context = Puppet::SSL::SSLContext.new
client.put(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: other_context})
end
it 'uses the system store' do
stub_request(:put, uri)
client.put(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {include_system_store: true})
end
it 'raises an HTTPError if both are specified' do
expect {
client.put(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: puppet_context, include_system_store: true})
}.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/)
end
end
end
context "for POST requests" do
it "includes default HTTP headers" do
stub_request(:post, uri).with(headers: {'X-Puppet-Version' => /./, 'User-Agent' => /./})
client.post(uri, "", headers: {'Content-Type' => 'text/plain'})
end
it "stringifies keys and encodes values in the query" do
stub_request(:post, "https://www.example.com").with(query: "foo=bar%3Dbaz")
client.post(uri, "", params: {:foo => "bar=baz"}, headers: {'Content-Type' => 'text/plain'})
end
it "includes custom headers" do
stub_request(:post, "https://www.example.com").with(headers: { 'X-Foo' => 'Bar' })
client.post(uri, "", headers: {'X-Foo' => 'Bar', 'Content-Type' => 'text/plain'})
end
it "returns the response" do
stub_request(:post, uri)
response = client.post(uri, "", headers: {'Content-Type' => 'text/plain'})
expect(response).to be_a(Puppet::HTTP::Response)
expect(response).to be_success
expect(response.code).to eq(200)
end
it "sets content-length and content-type for the body" do
stub_request(:post, uri).with(headers: {"Content-Length" => "5", "Content-Type" => "text/plain"})
client.post(uri, "hello", headers: {'Content-Type' => 'text/plain'})
end
it "streams the response body when a block is given" do
stub_request(:post, uri).to_return(body: "abc")
io = StringIO.new
client.post(uri, "", headers: {'Content-Type' => 'text/plain'}) do |response|
response.read_body do |data|
io.write(data)
end
end
expect(io.string).to eq("abc")
end
it 'raises an ArgumentError if `body` is missing' do
expect {
client.post(uri, nil, headers: {'Content-Type' => 'text/plain'})
}.to raise_error(ArgumentError, /'post' requires a string 'body' argument/)
end
it 'raises an ArgumentError if `content_type` is missing from the headers hash' do
expect {
client.post(uri, "")
}.to raise_error(ArgumentError, /'post' requires a 'content-type' header/)
end
context 'when connecting' do
it 'uses a specified ssl context' do
stub_request(:post, uri)
other_context = Puppet::SSL::SSLContext.new
client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {body: "", ssl_context: other_context})
end
it 'uses the system store' do
stub_request(:post, uri)
client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {include_system_store: true})
end
it 'raises an HTTPError if both are specified' do
expect {
client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: puppet_context, include_system_store: true})
}.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/)
end
end
end
context "for DELETE requests" do
it "includes default HTTP headers" do
stub_request(:delete, uri).with(headers: {'X-Puppet-Version' => /./, 'User-Agent' => /./})
client.delete(uri)
end
it "merges custom headers with default ones" do
stub_request(:delete, uri).with(headers: { 'X-Foo' => 'Bar', 'X-Puppet-Version' => /./, 'User-Agent' => /./ })
client.delete(uri, headers: {'X-Foo' => 'Bar'})
end
it "stringifies keys and encodes values in the query" do
stub_request(:delete, "https://www.example.com").with(query: "foo=bar%3Dbaz")
client.delete(uri, params: {:foo => "bar=baz"})
end
it "returns the response" do
stub_request(:delete, uri)
response = client.delete(uri)
expect(response).to be_a(Puppet::HTTP::Response)
expect(response).to be_success
expect(response.code).to eq(200)
end
it "returns the entire response body" do
stub_request(:delete, uri).to_return(body: "abc")
expect(client.delete(uri).body).to eq("abc")
end
context 'when connecting' do
it 'uses a specified ssl context' do
stub_request(:delete, uri)
other_context = Puppet::SSL::SSLContext.new
client.delete(uri, options: {ssl_context: other_context})
end
it 'uses the system store' do
stub_request(:delete, uri)
client.delete(uri, options: {include_system_store: true})
end
it 'raises an HTTPError if both are specified' do
expect {
client.delete(uri, options: {ssl_context: puppet_context, include_system_store: true})
}.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/)
end
end
end
context "Basic Auth" do
it "submits credentials for GET requests" do
stub_request(:get, uri).with(basic_auth: credentials)
client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}})
end
it "submits credentials for PUT requests" do
stub_request(:put, uri).with(basic_auth: credentials)
client.put(uri, "hello", headers: {'Content-Type' => 'text/plain'}, options: {basic_auth: {user: 'user', password: 'pass'}})
end
it "returns response containing access denied" do
stub_request(:get, uri).with(basic_auth: credentials).to_return(status: [403, "Ye Shall Not Pass"])
response = client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}})
expect(response.code).to eq(403)
expect(response.reason).to eq("Ye Shall Not Pass")
expect(response).to_not be_success
end
it 'includes basic auth if user is nil' do
stub_request(:get, uri).with do |req|
expect(req.headers).to include('Authorization')
end
client.get(uri, options: {basic_auth: {user: nil, password: 'pass'}})
end
it 'includes basic auth if password is nil' do
stub_request(:get, uri).with do |req|
expect(req.headers).to include('Authorization')
end
client.get(uri, options: {basic_auth: {user: 'user', password: nil}})
end
it 'observes userinfo in the URL' do
stub_request(:get, uri).with(basic_auth: credentials)
client.get(URI("https://user:pass@www.example.com"))
end
it 'prefers explicit basic_auth credentials' do
uri = URI("https://ignored_user:ignored_pass@www.example.com")
stub_request(:get, "https://www.example.com").with(basic_auth: credentials)
client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}})
end
end
context "when redirecting" do
let(:start_url) { URI("https://www.example.com:8140/foo") }
let(:bar_url) { "https://www.example.com:8140/bar" }
let(:baz_url) { "https://www.example.com:8140/baz" }
let(:other_host) { "https://other.example.com:8140/qux" }
def redirect_to(status: 302, url:)
{ status: status, headers: { 'Location' => url }, body: "Redirected to #{url}" }
end
it "preserves GET method" do
stub_request(:get, start_url).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).to_return(status: 200)
response = client.get(start_url)
expect(response).to be_success
end
it "preserves PUT method" do
stub_request(:put, start_url).to_return(redirect_to(url: bar_url))
stub_request(:put, bar_url).to_return(status: 200)
response = client.put(start_url, "", headers: {'Content-Type' => 'text/plain'})
expect(response).to be_success
end
it "updates the Host header from the Location host and port" do
stub_request(:get, start_url).with(headers: { 'Host' => 'www.example.com:8140' })
.to_return(redirect_to(url: other_host))
stub_request(:get, other_host).with(headers: { 'Host' => 'other.example.com:8140' })
.to_return(status: 200)
response = client.get(start_url)
expect(response).to be_success
end
it "omits the default HTTPS port from the Host header" do
stub_request(:get, start_url).with(headers: { 'Host' => 'www.example.com:8140' })
.to_return(redirect_to(url: "https://other.example.com/qux"))
stub_request(:get, "https://other.example.com/qux").with(headers: { 'Host' => 'other.example.com' })
.to_return(status: 200)
response = client.get(start_url)
expect(response).to be_success
end
it "omits the default HTTP port from the Host header" do
stub_request(:get, start_url).with(headers: { 'Host' => 'www.example.com:8140' })
.to_return(redirect_to(url: "http://other.example.com/qux"))
stub_request(:get, "http://other.example.com/qux").with(headers: { 'Host' => 'other.example.com' })
.to_return(status: 200)
response = client.get(start_url)
expect(response).to be_success
end
it "applies query parameters from the location header" do
query = { 'redirected' => false }
stub_request(:get, start_url).with(query: query).to_return(redirect_to(url: "#{bar_url}?redirected=true"))
stub_request(:get, bar_url).with(query: {'redirected' => 'true'}).to_return(status: 200)
response = client.get(start_url, params: query)
expect(response).to be_success
end
it "preserves custom and default headers when redirecting" do
headers = { 'X-Foo' => 'Bar', 'X-Puppet-Version' => Puppet.version }
stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).with(headers: headers).to_return(status: 200)
response = client.get(start_url, headers: headers)
expect(response).to be_success
end
it "does not preserve basic authorization when redirecting to different hosts" do
stub_request(:get, start_url).with(basic_auth: credentials).to_return(redirect_to(url: other_host))
stub_request(:get, other_host).to_return(status: 200)
client.get(start_url, options: {basic_auth: {user: 'user', password: 'pass'}})
expect(a_request(:get, other_host).
with{ |req| !req.headers.key?('Authorization')}).to have_been_made
end
it "does preserve basic authorization when redirecting to the same hosts" do
stub_request(:get, start_url).with(basic_auth: credentials).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).with(basic_auth: credentials).to_return(status: 200)
client.get(start_url, options: {basic_auth: {user: 'user', password: 'pass'}})
expect(a_request(:get, bar_url).
with{ |req| req.headers.key?('Authorization')}).to have_been_made
end
it "does not preserve cookie header when redirecting to different hosts" do
headers = { 'Cookie' => 'TEST_COOKIE'}
stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: other_host))
stub_request(:get, other_host).to_return(status: 200)
client.get(start_url, headers: headers)
expect(a_request(:get, other_host).
with{ |req| !req.headers.key?('Cookie')}).to have_been_made
end
it "does preserve cookie header when redirecting to the same hosts" do
headers = { 'Cookie' => 'TEST_COOKIE'}
stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).with(headers: headers).to_return(status: 200)
client.get(start_url, headers: headers)
expect(a_request(:get, bar_url).
with{ |req| req.headers.key?('Cookie')}).to have_been_made
end
it "does preserves cookie header and basic authentication when Puppet[:location_trusted] is true redirecting to different hosts" do
headers = { 'cookie' => 'TEST_COOKIE'}
Puppet[:location_trusted] = true
stub_request(:get, start_url).with(headers: headers, basic_auth: credentials).to_return(redirect_to(url: other_host))
stub_request(:get, other_host).with(headers: headers, basic_auth: credentials).to_return(status: 200)
client.get(start_url, headers: headers, options: {basic_auth: {user: 'user', password: 'pass'}})
expect(a_request(:get, other_host).
with{ |req| req.headers.key?('Authorization') && req.headers.key?('Cookie')}).to have_been_made
end
it "treats hosts as case-insensitive" do
start_url = URI("https://www.EXAmple.com:8140/Start")
bar_url = "https://www.example.com:8140/bar"
stub_request(:get, start_url).with(basic_auth: credentials).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).with(basic_auth: credentials).to_return(status: 200)
client.get(start_url, options: {basic_auth: {user: 'user', password: 'pass'}})
expect(a_request(:get, bar_url).
with{ |req| req.headers.key?('Authorization')}).to have_been_made
end
it "redirects given a relative location" do
relative_url = "/people.html"
stub_request(:get, start_url).to_return(redirect_to(url: relative_url))
stub_request(:get, "https://www.example.com:8140/people.html").to_return(status: 200)
response = client.get(start_url)
expect(response).to be_success
end
it "applies query parameters from the location header" do
relative_url = "/people.html"
query = { 'redirected' => false }
stub_request(:get, start_url).with(query: query).to_return(redirect_to(url: "#{relative_url}?redirected=true"))
stub_request(:get, "https://www.example.com:8140/people.html").with(query: {'redirected' => 'true'}).to_return(status: 200)
response = client.get(start_url, params: query)
expect(response).to be_success
end
it "removes dot segments from a relative location" do
# from https://tools.ietf.org/html/rfc3986#section-5.4.2
base_url = URI("http://a/b/c/d;p?q")
relative_url = "../../../../g"
stub_request(:get, base_url).to_return(redirect_to(url: relative_url))
stub_request(:get, "http://a/g").to_return(status: 200)
response = client.get(base_url)
expect(response).to be_success
end
it "preserves request body for each request" do
data = 'some data'
stub_request(:put, start_url).with(body: data).to_return(redirect_to(url: bar_url))
stub_request(:put, bar_url).with(body: data).to_return(status: 200)
response = client.put(start_url, data, headers: {'Content-Type' => 'text/plain'})
expect(response).to be_success
end
it "returns the body from the final response" do
stub_request(:get, start_url).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).to_return(status: 200, body: 'followed')
response = client.get(start_url)
expect(response.body).to eq('followed')
end
[301, 307].each do |code|
it "also redirects on #{code}" do
stub_request(:get, start_url).to_return(redirect_to(status: code, url: bar_url))
stub_request(:get, bar_url).to_return(status: 200)
response = client.get(start_url)
expect(response).to be_success
end
end
[303, 308].each do |code|
it "returns an error on #{code}" do
stub_request(:get, start_url).to_return(redirect_to(status: code, url: bar_url))
response = client.get(start_url)
expect(response.code).to eq(code)
expect(response).to_not be_success
end
end
it "raises an error if the Location header is missing" do
stub_request(:get, start_url).to_return(status: 302)
expect {
client.get(start_url)
}.to raise_error(Puppet::HTTP::ProtocolError, "Location response header is missing")
end
it "raises an error if the Location header is invalid" do
stub_request(:get, start_url).to_return(redirect_to(status: 302, url: 'http://foo"bar'))
expect {
client.get(start_url)
}.to raise_error(Puppet::HTTP::ProtocolError, /Location URI is invalid/)
end
it "raises an error if limit is 0 and we're asked to follow" do
stub_request(:get, start_url).to_return(redirect_to(url: bar_url))
client = described_class.new(redirect_limit: 0)
expect {
client.get(start_url)
}.to raise_error(Puppet::HTTP::TooManyRedirects, %r{Too many HTTP redirections for https://www.example.com:8140})
end
it "raises an error if asked to follow redirects more times than the limit" do
stub_request(:get, start_url).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).to_return(redirect_to(url: baz_url))
client = described_class.new(redirect_limit: 1)
expect {
client.get(start_url)
}.to raise_error(Puppet::HTTP::TooManyRedirects, %r{Too many HTTP redirections for https://www.example.com:8140})
end
it "follows multiple redirects if equal to or less than the redirect limit" do
stub_request(:get, start_url).to_return(redirect_to(url: bar_url))
stub_request(:get, bar_url).to_return(redirect_to(url: baz_url))
stub_request(:get, baz_url).to_return(status: 200)
client = described_class.new(redirect_limit: 2)
response = client.get(start_url)
expect(response).to be_success
end
it "redirects to a different host" do
stub_request(:get, start_url).to_return(redirect_to(url: other_host))
stub_request(:get, other_host).to_return(status: 200)
response = client.get(start_url)
expect(response).to be_success
end
it "redirects from http to https" do
http = URI("http://example.com/foo")
https = URI("https://example.com/bar")
stub_request(:get, http).to_return(redirect_to(url: https))
stub_request(:get, https).to_return(status: 200)
response = client.get(http)
expect(response).to be_success
end
it "redirects from https to http" do
http = URI("http://example.com/foo")
https = URI("https://example.com/bar")
stub_request(:get, https).to_return(redirect_to(url: http))
stub_request(:get, http).to_return(status: 200)
response = client.get(https)
expect(response).to be_success
end
it "does not preserve accept-encoding header when redirecting" do
headers = { 'Accept-Encoding' => 'unwanted-encoding'}
stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: other_host))
stub_request(:get, other_host).to_return(status: 200)
client.get(start_url, headers: headers)
expect(a_request(:get, other_host).
with{ |req| req.headers['Accept-Encoding'] != 'unwanted-encoding' }).to have_been_made
end
end
context "when response indicates an overloaded server" do
def retry_after(datetime)
stub_request(:get, uri)
.to_return(status: [503, 'Service Unavailable'], headers: {'Retry-After' => datetime}).then
.to_return(status: 200)
end
it "returns a 503 response if Retry-After is not set" do
stub_request(:get, uri).to_return(status: [503, 'Service Unavailable'])
expect(client.get(uri).code).to eq(503)
end
it "raises if Retry-After is not convertible to an Integer or RFC 2822 Date" do
stub_request(:get, uri).to_return(status: [503, 'Service Unavailable'], headers: {'Retry-After' => 'foo'})
expect {
client.get(uri)
}.to raise_error(Puppet::HTTP::ProtocolError, /Failed to parse Retry-After header 'foo' as an integer or RFC 2822 date/)
end
it "should close the connection before sleeping" do
retry_after('42')
site = Puppet::HTTP::Site.from_uri(uri)
http1 = Net::HTTP.new(site.host, site.port)
http1.use_ssl = true
allow(http1).to receive(:started?).and_return(true)
http2 = Net::HTTP.new(site.host, site.port)
http2.use_ssl = true
allow(http2).to receive(:started?).and_return(true)
pool = Puppet::HTTP::Pool.new(15)
client = Puppet::HTTP::Client.new(pool: pool)
# The "with_connection" method is required to yield started connections
allow(pool).to receive(:with_connection).and_yield(http1).and_yield(http2)
expect(http1).to receive(:finish).ordered
expect(::Kernel).to receive(:sleep).with(42).ordered
client.get(uri)
end
it "should sleep and retry if Retry-After is an Integer" do
retry_after('42')
expect(::Kernel).to receive(:sleep).with(42)
client.get(uri)
end
it "should sleep and retry if Retry-After is an RFC 2822 Date" do
retry_after('Wed, 13 Apr 2005 15:18:05 GMT')
now = DateTime.new(2005, 4, 13, 8, 17, 5, '-07:00')
allow(DateTime).to receive(:now).and_return(now)
expect(::Kernel).to receive(:sleep).with(60)
client.get(uri)
end
it "should sleep for no more than the Puppet runinterval" do
retry_after('60')
Puppet[:runinterval] = 30
expect(::Kernel).to receive(:sleep).with(30)
client.get(uri)
end
it "should sleep for 0 seconds if the RFC 2822 date has past" do
retry_after('Wed, 13 Apr 2005 15:18:05 GMT')
expect(::Kernel).to receive(:sleep).with(0)
client.get(uri)
end
end
context "persistent connections" do
before :each do
stub_request(:get, uri)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/pool_entry_spec.rb | spec/unit/http/pool_entry_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::PoolEntry do
let(:connection) { double('connection') }
let(:verifier) { double('verifier') }
def create_session(connection, expiration_time = nil)
expiration_time ||= Time.now + 60 * 60
described_class.new(connection, verifier, expiration_time)
end
it 'provides access to its connection' do
session = create_session(connection)
expect(session.connection).to eq(connection)
end
it 'provides access to its verifier' do
session = create_session(connection)
expect(session.verifier).to eq(verifier)
end
it 'expires a connection whose expiration time is in the past' do
now = Time.now
past = now - 1
session = create_session(connection, past)
expect(session.expired?(now)).to be_truthy
end
it 'expires a connection whose expiration time is now' do
now = Time.now
session = create_session(connection, now)
expect(session.expired?(now)).to be_truthy
end
it 'does not expire a connection whose expiration time is in the future' do
now = Time.now
future = now + 1
session = create_session(connection, future)
expect(session.expired?(now)).to be_falsey
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/proxy_spec.rb | spec/unit/http/proxy_spec.rb | require 'uri'
require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Proxy do
before(:all) do
ENV['http_proxy'] = nil
ENV['HTTP_PROXY'] = nil
end
host, port, user, password = 'some.host', 1234, 'user1', 'pAssw0rd'
def expects_direct_connection_to(http, www)
expect(http.address).to eq(www.host)
expect(http.port).to eq(www.port)
expect(http.proxy_address).to be_nil
expect(http.proxy_port).to be_nil
expect(http.proxy_user).to be_nil
expect(http.proxy_pass).to be_nil
end
def expects_proxy_connection_via(http, www, host, port, user, password)
expect(http.address).to eq(www.host)
expect(http.port).to eq(www.port)
expect(http.proxy_address).to eq(host)
expect(http.proxy_port).to eq(port)
expect(http.proxy_user).to eq(user)
expect(http.proxy_pass).to eq(password)
end
describe '.proxy' do
let(:www) { URI::HTTP.build(host: 'www.example.com', port: 80) }
it 'uses a proxy' do
Puppet[:http_proxy_host] = host
Puppet[:http_proxy_port] = port
Puppet[:http_proxy_user] = user
Puppet[:http_proxy_password] = password
http = subject.proxy(www)
expects_proxy_connection_via(http, www, host, port, user, password)
end
it 'connects directly to the server' do
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
it 'connects directly to the server when HTTP_PROXY environment variable is set, but server matches no_proxy setting' do
Puppet[:http_proxy_host] = host
Puppet[:http_proxy_port] = port
Puppet[:no_proxy] = www.host
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
end
context 'when setting no_proxy' do
before :each do
Puppet[:http_proxy_host] = host
Puppet[:http_proxy_port] = port
end
it 'connects directly to the server when HTTP_PROXY environment variable is set, but server matches no_proxy setting' do
Puppet[:no_proxy] = www.host
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
end
it 'connects directly to the server when no_proxy matches wildcard domain' do
Puppet[:no_proxy] = '*.example.com'
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
it 'connects directly to the server when no_proxy matches dotted domain' do
Puppet[:no_proxy] = '.example.com'
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
it 'connects directly to the server when no_proxy matches a domain suffix like ruby does' do
Puppet[:no_proxy] = 'example.com'
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
it 'connects directly to the server when no_proxy matches a partial suffix like ruby does' do
Puppet[:no_proxy] = 'ample.com'
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
it 'connects directly to the server when it is a subdomain of no_proxy' do
Puppet[:no_proxy] = '*.com'
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
it 'connects directly to the server when no_proxy is *' do
Puppet[:no_proxy] = '*'
http = subject.proxy(www)
expects_direct_connection_to(http, www)
end
end
end
describe ".http_proxy_env" do
it "should return nil if no environment variables" do
expect(subject.http_proxy_env).to eq(nil)
end
it "should return a URI::HTTP object if http_proxy env variable is set" do
Puppet::Util.withenv('HTTP_PROXY' => host) do
expect(subject.http_proxy_env).to eq(URI.parse(host))
end
end
it "should return a URI::HTTP object if HTTP_PROXY env variable is set" do
Puppet::Util.withenv('HTTP_PROXY' => host) do
expect(subject.http_proxy_env).to eq(URI.parse(host))
end
end
it "should return a URI::HTTP object with .host and .port if URI is given" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
expect(subject.http_proxy_env).to eq(URI.parse("http://#{host}:#{port}"))
end
end
it "should return nil if proxy variable is malformed" do
Puppet::Util.withenv('HTTP_PROXY' => 'this is not a valid URI') do
expect(subject.http_proxy_env).to eq(nil)
end
end
end
describe ".http_proxy_host" do
it "should return nil if no proxy host in config or env" do
expect(subject.http_proxy_host).to eq(nil)
end
it "should return a proxy host if set in config" do
Puppet.settings[:http_proxy_host] = host
expect(subject.http_proxy_host).to eq(host)
end
it "should return nil if set to `none` in config" do
Puppet.settings[:http_proxy_host] = 'none'
expect(subject.http_proxy_host).to eq(nil)
end
it "uses environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
Puppet.settings[:http_proxy_host] = 'not.correct'
expect(subject.http_proxy_host).to eq(host)
end
end
end
describe ".http_proxy_port" do
it "should return a proxy port if set in environment" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
expect(subject.http_proxy_port).to eq(port)
end
end
it "should return a proxy port if set in config" do
Puppet.settings[:http_proxy_port] = port
expect(subject.http_proxy_port).to eq(port)
end
it "uses environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
Puppet.settings[:http_proxy_port] = 7456
expect(subject.http_proxy_port).to eq(port)
end
end
end
describe ".http_proxy_user" do
it "should return a proxy user if set in environment" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
expect(subject.http_proxy_user).to eq(user)
end
end
it "should return a proxy user if set in config" do
Puppet.settings[:http_proxy_user] = user
expect(subject.http_proxy_user).to eq(user)
end
it "should use environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
Puppet.settings[:http_proxy_user] = 'clownpants'
expect(subject.http_proxy_user).to eq(user)
end
end
end
describe ".http_proxy_password" do
it "should return a proxy password if set in environment" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
expect(subject.http_proxy_password).to eq(password)
end
end
it "should return a proxy password if set in config" do
Puppet.settings[:http_proxy_user] = user
Puppet.settings[:http_proxy_password] = password
expect(subject.http_proxy_password).to eq(password)
end
it "should use environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
Puppet.settings[:http_proxy_password] = 'clownpants'
expect(subject.http_proxy_password).to eq(password)
end
end
end
describe ".no_proxy" do
no_proxy = '127.0.0.1, localhost'
it "should use a no_proxy list if set in environment" do
Puppet::Util.withenv('NO_PROXY' => no_proxy) do
expect(subject.no_proxy).to eq(no_proxy)
end
end
it "should use a no_proxy list if set in config" do
Puppet.settings[:no_proxy] = no_proxy
expect(subject.no_proxy).to eq(no_proxy)
end
it "should use environment variable before puppet settings" do
no_proxy_puppet_setting = '10.0.0.1, localhost'
Puppet::Util.withenv('NO_PROXY' => no_proxy) do
Puppet.settings[:no_proxy] = no_proxy_puppet_setting
expect(subject.no_proxy).to eq(no_proxy)
end
end
end
describe ".no_proxy?" do
no_proxy = '127.0.0.1, localhost, mydomain.com, *.otherdomain.com, oddport.com:8080, *.otheroddport.com:8080, .anotherdomain.com, .anotheroddport.com:8080'
it "should return false if no_proxy does not exist in environment or puppet settings" do
Puppet::Util.withenv('no_proxy' => nil) do
dest = 'https://puppetlabs.com'
expect(subject.no_proxy?(dest)).to be false
end
end
it "should return false if the dest does not match any element in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'https://puppetlabs.com'
expect(subject.no_proxy?(dest)).to be false
end
end
it "should return true if the dest as an IP does match any element in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://127.0.0.1'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should return true if the dest as single word does match any element in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://localhost'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should return true if the dest as standard domain word does match any element in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://mydomain.com'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should return true if the dest as standard domain with port does match any element in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://oddport.com:8080'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should return false if the dest is standard domain not matching port" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://oddport.com'
expect(subject.no_proxy?(dest)).to be false
end
end
it "should return true if the dest does match any wildcarded element in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://sub.otherdomain.com'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should return true if the dest does match any wildcarded element with port in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://sub.otheroddport.com:8080'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should return true if the dest does match any domain level (no wildcard) element in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://sub.anotherdomain.com'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should return true if the dest does match any domain level (no wildcard) element with port in the no_proxy list" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = 'http://sub.anotheroddport.com:8080'
expect(subject.no_proxy?(dest)).to be true
end
end
it "should work if passed a URI object" do
Puppet::Util.withenv('no_proxy' => no_proxy) do
dest = URI.parse('http://sub.otheroddport.com:8080')
expect(subject.no_proxy?(dest)).to be true
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/session_spec.rb | spec/unit/http/session_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Session do
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:uri) { URI.parse('https://www.example.com') }
let(:good_service) {
double('good', url: uri, connect: nil)
}
let(:bad_service) {
create_bad_service
}
def create_bad_service(failure_message = 'whoops')
service = double('bad', url: uri)
allow(service).to receive(:connect).and_raise(Puppet::HTTP::ConnectionError, failure_message)
service
end
class DummyResolver < Puppet::HTTP::Resolver
attr_reader :count
def initialize(service)
@service = service
@count = 0
end
def resolve(session, name, ssl_context: nil, canceled_handler: nil)
@count += 1
return @service if check_connection?(session, @service, ssl_context: ssl_context)
end
end
context 'when routing' do
it 'returns the first resolved service' do
resolvers = [DummyResolver.new(bad_service), DummyResolver.new(good_service)]
session = described_class.new(client, resolvers)
resolved = session.route_to(:ca)
expect(resolved).to eq(good_service)
end
it 'only resolves once per session' do
resolver = DummyResolver.new(good_service)
session = described_class.new(client, [resolver])
session.route_to(:ca)
session.route_to(:ca)
expect(resolver.count).to eq(1)
end
it 'raises if there are no more routes' do
resolvers = [DummyResolver.new(bad_service)]
session = described_class.new(client, resolvers)
expect {
session.route_to(:ca)
}.to raise_error(Puppet::HTTP::RouteError, 'No more routes to ca')
end
it 'logs all routing failures as errors when there are no more routes' do
resolvers = [DummyResolver.new(create_bad_service('whoops1')), DummyResolver.new(create_bad_service('whoops2'))]
session = described_class.new(client, resolvers)
expect {
session.route_to(:ca)
}.to raise_error(Puppet::HTTP::RouteError, 'No more routes to ca')
expect(@logs).to include(an_object_having_attributes(level: :err, message: "Connection to #{uri} failed, trying next route: whoops1"),
an_object_having_attributes(level: :err, message: "Connection to #{uri} failed, trying next route: whoops2"))
end
it 'accepts an ssl context to use when connecting' do
alt_context = Puppet::SSL::SSLContext.new
expect(good_service).to receive(:connect).with(ssl_context: alt_context)
resolvers = [DummyResolver.new(good_service)]
session = described_class.new(client, resolvers)
session.route_to(:ca, ssl_context: alt_context)
end
it 'raises for unknown service names' do
expect {
session = described_class.new(client, [])
session.route_to(:westbound)
}.to raise_error(ArgumentError, "Unknown service westbound")
end
it 'routes to the service when given a puppet URL with an explicit host' do
allow_any_instance_of(Net::HTTP).to receive(:start)
session = described_class.new(client, [])
url = URI("puppet://example.com:8140/:modules/:module/path/to/file")
service = session.route_to(:fileserver, url: url)
expect(service.url.to_s).to eq("https://example.com:8140/puppet/v3")
end
it 'raises a connection error if we cannot connect' do
allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Net::OpenTimeout)
session = described_class.new(client, [])
url = URI('puppet://example.com:8140/:modules/:module/path/to/file')
expect {
session.route_to(:fileserver, url: url)
}.to raise_error(Puppet::HTTP::ConnectionError,
%r{Request to https://example.com:8140/puppet/v3 timed out connect operation after .* seconds})
end
it 'resolves the route when given a generic puppet:/// URL' do
resolvers = [DummyResolver.new(good_service)]
session = described_class.new(client, resolvers)
url = URI('puppet:///:modules/:module/path/to/file')
service = session.route_to(:fileserver, url: url)
expect(service.url).to eq(good_service.url)
end
end
context 'when resolving using multiple resolvers' do
let(:session) { client.create_session }
it "prefers SRV records" do
Puppet[:use_srv_records] = true
Puppet[:server_list] = 'foo.example.com,bar.example.com,baz.example.com'
Puppet[:ca_server] = 'caserver.example.com'
allow_any_instance_of(Puppet::HTTP::DNS).to receive(:each_srv_record).and_yield('mars.example.srv', 8140)
service = session.route_to(:ca)
expect(service.url).to eq(URI("https://mars.example.srv:8140/puppet-ca/v1"))
end
it "next prefers :ca_server when explicitly set" do
Puppet[:use_srv_records] = true
Puppet[:server_list] = 'foo.example.com,bar.example.com,baz.example.com'
Puppet[:ca_server] = 'caserver.example.com'
service = session.route_to(:ca)
expect(service.url).to eq(URI("https://caserver.example.com:8140/puppet-ca/v1"))
end
it "next prefers the first successful connection from server_list" do
Puppet[:use_srv_records] = true
Puppet[:server_list] = 'foo.example.com,bar.example.com,baz.example.com'
allow_any_instance_of(Puppet::HTTP::DNS).to receive(:each_srv_record)
stub_request(:get, "https://foo.example.com:8140/status/v1/simple/server").to_return(status: 500)
stub_request(:get, "https://bar.example.com:8140/status/v1/simple/server").to_return(status: 200)
service = session.route_to(:ca)
expect(service.url).to eq(URI("https://bar.example.com:8140/puppet-ca/v1"))
end
it "does not fallback from server_list to the settings resolver when server_list is exhausted" do
Puppet[:server_list] = 'foo.example.com'
expect_any_instance_of(Puppet::HTTP::Resolver::Settings).to receive(:resolve).never
stub_request(:get, "https://foo.example.com:8140/status/v1/simple/server").to_return(status: 500)
expect {
session.route_to(:ca)
}.to raise_error(Puppet::HTTP::RouteError, "No more routes to ca")
end
it "raises when there are no more routes" do
allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Errno::EHOSTUNREACH)
session = client.create_session
expect {
session.route_to(:ca)
}.to raise_error(Puppet::HTTP::RouteError, 'No more routes to ca')
end
Puppet::HTTP::Service::SERVICE_NAMES.each do |name|
it "resolves #{name} using server_list" do
Puppet[:server_list] = 'apple.example.com'
req = stub_request(:get, "https://apple.example.com:8140/status/v1/simple/server").to_return(status: 200)
session.route_to(name)
expect(req).to have_been_requested
end
end
it 'does not use server_list to resolve the ca service when ca_server is explicitly set' do
Puppet[:ca_server] = 'banana.example.com'
expect(session.route_to(:ca).url.to_s).to eq("https://banana.example.com:8140/puppet-ca/v1")
end
it 'does not use server_list to resolve the report service when the report_server is explicitly set' do
Puppet[:report_server] = 'cherry.example.com'
expect(session.route_to(:report).url.to_s).to eq("https://cherry.example.com:8140/puppet/v3")
end
it 'resolves once for all services in a session' do
Puppet[:server_list] = 'apple.example.com'
req = stub_request(:get, "https://apple.example.com:8140/status/v1/simple/server").to_return(status: 200)
Puppet::HTTP::Service::SERVICE_NAMES.each do |name|
session.route_to(name)
end
expect(req).to have_been_requested
end
it 'resolves server_list for each new session' do
Puppet[:server_list] = 'apple.example.com'
req = stub_request(:get, "https://apple.example.com:8140/status/v1/simple/server").to_return(status: 200)
client.create_session.route_to(:puppet)
client.create_session.route_to(:puppet)
expect(req).to have_been_requested.twice
end
end
context 'when retrieving capabilities' do
let(:response) { Puppet::HTTP::Response.new(uri, 200, 'OK') }
let(:session) do
resolver = DummyResolver.new(good_service)
described_class.new(client, [resolver])
end
it 'raises for unknown service names' do
expect {
session = described_class.new(client, [])
session.supports?(:westbound, 'a capability')
}.to raise_error(ArgumentError, "Unknown service westbound")
end
context 'locales' do
it 'does not support locales if the cached service has not been resolved' do
session = described_class.new(client, [])
expect(session).to_not be_supports(:puppet, 'locales')
end
it "supports locales if the cached service's version is 5.3.4 or greater" do
allow(response).to receive(:[]).with('X-Puppet-Version').and_return('5.3.4')
session.route_to(:puppet)
session.process_response(response)
expect(session).to be_supports(:puppet, 'locales')
end
it "does not support locales if the cached service's version is 5.3.3" do
allow(response).to receive(:[]).with('X-Puppet-Version').and_return('5.3.3')
session.route_to(:puppet)
session.process_response(response)
expect(session).to_not be_supports(:puppet, 'locales')
end
it "does not support locales if the cached service's version is missing" do
allow(response).to receive(:[]).with('X-Puppet-Version').and_return(nil)
session.route_to(:puppet)
session.process_response(response)
expect(session).to_not be_supports(:puppet, 'locales')
end
end
context 'json' do
it 'does not support json if the cached service has not been resolved' do
session = described_class.new(client, [])
expect(session).to_not be_supports(:puppet, 'json')
end
it "supports json if the cached service's version is 5 or greater" do
allow(response).to receive(:[]).with('X-Puppet-Version').and_return('5.5.12')
session.route_to(:puppet)
session.process_response(response)
expect(session).to be_supports(:puppet, 'json')
end
it "does not support json if the cached service's version is less than 5.0" do
allow(response).to receive(:[]).with('X-Puppet-Version').and_return('4.10.1')
session.route_to(:puppet)
session.process_response(response)
expect(session).to_not be_supports(:puppet, 'json')
end
it "supports json if the cached service's version is missing" do
allow(response).to receive(:[]).with('X-Puppet-Version').and_return(nil)
session.route_to(:puppet)
session.process_response(response)
expect(session).to be_supports(:puppet, 'json')
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/factory_spec.rb | spec/unit/http/factory_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Factory do
before(:all) do
ENV['http_proxy'] = nil
ENV['HTTP_PROXY'] = nil
end
let(:site) { Puppet::HTTP::Site.new('https', 'www.example.com', 443) }
def create_connection(site)
factory = described_class.new
factory.create_connection(site)
end
it 'creates a connection for the site' do
conn = create_connection(site)
expect(conn.use_ssl?).to be_truthy
expect(conn.address).to eq(site.host)
expect(conn.port).to eq(site.port)
end
it 'creates a connection that has not yet been started' do
conn = create_connection(site)
expect(conn).to_not be_started
end
it 'creates a connection supporting at least HTTP 1.1' do
conn = create_connection(site)
expect(conn.class.version_1_1? || conn.class.version_1_2?).to be_truthy
end
context "proxy settings" do
let(:proxy_host) { 'myhost' }
let(:proxy_port) { 432 }
let(:proxy_user) { 'mo' }
let(:proxy_pass) { 'password' }
it "should not set a proxy if the http_proxy_host setting is 'none'" do
Puppet[:http_proxy_host] = 'none'
conn = create_connection(site)
expect(conn.proxy_address).to be_nil
end
it 'should not set a proxy if a no_proxy env var matches the destination' do
Puppet[:http_proxy_host] = proxy_host
Puppet[:http_proxy_port] = proxy_port
Puppet::Util.withenv('NO_PROXY' => site.host) do
conn = create_connection(site)
expect(conn.proxy_address).to be_nil
expect(conn.proxy_port).to be_nil
end
end
it 'should not set a proxy if the no_proxy setting matches the destination' do
Puppet[:http_proxy_host] = proxy_host
Puppet[:http_proxy_port] = proxy_port
Puppet[:no_proxy] = site.host
conn = create_connection(site)
expect(conn.proxy_address).to be_nil
expect(conn.proxy_port).to be_nil
end
it 'sets proxy_address' do
Puppet[:http_proxy_host] = proxy_host
conn = create_connection(site)
expect(conn.proxy_address).to eq(proxy_host)
end
it 'sets proxy address and port' do
Puppet[:http_proxy_host] = proxy_host
Puppet[:http_proxy_port] = proxy_port
conn = create_connection(site)
expect(conn.proxy_port).to eq(proxy_port)
end
it 'sets proxy user and password' do
Puppet[:http_proxy_host] = proxy_host
Puppet[:http_proxy_port] = proxy_port
Puppet[:http_proxy_user] = proxy_user
Puppet[:http_proxy_password] = proxy_pass
conn = create_connection(site)
expect(conn.proxy_user).to eq(proxy_user)
expect(conn.proxy_pass).to eq(proxy_pass)
end
end
context 'socket timeouts' do
it 'sets open timeout' do
Puppet[:http_connect_timeout] = "10s"
conn = create_connection(site)
expect(conn.open_timeout).to eq(10)
end
it 'sets read timeout' do
Puppet[:http_read_timeout] = "2m"
conn = create_connection(site)
expect(conn.read_timeout).to eq(120)
end
end
it "disables ruby's http_keepalive_timeout" do
conn = create_connection(site)
expect(conn.keep_alive_timeout).to eq(2147483647)
end
it "disables ruby's max retry" do
conn = create_connection(site)
expect(conn.max_retries).to eq(0)
end
context 'source address' do
it 'defaults to system-defined' do
conn = create_connection(site)
expect(conn.local_host).to be(nil)
end
it 'sets the local_host address' do
Puppet[:sourceaddress] = "127.0.0.1"
conn = create_connection(site)
expect(conn.local_host).to eq('127.0.0.1')
end
end
context 'tls' do
it "sets the minimum version to TLS 1.0" do
conn = create_connection(site)
expect(conn.min_version).to eq(OpenSSL::SSL::TLS1_VERSION)
end
it "defaults to ciphersuites providing 128 bits of security or greater" do
conn = create_connection(site)
expect(conn.ciphers).to eq("ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256")
end
it "can be restricted to TLSv1.3 ciphers" do
tls13_ciphers = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256"
Puppet[:ciphers] = tls13_ciphers
conn = create_connection(site)
expect(conn.ciphers).to eq(tls13_ciphers)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/service_spec.rb | spec/unit/http/service_spec.rb | require 'spec_helper'
require 'puppet_spec/network'
require 'puppet/http'
require 'puppet/file_serving'
require 'puppet/file_serving/content'
require 'puppet/file_serving/metadata'
describe Puppet::HTTP::Service do
include PuppetSpec::Network
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:session) { Puppet::HTTP::Session.new(client, []) }
let(:url) { URI.parse('https://www.example.com') }
let(:service) { described_class.new(client, session, url) }
class TestService < Puppet::HTTP::Service
def get_test(ssl_context)
@client.get(
url,
headers: add_puppet_headers({'Default-Header' => 'default-value'}),
options: {ssl_context: ssl_context}
)
end
def mime_types(model)
get_mime_types(model)
end
end
context 'when modifying headers for an http request' do
let(:service) { TestService.new(client, session, url) }
it 'adds custom user-specified headers' do
stub_request(:get, "https://www.example.com/").
with( headers: { 'Default-Header'=>'default-value', 'Header2'=>'newvalue' })
Puppet[:http_extra_headers] = 'header2:newvalue'
service.get_test(ssl_context)
end
it 'adds X-Puppet-Profiling header if set' do
stub_request(:get, "https://www.example.com/").
with( headers: { 'Default-Header'=>'default-value', 'X-Puppet-Profiling'=>'true' })
Puppet[:profile] = true
service.get_test(ssl_context)
end
it 'ignores a custom header does not have a value' do
stub_request(:get, "https://www.example.com/").with do |request|
expect(request.headers).to include({'Default-Header' => 'default-value'})
expect(request.headers).to_not include('header-with-no-value')
end
Puppet[:http_extra_headers] = 'header-with-no-value:'
service.get_test(ssl_context)
end
it 'ignores a custom header that already exists (case insensitive) in the header hash' do
stub_request(:get, "https://www.example.com/").
with( headers: { 'Default-Header'=>'default-value' })
Puppet[:http_extra_headers] = 'default-header:wrongvalue'
service.get_test(ssl_context)
end
end
it "returns a URI containing the base URL and path" do
expect(service.with_base_url('/puppet/v3')).to eq(URI.parse("https://www.example.com/puppet/v3"))
end
it "doesn't modify frozen the base URL" do
service = described_class.new(client, session, url.freeze)
service.with_base_url('/puppet/v3')
end
it "percent encodes paths before appending them to the path" do
expect(service.with_base_url('/path/with/a space')).to eq(URI.parse("https://www.example.com/path/with/a%20space"))
end
it "connects to the base URL with a nil ssl context" do
expect(client).to receive(:connect).with(url, options: {ssl_context: nil})
service.connect
end
it "accepts an optional ssl_context" do
other_ctx = Puppet::SSL::SSLContext.new
expect(client).to receive(:connect).with(url, options: {ssl_context: other_ctx})
service.connect(ssl_context: other_ctx)
end
it 'raises for unknown service names' do
expect {
described_class.create_service(client, session, :westbound)
}.to raise_error(ArgumentError, "Unknown service westbound")
end
[:ca].each do |name|
it "returns true for #{name}" do
expect(described_class.valid_name?(name)).to eq(true)
end
end
it "returns false when the service name is a string" do
expect(described_class.valid_name?("ca")).to eq(false)
end
it "returns false for unknown service names" do
expect(described_class.valid_name?(:westbound)).to eq(false)
end
it 'returns different mime types for different models' do
mimes = acceptable_content_types
service = TestService.new(client, session, url)
[
Puppet::Node,
Puppet::Node::Facts,
Puppet::Transaction::Report,
Puppet::FileServing::Metadata,
].each do |model|
expect(service.mime_types(model)).to eq(mimes)
end
# These are special
expect(service.mime_types(Puppet::FileServing::Content)).to eq(%w[application/octet-stream])
expect(service.mime_types(Puppet::Resource::Catalog)).to eq(acceptable_catalog_content_types)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/dns_spec.rb | spec/unit/http/dns_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::DNS do
before do
@dns_mock_object = double('dns')
allow(Resolv::DNS).to receive(:new).and_return(@dns_mock_object)
@rr_type = Resolv::DNS::Resource::IN::SRV
@test_srv_domain = "domain.com"
@test_a_hostname = "puppet.domain.com"
@test_port = 1000
# The records we should use.
@test_records = [
# priority, weight, port, target
Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(0, 80, 8140, "puppet2.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(1, 1, 8140, "puppet3.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(4, 1, 8140, "puppet4.domain.com")
]
@test_records.each do |rec|
# Resources do not expose public API for setting the TTL
rec.instance_variable_set(:@ttl, 3600)
end
end
let(:resolver) { described_class.new }
describe 'when the domain is not known' do
before :each do
allow(@dns_mock_object).to receive(:getresources).and_return(@test_records)
end
describe 'because domain is nil' do
it 'does not yield' do
resolver.each_srv_record(nil) do |_,_,_|
raise Exception.new("nil domain caused SRV lookup")
end
end
end
describe 'because domain is an empty string' do
it 'does not yield' do
resolver.each_srv_record('') do |_,_,_|
raise Exception.new("nil domain caused SRV lookup")
end
end
end
end
describe "when resolving a host without SRV records" do
it "should not yield anything" do
# No records returned for a DNS entry without any SRV records
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet._tcp.#{@test_a_hostname}",
@rr_type
).and_return([])
resolver.each_srv_record(@test_a_hostname) do |hostname, port, remaining|
raise Exception.new("host with no records passed block")
end
end
end
describe "when resolving a host with SRV records" do
it "should iterate through records in priority order" do
# The order of the records that should be returned,
# an array means unordered (for weight)
order = {
0 => ["puppet1.domain.com", "puppet2.domain.com"],
1 => ["puppet3.domain.com"],
2 => ["puppet4.domain.com"]
}
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).and_return(@test_records)
resolver.each_srv_record(@test_srv_domain) do |hostname, port|
expected_priority = order.keys.min
expect(order[expected_priority]).to include(hostname)
expect(port).not_to be(@test_port)
# Remove the host from our expected hosts
order[expected_priority].delete hostname
# Remove this priority level if we're done with it
order.delete expected_priority if order[expected_priority] == []
end
end
it "should fall back to the :puppet service if no records are found for a more specific service" do
# The order of the records that should be returned,
# an array means unordered (for weight)
order = {
0 => ["puppet1.domain.com", "puppet2.domain.com"],
1 => ["puppet3.domain.com"],
2 => ["puppet4.domain.com"]
}
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet-report._tcp.#{@test_srv_domain}",
@rr_type
).and_return([])
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).and_return(@test_records)
resolver.each_srv_record(@test_srv_domain, :report) do |hostname, port|
expected_priority = order.keys.min
expect(order[expected_priority]).to include(hostname)
expect(port).not_to be(@test_port)
# Remove the host from our expected hosts
order[expected_priority].delete hostname
# Remove this priority level if we're done with it
order.delete expected_priority if order[expected_priority] == []
end
end
it "should use SRV records from the specific service if they exist" do
# The order of the records that should be returned,
# an array means unordered (for weight)
order = {
0 => ["puppet1.domain.com", "puppet2.domain.com"],
1 => ["puppet3.domain.com"],
2 => ["puppet4.domain.com"]
}
bad_records = [
# priority, weight, port, hostname
Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.bad.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(0, 80, 8140, "puppet2.bad.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(1, 1, 8140, "puppet3.bad.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(4, 1, 8140, "puppet4.bad.domain.com")
]
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet-report._tcp.#{@test_srv_domain}",
@rr_type
).and_return(@test_records)
allow(@dns_mock_object).to receive(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).and_return(bad_records)
resolver.each_srv_record(@test_srv_domain, :report) do |hostname, port|
expected_priority = order.keys.min
expect(order[expected_priority]).to include(hostname)
expect(port).not_to be(@test_port)
# Remove the host from our expected hosts
order[expected_priority].delete hostname
# Remove this priority level if we're done with it
order.delete expected_priority if order[expected_priority] == []
end
end
end
describe "when finding weighted servers" do
it "should return nil when no records were found" do
expect(resolver.find_weighted_server([])).to eq(nil)
end
it "should return the first record when one record is passed" do
result = resolver.find_weighted_server([@test_records.first])
expect(result).to eq(@test_records.first)
end
{
"all have weights" => [1, 3, 2, 4],
"some have weights" => [2, 0, 1, 0],
"none have weights" => [0, 0, 0, 0],
}.each do |name, weights|
it "should return correct results when #{name}" do
records = []
count = 0
weights.each do |w|
count += 1
# priority, weight, port, server
records << Resolv::DNS::Resource::IN::SRV.new(0, w, 1, count.to_s)
end
seen = Hash.new(0)
total_weight = records.inject(0) do |sum, record|
sum + resolver.weight(record)
end
total_weight.times do |n|
expect(Kernel).to receive(:rand).once.with(total_weight).and_return(n)
server = resolver.find_weighted_server(records)
seen[server] += 1
end
expect(seen.length).to eq(records.length)
records.each do |record|
expect(seen[record]).to eq(resolver.weight(record))
end
end
end
end
describe "caching records" do
it "should query DNS when no cache entry exists, then retrieve the cached value" do
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).and_return(@test_records).once
fetched_servers = []
resolver.each_srv_record(@test_srv_domain) do |server, port|
fetched_servers << server
end
cached_servers = []
expect(resolver).to receive(:expired?).and_return(false)
resolver.each_srv_record(@test_srv_domain) do |server, port|
cached_servers << server
end
expect(fetched_servers).to match_array(cached_servers)
end
context "TTLs" do
before(:each) do
# The TTL of an SRV record cannot be set via any public API
ttl_record1 = Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.domain.com")
ttl_record1.instance_variable_set(:@ttl, 10)
ttl_record2 = Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet2.domain.com")
ttl_record2.instance_variable_set(:@ttl, 20)
records = [ttl_record1, ttl_record2]
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).and_return(records)
end
it "should save the shortest TTL among records for a service" do
resolver.each_srv_record(@test_srv_domain) { |server, port| }
expect(resolver.ttl(:puppet)).to eq(10)
end
it "should fetch records again if the TTL has expired" do
# Fetch from DNS
resolver.each_srv_record(@test_srv_domain) do |server, port|
expect(server).to match(/puppet.*domain\.com/)
end
expect(resolver).to receive(:expired?).with(:puppet).and_return(false)
# Load from cache
resolver.each_srv_record(@test_srv_domain) do |server, port|
expect(server).to match(/puppet.*domain\.com/)
end
new_record = Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "new.domain.com")
new_record.instance_variable_set(:@ttl, 10)
expect(@dns_mock_object).to receive(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).and_return([new_record])
expect(resolver).to receive(:expired?).with(:puppet).and_return(true)
# Refresh from DNS
resolver.each_srv_record(@test_srv_domain) do |server, port|
expect(server).to eq("new.domain.com")
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/resolver_spec.rb | spec/unit/http/resolver_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Resolver do
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:session) { client.create_session }
let(:uri) { URI.parse('https://www.example.com') }
context 'when resolving using settings' do
let(:subject) { Puppet::HTTP::Resolver::Settings.new(client) }
it 'returns a service based on the current ca_server and ca_port settings' do
Puppet[:ca_server] = 'ca.example.com'
Puppet[:ca_port] = 8141
service = subject.resolve(session, :ca)
expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca)
expect(service.url.to_s).to eq("https://ca.example.com:8141/puppet-ca/v1")
end
end
context 'when resolving using server_list' do
let(:subject) { Puppet::HTTP::Resolver::ServerList.new(client, server_list_setting: Puppet.settings.setting(:server_list), default_port: 8142, services: Puppet::HTTP::Service::SERVICE_NAMES) }
before :each do
Puppet[:server_list] = 'ca.example.com:8141,apple.example.com'
end
it 'returns a service based on the current server_list setting' do
stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 200)
service = subject.resolve(session, :ca)
expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca)
expect(service.url.to_s).to eq("https://ca.example.com:8141/puppet-ca/v1")
end
it 'returns a service based on the current server_list setting if the server returns any success codes' do
stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 202)
service = subject.resolve(session, :ca)
expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca)
expect(service.url.to_s).to eq("https://ca.example.com:8141/puppet-ca/v1")
end
it 'includes extra http headers' do
Puppet[:http_extra_headers] = 'region:us-west'
stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server")
.with(headers: {'Region' => 'us-west'})
subject.resolve(session, :ca)
end
it 'uses the provided ssl context during resolution' do
stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 200)
other_ctx = Puppet::SSL::SSLContext.new
expect(client).to receive(:connect).with(URI("https://ca.example.com:8141/status/v1/simple/server"), options: {ssl_context: other_ctx}).and_call_original
subject.resolve(session, :ca, ssl_context: other_ctx)
end
it 'logs unsuccessful HTTP 500 responses' do
stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: [500, 'Internal Server Error'])
stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 200)
subject.resolve(session, :ca)
expect(@logs.map(&:message)).to include(/Puppet server ca.example.com:8141 is unavailable: 500 Internal Server Error/)
end
it 'cancels resolution if no servers in server_list are accessible' do
stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 503)
stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 503)
canceled = false
canceled_handler = lambda { |cancel| canceled = cancel }
expect(subject.resolve(session, :ca, canceled_handler: canceled_handler)).to eq(nil)
expect(canceled).to eq(true)
end
it 'cycles through server_list until a valid server is found' do
stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 503)
stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 200)
service = subject.resolve(session, :ca)
expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca)
expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet-ca/v1")
end
it 'resolves once per session' do
failed = stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 503)
passed = stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 200)
service = subject.resolve(session, :puppet)
expect(service).to be_a(Puppet::HTTP::Service::Compiler)
expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet/v3")
service = subject.resolve(session, :fileserver)
expect(service).to be_a(Puppet::HTTP::Service::FileServer)
expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet/v3")
service = subject.resolve(session, :report)
expect(service).to be_a(Puppet::HTTP::Service::Report)
expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet/v3")
expect(failed).to have_been_requested
expect(passed).to have_been_requested
end
end
context 'when resolving using SRV' do
let(:dns) { double('dns') }
let(:subject) { Puppet::HTTP::Resolver::SRV.new(client, domain: 'example.com', dns: dns) }
def stub_srv(host, port)
srv = Resolv::DNS::Resource::IN::SRV.new(0, 0, port, host)
srv.instance_variable_set :@ttl, 3600
allow(dns).to receive(:getresources).with("_x-puppet-ca._tcp.example.com", Resolv::DNS::Resource::IN::SRV).and_return([srv])
end
it 'returns a service based on an SRV record' do
stub_srv('ca1.example.com', 8142)
service = subject.resolve(session, :ca)
expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca)
expect(service.url.to_s).to eq("https://ca1.example.com:8142/puppet-ca/v1")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/pool_spec.rb | spec/unit/http/pool_spec.rb | require 'spec_helper'
require 'openssl'
require 'puppet/network/http'
require 'puppet/network/http_pool'
describe Puppet::HTTP::Pool do
let(:site) do
Puppet::HTTP::Site.new('https', 'rubygems.org', 443)
end
let(:different_site) do
Puppet::HTTP::Site.new('https', 'github.com', 443)
end
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:verifier) do
v = Puppet::SSL::Verifier.new(site.host, ssl_context)
allow(v).to receive(:setup_connection)
v
end
def create_pool
Puppet::HTTP::Pool.new(15)
end
def create_pool_with_connections(site, *connections)
pool = Puppet::HTTP::Pool.new(15)
connections.each do |conn|
pool.release(site, verifier, conn)
end
pool
end
def create_pool_with_http_connections(site, *connections)
pool = Puppet::HTTP::Pool.new(15)
connections.each do |conn|
pool.release(site, nil, conn)
end
pool
end
def create_pool_with_expired_connections(site, *connections)
# setting keepalive timeout to -1 ensures any newly added
# connections have already expired
pool = Puppet::HTTP::Pool.new(-1)
connections.each do |conn|
pool.release(site, verifier, conn)
end
pool
end
def create_connection(site)
double(site.addr, :started? => false, :start => nil, :finish => nil, :use_ssl? => true, :verify_mode => OpenSSL::SSL::VERIFY_PEER)
end
def create_http_connection(site)
double(site.addr, :started? => false, :start => nil, :finish => nil, :use_ssl? => false)
end
context 'when yielding a connection' do
it 'yields a connection' do
conn = create_connection(site)
pool = create_pool_with_connections(site, conn)
expect { |b|
pool.with_connection(site, verifier, &b)
}.to yield_with_args(conn)
end
it 'returns the connection to the pool' do
conn = create_connection(site)
expect(conn).to receive(:started?).and_return(true)
pool = create_pool
pool.release(site, verifier, conn)
pool.with_connection(site, verifier) { |c| }
expect(pool.pool[site].first.connection).to eq(conn)
end
it 'can yield multiple connections to the same site' do
lru_conn = create_connection(site)
mru_conn = create_connection(site)
pool = create_pool_with_connections(site, lru_conn, mru_conn)
pool.with_connection(site, verifier) do |a|
expect(a).to eq(mru_conn)
pool.with_connection(site, verifier) do |b|
expect(b).to eq(lru_conn)
end
end
end
it 'propagates exceptions' do
conn = create_connection(site)
pool = create_pool
pool.release(site, verifier, conn)
expect {
pool.with_connection(site, verifier) do |c|
raise IOError, 'connection reset'
end
}.to raise_error(IOError, 'connection reset')
end
it 'does not re-cache connections when an error occurs' do
# we're not distinguishing between network errors that would
# suggest we close the socket, and other errors
conn = create_connection(site)
pool = create_pool
pool.release(site, verifier, conn)
expect(pool).not_to receive(:release).with(site, verifier, conn)
pool.with_connection(site, verifier) do |c|
raise IOError, 'connection reset'
end rescue nil
end
it 'sets keepalive bit on network socket' do
pool = create_pool
s = Socket.new(Socket::PF_INET, Socket::SOCK_STREAM)
pool.setsockopts(Net::BufferedIO.new(s))
# On windows, Socket.getsockopt() doesn't return exactly the same data
# as an equivalent Socket::Option.new() statement, so we strip off the
# unrelevant bits only on this platform.
#
# To make sure we're not voiding the test case by doing this, we check
# both with and without the keepalive bit set.
#
# This workaround can be removed once all the ruby versions we care about
# have the patch from https://bugs.ruby-lang.org/issues/11958 applied.
#
if Puppet::Util::Platform.windows?
keepalive = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, true).data[0]
nokeepalive = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, false).data[0]
expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).data).to eq(keepalive)
expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).data).to_not eq(nokeepalive)
else
expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).bool).to eq(true)
end
end
context 'when releasing connections' do
it 'releases HTTP connections' do
conn = create_connection(site)
expect(conn).to receive(:use_ssl?).and_return(false)
expect(conn).to receive(:started?).and_return(true)
pool = create_pool_with_connections(site, conn)
expect(pool).to receive(:release).with(site, verifier, conn)
pool.with_connection(site, verifier) {|c| }
end
it 'releases secure HTTPS connections' do
conn = create_connection(site)
expect(conn).to receive(:use_ssl?).and_return(true)
expect(conn).to receive(:verify_mode).and_return(OpenSSL::SSL::VERIFY_PEER)
expect(conn).to receive(:started?).and_return(true)
pool = create_pool_with_connections(site, conn)
expect(pool).to receive(:release).with(site, verifier, conn)
pool.with_connection(site, verifier) {|c| }
end
it 'closes insecure HTTPS connections' do
conn = create_connection(site)
expect(conn).to receive(:use_ssl?).and_return(true)
expect(conn).to receive(:verify_mode).and_return(OpenSSL::SSL::VERIFY_NONE)
pool = create_pool_with_connections(site, conn)
expect(pool).not_to receive(:release).with(site, verifier, conn)
pool.with_connection(site, verifier) {|c| }
end
it "doesn't add a closed connection back to the pool" do
http = Net::HTTP.new(site.addr)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.start
pool = create_pool_with_connections(site, http)
pool.with_connection(site, verifier) {|c| c.finish}
expect(pool.pool[site]).to be_nil
end
end
end
context 'when borrowing' do
it 'returns a new connection if the pool is empty' do
conn = create_connection(site)
pool = create_pool
expect(pool.factory).to receive(:create_connection).with(site).and_return(conn)
expect(pool.borrow(site, verifier)).to eq(conn)
end
it 'returns a matching connection' do
conn = create_connection(site)
pool = create_pool_with_connections(site, conn)
expect(pool.factory).not_to receive(:create_connection)
expect(pool.borrow(site, verifier)).to eq(conn)
end
it 'returns a new connection if there are no matching sites' do
different_conn = create_connection(different_site)
pool = create_pool_with_connections(different_site, different_conn)
conn = create_connection(site)
expect(pool.factory).to receive(:create_connection).with(site).and_return(conn)
expect(pool.borrow(site, verifier)).to eq(conn)
end
it 'returns a new HTTP connection if the cached connection is HTTPS' do
https_site = Puppet::HTTP::Site.new('https', 'www.example.com', 443)
old_conn = create_connection(https_site)
pool = create_pool_with_connections(https_site, old_conn)
http_site = Puppet::HTTP::Site.new('http', 'www.example.com', 443)
new_conn = create_http_connection(http_site)
allow(pool.factory).to receive(:create_connection).with(http_site).and_return(new_conn)
expect(pool.borrow(http_site, nil)).to eq(new_conn)
end
it 'returns a new HTTPS connection if the cached connection is HTTP' do
http_site = Puppet::HTTP::Site.new('http', 'www.example.com', 443)
old_conn = create_http_connection(http_site)
pool = create_pool_with_http_connections(http_site, old_conn)
https_site = Puppet::HTTP::Site.new('https', 'www.example.com', 443)
new_conn = create_connection(https_site)
allow(pool.factory).to receive(:create_connection).with(https_site).and_return(new_conn)
expect(pool.borrow(https_site, verifier)).to eq(new_conn)
end
it 'returns a new connection if the ssl contexts are different' do
old_conn = create_connection(site)
pool = create_pool_with_connections(site, old_conn)
new_conn = create_connection(site)
allow(pool.factory).to receive(:create_connection).with(site).and_return(new_conn)
new_verifier = Puppet::SSL::Verifier.new(site.host, Puppet::SSL::SSLContext.new)
allow(new_verifier).to receive(:setup_connection)
# 'equal' tests that it's the same object
expect(pool.borrow(site, new_verifier)).to eq(new_conn)
end
it 'returns a cached connection if the ssl contexts are the same' do
old_conn = create_connection(site)
pool = create_pool_with_connections(site, old_conn)
expect(pool.factory).not_to receive(:create_connection)
# 'equal' tests that it's the same object
new_verifier = Puppet::SSL::Verifier.new(site.host, ssl_context)
expect(pool.borrow(site, new_verifier)).to equal(old_conn)
end
it 'returns a cached connection if both connections are http' do
http_site = Puppet::HTTP::Site.new('http', 'www.example.com', 80)
old_conn = create_http_connection(http_site)
pool = create_pool_with_http_connections(http_site, old_conn)
# 'equal' tests that it's the same object
expect(pool.borrow(http_site, nil)).to equal(old_conn)
end
it 'returns started connections' do
conn = create_connection(site)
expect(conn).to receive(:start)
pool = create_pool
expect(pool.factory).to receive(:create_connection).with(site).and_return(conn)
expect(pool.borrow(site, verifier)).to eq(conn)
end
it "doesn't start a cached connection" do
conn = create_connection(site)
expect(conn).not_to receive(:start)
pool = create_pool_with_connections(site, conn)
pool.borrow(site, verifier)
end
it 'returns the most recently used connection from the pool' do
least_recently_used = create_connection(site)
most_recently_used = create_connection(site)
pool = create_pool_with_connections(site, least_recently_used, most_recently_used)
expect(pool.borrow(site, verifier)).to eq(most_recently_used)
end
it 'finishes expired connections' do
conn = create_connection(site)
allow(conn).to receive(:started?).and_return(true)
expect(conn).to receive(:finish)
pool = create_pool_with_expired_connections(site, conn)
expect(pool.factory).to receive(:create_connection).and_return(double('conn', :start => nil, :use_ssl? => true))
pool.borrow(site, verifier)
end
it 'logs an exception if it fails to close an expired connection' do
expect(Puppet).to receive(:log_exception).with(be_a(IOError), "Failed to close connection for #{site}: read timeout")
conn = create_connection(site)
expect(conn).to receive(:started?).and_return(true)
expect(conn).to receive(:finish).and_raise(IOError, 'read timeout')
pool = create_pool_with_expired_connections(site, conn)
expect(pool.factory).to receive(:create_connection).and_return(double('open_conn', :start => nil, :use_ssl? => true))
pool.borrow(site, verifier)
end
it 'deletes the session when the last connection is borrowed' do
conn = create_connection(site)
pool = create_pool_with_connections(site, conn)
pool.borrow(site, verifier)
expect(pool.pool[site]).to be_nil
end
end
context 'when releasing a connection' do
it 'adds the connection to an empty pool' do
conn = create_connection(site)
pool = create_pool
pool.release(site, verifier, conn)
expect(pool.pool[site].first.connection).to eq(conn)
end
it 'adds the connection to a pool with a connection for the same site' do
pool = create_pool
pool.release(site, verifier, create_connection(site))
pool.release(site, verifier, create_connection(site))
expect(pool.pool[site].count).to eq(2)
end
it 'adds the connection to a pool with a connection for a different site' do
pool = create_pool
pool.release(site, verifier, create_connection(site))
pool.release(different_site, verifier, create_connection(different_site))
expect(pool.pool[site].count).to eq(1)
expect(pool.pool[different_site].count).to eq(1)
end
end
context 'when closing' do
it 'clears the pool' do
pool = create_pool
pool.close
expect(pool.pool).to be_empty
end
it 'closes all cached connections' do
conn = create_connection(site)
allow(conn).to receive(:started?).and_return(true)
expect(conn).to receive(:finish)
pool = create_pool_with_connections(site, conn)
pool.close
end
it 'allows a connection to be closed multiple times safely' do
http = Net::HTTP.new(site.addr)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.start
pool = create_pool
expect(pool.close_connection(site, http)).to eq(true)
expect(pool.close_connection(site, http)).to eq(false)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/service/ca_spec.rb | spec/unit/http/service/ca_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Service::Ca do
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:session) { Puppet::HTTP::Session.new(client, []) }
let(:subject) { client.create_session.route_to(:ca) }
before :each do
Puppet[:ca_server] = 'www.example.com'
Puppet[:ca_port] = 443
end
context 'when making requests' do
let(:uri) {"https://www.example.com:443/puppet-ca/v1/certificate/ca"}
it 'includes default HTTP headers' do
stub_request(:get, uri).with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end
subject.get_certificate('ca')
end
end
context 'when routing to the CA service' do
let(:cert) { cert_fixture('ca.pem') }
let(:pem) { cert.to_pem }
it 'defaults the server and port based on settings' do
Puppet[:ca_server] = 'ca.example.com'
Puppet[:ca_port] = 8141
stub_request(:get, "https://ca.example.com:8141/puppet-ca/v1/certificate/ca").to_return(body: pem)
subject.get_certificate('ca')
end
it 'fallbacks to server and serverport' do
Puppet[:ca_server] = nil
Puppet[:ca_port] = nil
Puppet[:server] = 'ca2.example.com'
Puppet[:serverport] = 8142
stub_request(:get, "https://ca2.example.com:8142/puppet-ca/v1/certificate/ca").to_return(body: pem)
subject.get_certificate('ca')
end
end
context 'when getting certificates' do
let(:cert) { cert_fixture('ca.pem') }
let(:pem) { cert.to_pem }
let(:url) { "https://www.example.com/puppet-ca/v1/certificate/ca" }
it 'includes headers set via the :http_extra_headers and :profile settings' do
stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'})
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.get_certificate('ca')
end
it 'gets a certificate from the "certificate" endpoint' do
stub_request(:get, url).to_return(body: pem)
_, body = subject.get_certificate('ca')
expect(body).to eq(pem)
end
it 'returns the request response' do
stub_request(:get, url).to_return(body: pem)
resp, _ = subject.get_certificate('ca')
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'accepts text/plain responses' do
stub_request(:get, url).with(headers: {'Accept' => 'text/plain'})
subject.get_certificate('ca')
end
it 'raises a response error if unsuccessful' do
stub_request(:get, url).to_return(status: [404, 'Not Found'])
expect {
subject.get_certificate('ca')
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq("Not Found")
expect(err.response.code).to eq(404)
end
end
it 'raises a 304 response error if it is unmodified' do
stub_request(:get, url).to_return(status: [304, 'Not Modified'])
expect {
subject.get_certificate('ca', if_modified_since: Time.now)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq("Not Modified")
expect(err.response.code).to eq(304)
end
end
end
context 'when getting CRLs' do
let(:crl) { crl_fixture('crl.pem') }
let(:pem) { crl.to_pem }
let(:url) { "https://www.example.com/puppet-ca/v1/certificate_revocation_list/ca" }
it 'includes headers set via the :http_extra_headers and :profile settings' do
stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'})
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.get_certificate_revocation_list
end
it 'gets a CRL from "certificate_revocation_list" endpoint' do
stub_request(:get, url).to_return(body: pem)
_, body = subject.get_certificate_revocation_list
expect(body).to eq(pem)
end
it 'returns the request response' do
stub_request(:get, url).to_return(body: pem)
resp, _ = subject.get_certificate_revocation_list
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'accepts text/plain responses' do
stub_request(:get, url).with(headers: {'Accept' => 'text/plain'})
subject.get_certificate_revocation_list
end
it 'raises a response error if unsuccessful' do
stub_request(:get, url).to_return(status: [404, 'Not Found'])
expect {
subject.get_certificate_revocation_list
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq("Not Found")
expect(err.response.code).to eq(404)
end
end
it 'raises a 304 response error if it is unmodified' do
stub_request(:get, url).to_return(status: [304, 'Not Modified'])
expect {
subject.get_certificate_revocation_list(if_modified_since: Time.now)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq("Not Modified")
expect(err.response.code).to eq(304)
end
end
end
context 'when submitting a CSR' do
let(:request) { request_fixture('request.pem') }
let(:pem) { request.to_pem }
let(:url) { "https://www.example.com/puppet-ca/v1/certificate_request/infinity" }
it 'includes headers set via the :http_extra_headers and :profile settings' do
stub_request(:put, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'})
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.put_certificate_request('infinity', request)
end
it 'submits a CSR to the "certificate_request" endpoint' do
stub_request(:put, url).with(body: pem, headers: { 'Content-Type' => 'text/plain' })
subject.put_certificate_request('infinity', request)
end
it 'returns the request response' do
stub_request(:put, url).with(body: pem, headers: { 'Content-Type' => 'text/plain' })
resp = subject.put_certificate_request('infinity', request)
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises response error if unsuccessful' do
stub_request(:put, url).to_return(status: [400, 'Bad Request'])
expect {
subject.put_certificate_request('infinity', request)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Bad Request')
expect(err.response.code).to eq(400)
end
end
end
context 'when getting certificates' do
let(:cert) { cert_fixture('signed.pem') }
let(:pem) { cert.to_pem }
let(:url) { "https://www.example.com/puppet-ca/v1/certificate_renewal" }
let(:cert_context) { Puppet::SSL::SSLContext.new(client_cert: pem) }
let(:client) { Puppet::HTTP::Client.new(ssl_context: cert_context) }
let(:session) { Puppet::HTTP::Session.new(client, []) }
let(:subject) { client.create_session.route_to(:ca) }
it "gets a certificate from the 'certificate_renewal' endpoint" do
stub_request(:post, url).to_return(body: pem)
_, body = subject.post_certificate_renewal(cert_context)
expect(body).to eq(pem)
end
it 'returns the request response' do
stub_request(:post, url).to_return(body: 'pem')
resp, _ = subject.post_certificate_renewal(cert_context)
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'accepts text/plain responses' do
stub_request(:post, url).with(headers: {'Accept' => 'text/plain'})
subject.post_certificate_renewal(cert_context)
end
it 'raises an ArgumentError if the SSL context does not contain a client cert' do
stub_request(:post, url)
expect { subject.post_certificate_renewal(ssl_context) }.to raise_error(ArgumentError, 'SSL context must contain a client certificate.')
end
it 'raises response error if unsuccessful' do
stub_request(:post, url).to_return(status: [400, 'Bad Request'])
expect {
subject.post_certificate_renewal(cert_context)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Bad Request')
expect(err.response.code).to eq(400)
end
end
it 'raises a response error if unsuccessful' do
stub_request(:post, url).to_return(status: [404, 'Not Found'])
expect {
subject.post_certificate_renewal(cert_context)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq("Not Found")
expect(err.response.code).to eq(404)
end
end
it 'raises a response error if unsuccessful' do
stub_request(:post, url).to_return(status: [404, 'Forbidden'])
expect {
subject.post_certificate_renewal(cert_context)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq("Forbidden")
expect(err.response.code).to eq(404)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/service/puppetserver_spec.rb | spec/unit/http/service/puppetserver_spec.rb | require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Service::Puppetserver do
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:subject) { client.create_session.route_to(:puppetserver) }
before :each do
Puppet[:server] = 'puppetserver.example.com'
end
context 'when making requests' do
it 'includes default HTTP headers' do
stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server").with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end.to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'})
subject.get_simple_status
end
it 'includes extra headers' do
Puppet[:http_extra_headers] = 'region:us-west'
stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server")
.with(headers: {'Region' => 'us-west'})
.to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'})
subject.get_simple_status
end
end
context 'when routing to the puppetserver service' do
it 'defaults the server and port based on settings' do
Puppet[:server] = 'compiler2.example.com'
Puppet[:serverport] = 8141
stub_request(:get, "https://compiler2.example.com:8141/status/v1/simple/server")
.to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'})
subject.get_simple_status
end
end
context 'when getting puppetserver status' do
let(:url) { "https://puppetserver.example.com:8140/status/v1/simple/server" }
it 'returns the request response and status' do
stub_request(:get, url)
.to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'})
resp, status = subject.get_simple_status
expect(resp).to be_a(Puppet::HTTP::Response)
expect(status).to eq('running')
end
it 'raises a response error if unsuccessful' do
stub_request(:get, url).to_return(status: [500, 'Internal Server Error'])
expect {
subject.get_simple_status
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq("Internal Server Error")
expect(err.response.code).to eq(500)
end
end
it 'accepts an ssl context' do
stub_request(:get, url)
.to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'})
other_ctx = Puppet::SSL::SSLContext.new
expect(client).to receive(:connect).with(URI(url), options: {ssl_context: other_ctx}).and_call_original
session = client.create_session
service = Puppet::HTTP::Service.create_service(client, session, :puppetserver, 'puppetserver.example.com', 8140)
service.get_simple_status(ssl_context: other_ctx)
end
end
context 'when /status/v1/simple/server returns not found' do
it 'calls /status/v1/simple/master' do
stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server")
.to_return(status: [404, 'not found: server'])
stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/master")
.to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'})
resp, status = subject.get_simple_status
expect(resp).to be_a(Puppet::HTTP::Response)
expect(status).to eq('running')
end
it 'raises a response error if fallback is unsuccessful' do
stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server")
.to_return(status: [404, 'not found: server'])
stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/master")
.to_return(status: [404, 'not found: master'])
expect {
subject.get_simple_status
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('not found: master')
expect(err.response.code).to eq(404)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/service/report_spec.rb | spec/unit/http/service/report_spec.rb | require 'spec_helper'
require 'puppet_spec/network'
require 'puppet/http'
describe Puppet::HTTP::Service::Report do
include PuppetSpec::Network
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:subject) { client.create_session.route_to(:report) }
let(:environment) { 'testing' }
let(:report) { Puppet::Transaction::Report.new }
before :each do
Puppet[:report_server] = 'www.example.com'
Puppet[:report_port] = 443
end
context 'when making requests' do
let(:uri) {"https://www.example.com:443/puppet/v3/report/report?environment=testing"}
it 'includes default HTTP headers' do
stub_request(:put, uri).with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end
subject.put_report('report', report, environment: environment)
end
end
context 'when routing to the report service' do
it 'defaults the server and port based on settings' do
Puppet[:report_server] = 'report.example.com'
Puppet[:report_port] = 8141
stub_request(:put, "https://report.example.com:8141/puppet/v3/report/report?environment=testing")
subject.put_report('report', report, environment: environment)
end
it 'fallbacks to server and serverport' do
Puppet[:report_server] = nil
Puppet[:report_port] = nil
Puppet[:server] = 'report2.example.com'
Puppet[:serverport] = 8142
stub_request(:put, "https://report2.example.com:8142/puppet/v3/report/report?environment=testing")
subject.put_report('report', report, environment: environment)
end
end
context 'when submitting a report' do
let(:url) { "https://www.example.com/puppet/v3/report/infinity?environment=testing" }
it 'includes puppet headers set via the :http_extra_headers and :profile settings' do
stub_request(:put, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'})
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.put_report('infinity', report, environment: environment)
end
it 'submits a report to the "report" endpoint' do
stub_request(:put, url)
.with(
headers: {
'Accept'=>acceptable_content_types_string,
'Content-Type'=>'application/json',
}).
to_return(status: 200, body: "", headers: {})
subject.put_report('infinity', report, environment: environment)
end
it 'percent encodes the uri before submitting the report' do
stub_request(:put, "https://www.example.com/puppet/v3/report/node%20name?environment=testing")
.to_return(status: 200, body: "", headers: {})
subject.put_report('node name', report, environment: environment)
end
it 'returns the response whose body contains the list of report processors' do
body = "[\"store\":\"http\"]"
stub_request(:put, url)
.to_return(status: 200, body: body, headers: {'Content-Type' => 'application/json'})
resp = subject.put_report('infinity', report, environment: environment)
expect(resp.body).to eq(body)
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises response error if unsuccessful' do
stub_request(:put, url).to_return(status: [400, 'Bad Request'], headers: {'X-Puppet-Version' => '6.1.8' })
expect {
subject.put_report('infinity', report, environment: environment)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Bad Request')
expect(err.response.code).to eq(400)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/service/file_server_spec.rb | spec/unit/http/service/file_server_spec.rb | require 'spec_helper'
require 'puppet_spec/network'
require 'puppet/http'
describe Puppet::HTTP::Service::FileServer do
include PuppetSpec::Files
include PuppetSpec::Network
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:subject) { client.create_session.route_to(:fileserver) }
let(:environment) { 'testing' }
let(:report) { Puppet::Transaction::Report.new }
before :each do
Puppet[:server] = 'www.example.com'
Puppet[:serverport] = 443
end
context 'when making requests' do
let(:uri) {"https://www.example.com:443/puppet/v3/file_content/:mount/:path?environment=testing"}
it 'includes default HTTP headers' do
stub_request(:get, uri).with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end
subject.get_file_content(path: '/:mount/:path', environment: environment) { |data| }
end
end
context 'when routing to the file service' do
it 'defaults the server and port based on settings' do
Puppet[:server] = 'file.example.com'
Puppet[:serverport] = 8141
stub_request(:get, "https://file.example.com:8141/puppet/v3/file_content/:mount/:path?environment=testing")
subject.get_file_content(path: '/:mount/:path', environment: environment) { |data| }
end
end
context 'retrieving file metadata' do
let(:path) { tmpfile('get_file_metadata') }
let(:url) { "https://www.example.com/puppet/v3/file_metadata/:mount/#{path}?checksum_type=sha256&environment=testing&links=manage&source_permissions=ignore" }
let(:filemetadata) { Puppet::FileServing::Metadata.new(path) }
let(:request_path) { "/:mount/#{path}"}
it 'includes puppet headers set via the :http_extra_headers and :profile settings' do
stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}).
to_return(status: 200, body: filemetadata.render, headers: { 'Content-Type' => 'application/json' })
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.get_file_metadata(path: request_path, environment: environment)
end
it 'submits a request for file metadata to the server' do
stub_request(:get, url).with(
headers: {'Accept'=>acceptable_content_types_string}
).to_return(
status: 200, body: filemetadata.render, headers: { 'Content-Type' => 'application/json' }
)
_, metadata = subject.get_file_metadata(path: request_path, environment: environment)
expect(metadata.path).to eq(path)
end
it 'returns the request response' do
stub_request(:get, url).to_return(
status: 200, body: filemetadata.render, headers: { 'Content-Type' => 'application/json' }
)
resp, _ = subject.get_file_metadata(path: request_path, environment: environment)
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises a protocol error if the Content-Type header is missing from the response' do
stub_request(:get, url).to_return(status: 200, body: '', headers: {})
expect {
subject.get_file_metadata(path: request_path, environment: environment)
}.to raise_error(Puppet::HTTP::ProtocolError, "No content type in http response; cannot parse")
end
it 'raises an error if the Content-Type is unsupported' do
stub_request(:get, url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'text/yaml' })
expect {
subject.get_file_metadata(path: request_path, environment: environment)
}.to raise_error(Puppet::HTTP::ProtocolError, "Content-Type is unsupported")
end
it 'raises response error if unsuccessful' do
stub_request(:get, url).to_return(status: [400, 'Bad Request'])
expect {
subject.get_file_metadata(path: request_path, environment: environment)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Bad Request')
expect(err.response.code).to eq(400)
end
end
it 'raises a serialization error if serialization fails' do
stub_request(:get, url).to_return(
status: 200, body: '', headers: { 'Content-Type' => 'application/json' }
)
expect {
subject.get_file_metadata(path: request_path, environment: environment)
}.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::FileServing::Metadata from json/)
end
it 'raises response error if path is relative' do
expect {
subject.get_file_metadata(path: 'relative_path', environment: environment)
}.to raise_error(ArgumentError, 'Path must start with a slash')
end
end
context 'retrieving multiple file metadatas' do
let(:path) { tmpfile('get_file_metadatas') }
let(:url) { "https://www.example.com/puppet/v3/file_metadatas/:mount/#{path}?checksum_type=sha256&links=manage&recurse=false&source_permissions=ignore&environment=testing" }
let(:filemetadatas) { [Puppet::FileServing::Metadata.new(path)] }
let(:formatter) { Puppet::Network::FormatHandler.format(:json) }
let(:request_path) { "/:mount/#{path}"}
it 'includes puppet headers set via the :http_extra_headers and :profile settings' do
stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}).
to_return(status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' })
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.get_file_metadatas(path: request_path, environment: environment)
end
it 'submits a request for file metadata to the server' do
stub_request(:get, url).with(
headers: {'Accept' => acceptable_content_types_string}
).to_return(
status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' }
)
_, metadatas = subject.get_file_metadatas(path: request_path, environment: environment)
expect(metadatas.first.path).to eq(path)
end
it 'returns the request response' do
stub_request(:get, url).to_return(
status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' }
)
resp, _ = subject.get_file_metadatas(path: request_path, environment: environment)
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'automatically converts an array of parameters to the stringified query' do
url = "https://www.example.com/puppet/v3/file_metadatas/:mount/#{path}?checksum_type=sha256&environment=testing&ignore=CVS&ignore=.git&ignore=.hg&links=manage&recurse=false&source_permissions=ignore"
stub_request(:get, url).with(
headers: {'Accept'=>acceptable_content_types_string}
).to_return(
status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' }
)
_, metadatas = subject.get_file_metadatas(path: request_path, environment: environment, ignore: ['CVS', '.git', '.hg'])
expect(metadatas.first.path).to eq(path)
end
it 'raises a protocol error if the Content-Type header is missing from the response' do
stub_request(:get, url).to_return(status: 200, body: '', headers: {})
expect {
subject.get_file_metadatas(path: request_path, environment: environment)
}.to raise_error(Puppet::HTTP::ProtocolError, "No content type in http response; cannot parse")
end
it 'raises an error if the Content-Type is unsupported' do
stub_request(:get, url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'text/yaml' })
expect {
subject.get_file_metadatas(path: request_path, environment: environment)
}.to raise_error(Puppet::HTTP::ProtocolError, "Content-Type is unsupported")
end
it 'raises response error if unsuccessful' do
stub_request(:get, url).to_return(status: [400, 'Bad Request'])
expect {
subject.get_file_metadatas(path: request_path, environment: environment)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Bad Request')
expect(err.response.code).to eq(400)
end
end
it 'raises a serialization error if serialization fails' do
stub_request(:get, url).to_return(
status: 200, body: '', headers: { 'Content-Type' => 'application/json' }
)
expect {
subject.get_file_metadatas(path: request_path, environment: environment)
}.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize multiple Puppet::FileServing::Metadata from json/)
end
it 'raises response error if path is relative' do
expect {
subject.get_file_metadatas(path: 'relative_path', environment: environment)
}.to raise_error(ArgumentError, 'Path must start with a slash')
end
end
context 'getting file content' do
let(:uri) {"https://www.example.com:443/puppet/v3/file_content/:mount/:path?environment=testing"}
it 'includes puppet headers set via the :http_extra_headers and :profile settings' do
stub_request(:get, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}).
to_return(status: 200, body: "and beyond")
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
expect { |b|
subject.get_file_content(path: '/:mount/:path', environment: environment, &b)
}.to yield_with_args("and beyond")
end
it 'yields file content' do
stub_request(:get, uri).with do |request|
expect(request.headers).to include({'Accept' => 'application/octet-stream'})
end.to_return(status: 200, body: "and beyond")
expect { |b|
subject.get_file_content(path: '/:mount/:path', environment: environment, &b)
}.to yield_with_args("and beyond")
end
it 'returns the request response' do
stub_request(:get, uri)
resp = subject.get_file_content(path: '/:mount/:path', environment: environment) { |b| b }
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises response error if unsuccessful' do
stub_request(:get, uri).to_return(status: [400, 'Bad Request'])
expect {
subject.get_file_content(path: '/:mount/:path', environment: environment) { |data| }
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Bad Request')
expect(err.response.code).to eq(400)
end
end
it 'raises response error if path is relative' do
expect {
subject.get_file_content(path: 'relative_path', environment: environment) { |data| }
}.to raise_error(ArgumentError, 'Path must start with a slash')
end
end
context 'getting static file content' do
let(:code_id) { "0fc72115-adc6-4b1a-aa50-8f31b3ece440" }
let(:uri) { "https://www.example.com:443/puppet/v3/static_file_content/:mount/:path?environment=testing&code_id=#{code_id}"}
it 'yields file content' do
stub_request(:get, uri).with do |request|
expect(request.headers).to include({'Accept' => 'application/octet-stream'})
end.to_return(status: 200, body: "and beyond")
expect { |b|
subject.get_static_file_content(path: '/:mount/:path', environment: environment, code_id: code_id, &b)
}.to yield_with_args("and beyond")
end
it 'returns the request response' do
stub_request(:get, uri)
resp = subject.get_static_file_content(path: '/:mount/:path', environment: environment, code_id: code_id) { |b| b }
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises response error if unsuccessful' do
stub_request(:get, uri).to_return(status: [400, 'Bad Request'])
expect {
subject.get_static_file_content(path: '/:mount/:path', environment: environment, code_id: code_id) { |data| }
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Bad Request')
expect(err.response.code).to eq(400)
end
end
it 'raises response error if path is relative' do
expect {
subject.get_static_file_content(path: 'relative_path', environment: environment, code_id: code_id) { |data| }
}.to raise_error(ArgumentError, 'Path must start with a slash')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/http/service/compiler_spec.rb | spec/unit/http/service/compiler_spec.rb |
# coding: utf-8
require 'spec_helper'
require 'puppet/http'
describe Puppet::HTTP::Service::Compiler do
let(:ssl_context) { Puppet::SSL::SSLContext.new }
let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) }
let(:subject) { client.create_session.route_to(:puppet) }
let(:environment) { 'testing' }
let(:certname) { 'ziggy' }
let(:node) { Puppet::Node.new(certname) }
let(:facts) { Puppet::Node::Facts.new(certname) }
let(:catalog) { Puppet::Resource::Catalog.new(certname) }
let(:formatter) { Puppet::Network::FormatHandler.format(:json) }
before :each do
Puppet[:server] = 'compiler.example.com'
Puppet[:serverport] = 8140
Puppet::Node::Facts.indirection.terminus_class = :memory
end
context 'when making requests' do
let(:uri) {"https://compiler.example.com:8140/puppet/v3/catalog/ziggy?environment=testing"}
it 'includes default HTTP headers' do
stub_request(:post, uri).with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end.to_return(body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime })
subject.post_catalog(certname, environment: environment, facts: facts)
end
end
context 'when routing to the compiler service' do
it 'defaults the server and port based on settings' do
Puppet[:server] = 'compiler2.example.com'
Puppet[:serverport] = 8141
stub_request(:post, "https://compiler2.example.com:8141/puppet/v3/catalog/ziggy?environment=testing")
.to_return(body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime })
subject.post_catalog(certname, environment: environment, facts: facts)
end
end
context 'when posting for a catalog' do
let(:uri) { %r{/puppet/v3/catalog/ziggy} }
let(:catalog_response) { { body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime } } }
it 'includes puppet headers set via the :http_extra_headers and :profile settings' do
stub_request(:post, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}).
to_return(body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime })
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.post_catalog(certname, environment: environment, facts: facts)
end
it 'submits facts as application/json by default' do
stub_request(:post, uri)
.with(body: hash_including("facts_format" => /application\/json/))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: environment, facts: facts)
end
it 'submits facts as pson if set as the preferred format', if: Puppet.features.pson? do
Puppet[:preferred_serialization_format] = "pson"
stub_request(:post, uri)
.with(body: hash_including("facts_format" => /pson/))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: environment, facts: facts)
end
it 'includes environment as a query parameter AND in the POST body' do
stub_request(:post, uri)
.with(query: {"environment" => "outerspace"},
body: hash_including("environment" => 'outerspace'))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: 'outerspace', facts: facts)
end
it 'includes configured_environment' do
stub_request(:post, uri)
.with(body: hash_including("configured_environment" => 'agent_specified'))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: 'production', facts: facts, configured_environment: 'agent_specified')
end
it 'includes check_environment' do
stub_request(:post, uri)
.with(body: hash_including('check_environment' => 'false'))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: 'production', facts: facts)
end
it 'includes transaction_uuid' do
uuid = "ec3d2844-b236-4287-b0ad-632fbb4d1ff0"
stub_request(:post, uri)
.with(body: hash_including("transaction_uuid" => uuid))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: 'production', facts: facts, transaction_uuid: uuid)
end
it 'includes job_uuid' do
uuid = "3dd13eec-1b6b-4b5d-867b-148193e0593e"
stub_request(:post, uri)
.with(body: hash_including("job_uuid" => uuid))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: 'production', facts: facts, job_uuid: uuid)
end
it 'includes static_catalog' do
stub_request(:post, uri)
.with(body: hash_including("static_catalog" => "false"))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: 'production', facts: facts, static_catalog: false)
end
it 'includes dot-separated list of checksum_types' do
stub_request(:post, uri)
.with(body: hash_including("checksum_type" => "sha256.sha384"))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: 'production', facts: facts, checksum_type: %w[sha256 sha384])
end
it 'does not accept msgpack by default' do
stub_request(:post, uri)
.with(headers: {'Accept' => 'application/vnd.puppet.rich+json, application/json'})
.to_return(**catalog_response)
allow(Puppet.features).to receive(:msgpack?).and_return(false)
allow(Puppet.features).to receive(:pson?).and_return(false)
subject.post_catalog(certname, environment: environment, facts: facts)
end
it 'accepts msgpack & rich_json_msgpack if the gem is present' do
stub_request(:post, uri)
.with(headers: {'Accept' => 'application/vnd.puppet.rich+json, application/json, application/vnd.puppet.rich+msgpack, application/x-msgpack'})
.to_return(**catalog_response)
allow(Puppet.features).to receive(:msgpack?).and_return(true)
allow(Puppet.features).to receive(:pson?).and_return(false)
subject.post_catalog(certname, environment: environment, facts: facts)
end
it 'returns a deserialized catalog' do
stub_request(:post, uri)
.to_return(**catalog_response)
_, cat = subject.post_catalog(certname, environment: 'production', facts: facts)
expect(cat).to be_a(Puppet::Resource::Catalog)
expect(cat.name).to eq(certname)
end
it 'deserializes the catalog from msgpack', if: Puppet.features.msgpack? do
body = catalog.to_msgpack
formatter = Puppet::Network::FormatHandler.format(:msgpack)
catalog_response = { body: body, headers: {'Content-Type' => formatter.mime }}
stub_request(:post, uri)
.to_return(**catalog_response)
_, cat = subject.post_catalog(certname, environment: 'production', facts: facts)
expect(cat).to be_a(Puppet::Resource::Catalog)
expect(cat.name).to eq(certname)
end
it 'deserializes the catalog from rich msgpack', if: Puppet.features.msgpack? do
body = Puppet.override(rich_data: true) do
catalog.to_msgpack
end
formatter = Puppet::Network::FormatHandler.format(:rich_data_msgpack)
catalog_response = { body: body, headers: {'Content-Type' => formatter.mime }}
stub_request(:post, uri)
.to_return(**catalog_response)
_, cat = subject.post_catalog(certname, environment: 'production', facts: facts)
expect(cat).to be_a(Puppet::Resource::Catalog)
expect(cat.name).to eq(certname)
end
it 'returns the request response' do
stub_request(:post, uri)
.to_return(**catalog_response)
resp, _ = subject.post_catalog(certname, environment: 'production', facts: facts)
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises a response error if unsuccessful' do
stub_request(:post, uri)
.to_return(status: [500, "Server Error"])
expect {
subject.post_catalog(certname, environment: 'production', facts: facts)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Server Error')
expect(err.response.code).to eq(500)
end
end
it 'raises a protocol error if the content-type header is missing' do
stub_request(:post, uri)
.to_return(body: "content-type is missing")
expect {
subject.post_catalog(certname, environment: 'production', facts: facts)
}.to raise_error(Puppet::HTTP::ProtocolError, /No content type in http response; cannot parse/)
end
it 'raises a serialization error if the content is invalid' do
stub_request(:post, uri)
.to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'})
expect {
subject.post_catalog(certname, environment: 'production', facts: facts)
}.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::Resource::Catalog from json/)
end
context 'serializing facts' do
facts_with_special_characters = [
{ :hash => { 'afact' => 'a+b' }, :encoded => 'a%2Bb' },
{ :hash => { 'afact' => 'a b' }, :encoded => 'a%20b' },
{ :hash => { 'afact' => 'a&b' }, :encoded => 'a%26b' },
{ :hash => { 'afact' => 'a*b' }, :encoded => 'a%2Ab' },
{ :hash => { 'afact' => 'a=b' }, :encoded => 'a%3Db' },
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
{ :hash => { 'afact' => "A\u06FF\u16A0\u{2070E}" }, :encoded => 'A%DB%BF%E1%9A%A0%F0%A0%9C%8E' },
]
facts_with_special_characters.each do |test_fact|
it "escapes special characters #{test_fact[:hash]}" do
facts = Puppet::Node::Facts.new(certname, test_fact[:hash])
Puppet::Node::Facts.indirection.save(facts)
stub_request(:post, uri)
.with(body: hash_including("facts" => /#{test_fact[:encoded]}/))
.to_return(**catalog_response)
subject.post_catalog(certname, environment: environment, facts: facts)
end
end
end
end
context 'when posting for a v4 catalog' do
let(:uri) {"https://compiler.example.com:8140/puppet/v4/catalog"}
let(:persistence) {{ facts: true, catalog: true }}
let(:facts) {{ 'foo' => 'bar' }}
let(:trusted_facts) {{}}
let(:uuid) { "ec3d2844-b236-4287-b0ad-632fbb4d1ff0" }
let(:job_id) { "1" }
let(:payload) {{
environment: environment,
persistence: persistence,
facts: facts,
trusted_facts: trusted_facts,
transaction_uuid: uuid,
job_id: job_id,
options: {
prefer_requested_environment: false,
capture_logs: false
}
}}
let(:serialized_catalog) {{ 'catalog' => catalog.to_data_hash }.to_json}
let(:catalog_response) {{ body: serialized_catalog, headers: {'Content-Type' => formatter.mime }}}
it 'includes default HTTP headers' do
stub_request(:post, uri).with do |request|
expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./})
expect(request.headers).to_not include('X-Puppet-Profiling')
end.to_return(**catalog_response)
subject.post_catalog4(certname, **payload)
end
it 'defaults the server and port based on settings' do
Puppet[:server] = 'compiler2.example.com'
Puppet[:serverport] = 8141
stub_request(:post, "https://compiler2.example.com:8141/puppet/v4/catalog")
.to_return(**catalog_response)
subject.post_catalog4(certname, **payload)
end
it 'includes puppet headers set via the :http_extra_headers and :profile settings' do
stub_request(:post, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}).
to_return(**catalog_response)
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.post_catalog4(certname, **payload)
end
it 'returns a deserialized catalog' do
stub_request(:post, uri)
.to_return(**catalog_response)
_, cat, _ = subject.post_catalog4(certname, **payload)
expect(cat).to be_a(Puppet::Resource::Catalog)
expect(cat.name).to eq(certname)
end
it 'returns the request response' do
stub_request(:post, uri)
.to_return(**catalog_response)
resp, _, _ = subject.post_catalog4(certname, **payload)
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises a response error if unsuccessful' do
stub_request(:post, uri)
.to_return(status: [500, "Server Error"])
expect {
subject.post_catalog4(certname, **payload)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Server Error')
expect(err.response.code).to eq(500)
end
end
it 'raises a response error when server response is not JSON' do
stub_request(:post, uri)
.to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'})
expect {
subject.post_catalog4(certname, **payload)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::SerializationError)
expect(err.message).to match(/Failed to deserialize catalog from puppetserver response/)
end
end
it 'raises a response error when server response a JSON serialized catalog' do
stub_request(:post, uri)
.to_return(body: {oops: 'bad response data'}.to_json, headers: {'Content-Type' => 'application/json'})
expect {
subject.post_catalog4(certname, **payload)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::SerializationError)
expect(err.message).to match(/Failed to deserialize catalog from puppetserver response/)
end
end
it 'raises ArgumentError when the `persistence` hash does not contain required keys' do
payload[:persistence].delete(:facts)
expect { subject.post_catalog4(certname, **payload) }.to raise_error do |err|
expect(err).to be_an_instance_of(ArgumentError)
expect(err.message).to match(/The 'persistence' hash is missing the keys: facts/)
end
end
it 'raises ArgumentError when `facts` are not a Hash' do
payload[:facts] = Puppet::Node::Facts.new(certname)
expect { subject.post_catalog4(certname, **payload) }.to raise_error do |err|
expect(err).to be_an_instance_of(ArgumentError)
expect(err.message).to match(/Facts must be a Hash not a Puppet::Node::Facts/)
end
end
end
context 'when getting a node' do
let(:uri) { %r{/puppet/v3/node/ziggy} }
let(:node_response) { { body: formatter.render(node), headers: {'Content-Type' => formatter.mime } } }
it 'includes custom headers set via the :http_extra_headers and :profile settings' do
stub_request(:get, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}).
to_return(**node_response)
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.get_node(certname, environment: 'production')
end
it 'includes environment' do
stub_request(:get, uri)
.with(query: hash_including("environment" => "outerspace"))
.to_return(**node_response)
subject.get_node(certname, environment: 'outerspace')
end
it 'includes configured_environment' do
stub_request(:get, uri)
.with(query: hash_including("configured_environment" => 'agent_specified'))
.to_return(**node_response)
subject.get_node(certname, environment: 'production', configured_environment: 'agent_specified')
end
it 'includes transaction_uuid' do
uuid = "ec3d2844-b236-4287-b0ad-632fbb4d1ff0"
stub_request(:get, uri)
.with(query: hash_including("transaction_uuid" => uuid))
.to_return(**node_response)
subject.get_node(certname, environment: 'production', transaction_uuid: uuid)
end
it 'returns a deserialized node' do
stub_request(:get, uri)
.to_return(**node_response)
_, n = subject.get_node(certname, environment: 'production')
expect(n).to be_a(Puppet::Node)
expect(n.name).to eq(certname)
end
it 'returns the request response' do
stub_request(:get, uri)
.to_return(**node_response)
resp, _ = subject.get_node(certname, environment: 'production')
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises a response error if unsuccessful' do
stub_request(:get, uri)
.to_return(status: [500, "Server Error"])
expect {
subject.get_node(certname, environment: 'production')
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Server Error')
expect(err.response.code).to eq(500)
end
end
it 'raises a protocol error if the content-type header is missing' do
stub_request(:get, uri)
.to_return(body: "content-type is missing")
expect {
subject.get_node(certname, environment: 'production')
}.to raise_error(Puppet::HTTP::ProtocolError, /No content type in http response; cannot parse/)
end
it 'raises a serialization error if the content is invalid' do
stub_request(:get, uri)
.to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'})
expect {
subject.get_node(certname, environment: 'production')
}.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::Node from json/)
end
end
context 'when getting facts' do
let(:uri) { %r{/puppet/v3/facts/ziggy} }
let(:facts_response) { { body: formatter.render(facts), headers: {'Content-Type' => formatter.mime } } }
it 'includes environment' do
stub_request(:get, uri)
.with(query: hash_including("environment" => "outerspace"))
.to_return(**facts_response)
subject.get_facts(certname, environment: 'outerspace')
end
it 'returns a deserialized facts object' do
stub_request(:get, uri)
.to_return(**facts_response)
_, n = subject.get_facts(certname, environment: 'production')
expect(n).to be_a(Puppet::Node::Facts)
expect(n.name).to eq(certname)
end
it 'returns the request response' do
stub_request(:get, uri)
.to_return(**facts_response)
resp, _ = subject.get_facts(certname, environment: 'production')
expect(resp).to be_a(Puppet::HTTP::Response)
end
it 'raises a response error if unsuccessful' do
stub_request(:get, uri)
.to_return(status: [500, "Server Error"])
expect {
subject.get_facts(certname, environment: 'production')
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Server Error')
expect(err.response.code).to eq(500)
end
end
it 'raises a protocol error if the content-type header is missing' do
stub_request(:get, uri)
.to_return(body: "content-type is missing")
expect {
subject.get_facts(certname, environment: 'production')
}.to raise_error(Puppet::HTTP::ProtocolError, /No content type in http response; cannot parse/)
end
it 'raises a serialization error if the content is invalid' do
stub_request(:get, uri)
.to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'})
expect {
subject.get_facts(certname, environment: 'production')
}.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::Node::Facts from json/)
end
end
context 'when putting facts' do
let(:uri) { %r{/puppet/v3/facts/ziggy} }
it 'includes custom headers set the :http_extra_headers and :profile settings' do
stub_request(:put, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'})
Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing'
Puppet[:profile] = true
subject.put_facts(certname, environment: environment, facts: facts)
end
it 'serializes facts in the body' do
facts = Puppet::Node::Facts.new(certname, { 'domain' => 'zork'})
Puppet::Node::Facts.indirection.save(facts)
stub_request(:put, uri)
.with(body: hash_including("name" => "ziggy", "values" => {"domain" => "zork"}))
subject.put_facts(certname, environment: environment, facts: facts)
end
it 'includes environment' do
stub_request(:put, uri)
.with(query: {"environment" => "outerspace"})
subject.put_facts(certname, environment: 'outerspace', facts: facts)
end
it 'returns the request response' do
# the REST API returns the filename, good grief
stub_request(:put, uri)
.to_return(status: 200, body: "/opt/puppetlabs/server/data/puppetserver/yaml/facts/#{certname}.yaml")
expect(subject.put_facts(certname, environment: environment, facts: facts)).to be_a(Puppet::HTTP::Response)
end
it 'raises a response error if unsuccessful' do
stub_request(:put, uri)
.to_return(status: [500, "Server Error"])
expect {
subject.put_facts(certname, environment: environment, facts: facts)
}.to raise_error do |err|
expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError)
expect(err.message).to eq('Server Error')
expect(err.response.code).to eq(500)
end
end
it 'raises a serialization error if the report cannot be serialized' do
invalid_facts = Puppet::Node::Facts.new(certname, {'invalid_utf8_sequence' => "\xE2\x82".force_encoding('binary')})
expect {
subject.put_facts(certname, environment: 'production', facts: invalid_facts)
}.to raise_error(Puppet::HTTP::SerializationError, /Failed to serialize Puppet::Node::Facts to json: ("\\xE2" from ASCII-8BIT to UTF-8|partial character in source, but hit end)/)
end
end
context 'filebucket' do
let(:filebucket_file) { Puppet::FileBucket::File.new('file to store') }
let(:formatter) { Puppet::Network::FormatHandler.format(:binary) }
let(:path) { "md5/4aabe1257043bd03ce4c3319c155bc55" }
let(:uri) { %r{/puppet/v3/file_bucket_file/#{path}} }
context 'when getting a file' do
let(:status_response) { { body: formatter.render(filebucket_file), headers: {'Content-Type' => 'application/octet-stream' }}}
it 'includes default HTTP headers' do
stub_request(:get, uri).with do |request|
expect(request.headers).to include({
'X-Puppet-Version' => /./,
'User-Agent' => /./,
'Accept' => 'application/octet-stream'
})
expect(request.headers).to_not include('X-Puppet-Profiling')
end.to_return(**status_response)
subject.get_filebucket_file(path, environment: 'production')
end
it 'always the environment as a parameter' do
stub_request(:get, uri).with(query: hash_including('environment' => 'production')).to_return(**status_response)
subject.get_filebucket_file(path, environment: 'production')
end
{bucket_path: 'path', diff_with: '4aabe1257043bd0', list_all: 'true', fromdate: '20200404', todate: '20200404'}.each do |param, val|
it "includes #{param} as a parameter in the request if #{param} is set" do
stub_request(:get, uri).with(query: hash_including(param => val)).to_return(**status_response)
options = { param => val }
subject.get_filebucket_file(path, environment: 'production', **options)
end
end
it "doesn't include :diff_with as a query param if :bucket_path is nil" do
stub_request(:get, uri).with do |request|
expect(request.uri.query).not_to match(/diff_with/)
end.to_return(**status_response)
subject.get_filebucket_file(path, environment: 'production', diff_with: nil)
end
it 'returns a deserialized response' do
stub_request(:get, uri)
.to_return(**status_response)
_, s = subject.get_filebucket_file(path, environment: 'production')
expect(s).to be_a(Puppet::FileBucket::File)
expect(s.contents).to eq('file to store')
end
it 'returns the request response' do
stub_request(:get, uri)
.to_return(**status_response)
resp, _ = subject.get_filebucket_file(path, environment: 'production')
expect(resp).to be_a(Puppet::HTTP::Response)
end
end
context 'when putting a file' do
let(:status_response) { { status: 200, body: '' } }
it 'includes default HTTP headers' do
stub_request(:put, uri).with do |request|
expect(request.headers).to include({
'X-Puppet-Version' => /./,
'User-Agent' => /./,
'Accept' => 'application/octet-stream',
'Content-Type' => 'application/octet-stream'
})
expect(request.headers).to_not include('X-Puppet-Profiling')
end.to_return(**status_response)
subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production')
end
it 'always the environment as a parameter' do
stub_request(:put, uri).with(query: hash_including('environment' => 'production')).to_return(**status_response)
subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production')
end
it 'sends the file contents as the request body' do
stub_request(:put, uri).with(body: filebucket_file.contents).to_return(**status_response)
subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production')
end
it 'returns the request response' do
stub_request(:put, uri)
.to_return(**status_response)
s = subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production')
expect(s).to be_a(Puppet::HTTP::Response)
end
end
context 'when heading a file' do
let(:status_response) {{ status: 200 }}
it 'includes default HTTP headers' do
stub_request(:head, uri).with do |request|
expect(request.headers).to include({
'X-Puppet-Version' => /./,
'User-Agent' => /./,
'Accept' => 'application/octet-stream',
})
expect(request.headers).to_not include('X-Puppet-Profiling')
end.to_return(**status_response)
subject.head_filebucket_file(path, environment: 'production')
end
it 'always the environment as a parameter' do
stub_request(:head, uri).with(query: hash_including('environment' => 'production')).to_return(**status_response)
subject.head_filebucket_file(path, environment: 'production')
end
it "includes :bucket_path as a parameter in the request if :bucket_path is set" do
stub_request(:head, uri).with(query: hash_including(:bucket_path => 'some/path')).to_return(**status_response)
subject.head_filebucket_file(path, environment: 'production', bucket_path: 'some/path')
end
it "doesn't include :bucket_path as a query param if :bucket_path is nil" do
stub_request(:head, uri).with do |request|
expect(request.uri.query).not_to match(/bucket_path/)
end.to_return(**status_response)
subject.head_filebucket_file(path, environment: 'production', bucket_path: nil)
end
it "returns the request response" do
stub_request(:head, uri).with(query: hash_including(:bucket_path => 'some/path')).to_return(**status_response)
resp = subject.head_filebucket_file(path, environment: 'production', bucket_path: 'some/path')
expect(resp).to be_a(Puppet::HTTP::Response)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.