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
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_content/selector_spec.rb
spec/unit/indirector/file_content/selector_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/selector' describe Puppet::Indirector::FileContent::Selector do include PuppetSpec::Files it_should_behave_like "Puppet::FileServing::Files", :file_content end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_content/rest_spec.rb
spec/unit/indirector/file_content/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/rest' describe Puppet::Indirector::FileContent::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/file_content/:mount/path/to/file} } let(:key) { "puppet:///:mount/path/to/file" } before :each do described_class.indirection.terminus_class = :rest end def file_content_response {body: "some content", headers: { 'Content-Type' => 'application/octet-stream' } } end it "returns content as a binary string" do stub_request(:get, uri).to_return(status: 200, **file_content_response) file_content = described_class.indirection.find(key) expect(file_content.content.encoding).to eq(Encoding::BINARY) expect(file_content.content).to eq('some content') end it "URL encodes special characters" do stub_request(:get, %r{/puppet/v3/file_content/:mount/path%20to%20file}).to_return(status: 200, **file_content_response) described_class.indirection.find('puppet:///:mount/path to file') end it "returns nil if the content doesn't exist" do stub_request(:get, uri).to_return(status: 404) expect(described_class.indirection.find(key)).to be_nil end it "raises if fail_on_404 is true" do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { described_class.indirection.find(key, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/file_content/:mount/path/to/file resulted in 404 with the message: {}}) end it "raises an error on HTTP 500" do stub_request(:get, uri).to_return(status: 500, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { described_class.indirection.find(key) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end it "connects to a specific host" do stub_request(:get, %r{https://example.com:8140/puppet/v3/file_content/:mount/path/to/file}) .to_return(status: 200, **file_content_response) described_class.indirection.find("puppet://example.com:8140/:mount/path/to/file") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_content/file_server_spec.rb
spec/unit/indirector/file_content/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/file_server' describe Puppet::Indirector::FileContent::FileServer do it "should be registered with the file_content indirection" do expect(Puppet::Indirector::Terminus.terminus_class(:file_content, :file_server)).to equal(Puppet::Indirector::FileContent::FileServer) end it "should be a subclass of the FileServer terminus" do expect(Puppet::Indirector::FileContent::FileServer.superclass).to equal(Puppet::Indirector::FileServer) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/report/rest_spec.rb
spec/unit/indirector/report/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/report/rest' describe Puppet::Transaction::Report::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/report/ziggy} } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } let(:report) do report = Puppet::Transaction::Report.new report.host = certname report end before(:each) do described_class.indirection.terminus_class = :rest end def report_response { body: formatter.render(["store", "http"]), headers: {'Content-Type' => formatter.mime } } end it "saves a report " do stub_request(:put, uri) .to_return(status: 200, **report_response) described_class.indirection.save(report) end it "serializes the environment" do stub_request(:put, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(**report_response) described_class.indirection.save(report, nil, environment: Puppet::Node::Environment.remote('outerspace')) end it "deserializes the response as an array of report processor names" do stub_request(:put, %r{/puppet/v3/report}) .to_return(status: 200, **report_response) expect(described_class.indirection.save(report)).to eq(["store", "http"]) end it "returns nil if the node does not exist" do stub_request(:put, uri) .to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect(described_class.indirection.save(report)).to be_nil end it "parses charset from response content-type" do stub_request(:put, uri) .to_return(status: 200, body: JSON.dump(["store"]), headers: { 'Content-Type' => 'application/json;charset=utf-8' }) expect(described_class.indirection.save(report)).to eq(["store"]) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/report/msgpack_spec.rb
spec/unit/indirector/report/msgpack_spec.rb
require 'spec_helper' require 'puppet/transaction/report' require 'puppet/indirector/report/msgpack' describe Puppet::Transaction::Report::Msgpack, :if => Puppet.features.msgpack? do it "should be a subclass of the Msgpack terminus" do expect(Puppet::Transaction::Report::Msgpack.superclass).to equal(Puppet::Indirector::Msgpack) end it "should have documentation" do expect(Puppet::Transaction::Report::Msgpack.doc).not_to be_nil end it "should be registered with the report indirection" do indirection = Puppet::Indirector::Indirection.instance(:report) expect(Puppet::Transaction::Report::Msgpack.indirection).to equal(indirection) end it "should have its name set to :msgpack" do expect(Puppet::Transaction::Report::Msgpack.name).to eq(:msgpack) end it "should unconditionally save/load from the --lastrunreport setting" do expect(subject.path(:me)).to eq(Puppet[:lastrunreport]) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/report/processor_spec.rb
spec/unit/indirector/report/processor_spec.rb
require 'spec_helper' require 'puppet/indirector/report/processor' describe Puppet::Transaction::Report::Processor do before do allow(Puppet.settings).to receive(:use).and_return(true) end it "should provide a method for saving reports" do expect(Puppet::Transaction::Report::Processor.new).to respond_to(:save) end it "should provide a method for cleaning reports" do expect(Puppet::Transaction::Report::Processor.new).to respond_to(:destroy) end end describe Puppet::Transaction::Report::Processor, " when processing a report" do before do allow(Puppet.settings).to receive(:use) @reporter = Puppet::Transaction::Report::Processor.new @request = double('request', :instance => double("report", :host => 'hostname'), :key => 'node') end it "should not save the report if reports are set to 'none'" do expect(Puppet::Reports).not_to receive(:report) Puppet[:reports] = 'none' request = Puppet::Indirector::Request.new(:indirection_name, :head, "key", nil) report = Puppet::Transaction::Report.new request.instance = report @reporter.save(request) end it "should save the report with each configured report type" do Puppet[:reports] = "one,two" expect(@reporter.send(:reports)).to eq(%w{one two}) expect(Puppet::Reports).to receive(:report).with('one') expect(Puppet::Reports).to receive(:report).with('two') @reporter.save(@request) end it "should destroy reports for each processor that responds to destroy" do Puppet[:reports] = "http,store" http_report = double() store_report = double() expect(store_report).to receive(:destroy).with(@request.key) expect(Puppet::Reports).to receive(:report).with('http').and_return(http_report) expect(Puppet::Reports).to receive(:report).with('store').and_return(store_report) @reporter.destroy(@request) end end describe Puppet::Transaction::Report::Processor, " when processing a report" do before do Puppet[:reports] = "one" allow(Puppet.settings).to receive(:use) @reporter = Puppet::Transaction::Report::Processor.new @report_type = double('one') @dup_report = double('dupe report') allow(@dup_report).to receive(:process) @report = Puppet::Transaction::Report.new expect(@report).to receive(:dup).and_return(@dup_report) @request = double('request', :instance => @report) expect(Puppet::Reports).to receive(:report).with("one").and_return(@report_type) expect(@dup_report).to receive(:extend).with(@report_type) end # LAK:NOTE This is stupid, because the code is so short it doesn't # make sense to split it out, which means I just do the same test # three times so the spec looks right. it "should process a duplicate of the report, not the original" do @reporter.save(@request) end it "should extend the report with the report type's module" do @reporter.save(@request) end it "should call the report type's :process method" do expect(@dup_report).to receive(:process) @reporter.save(@request) end it "should not raise exceptions" do Puppet[:trace] = false expect(@dup_report).to receive(:process).and_raise(ArgumentError) expect { @reporter.save(@request) }.not_to raise_error end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/report/json_spec.rb
spec/unit/indirector/report/json_spec.rb
require 'spec_helper' require 'puppet/transaction/report' require 'puppet/indirector/report/json' describe Puppet::Transaction::Report::Json do include PuppetSpec::Files describe '#save' do subject(:indirection) { described_class.indirection } let(:request) { described_class.new } let(:certname) { 'ziggy' } let(:report) do report = Puppet::Transaction::Report.new report.host = certname report end let(:file) { request.path(:me) } before do Puppet[:lastrunreport] = File.join(Puppet[:statedir], "last_run_report.json") indirection.terminus_class = :json end it 'saves the instance of the report as JSON to disk' do indirection.save(report) json = Puppet::FileSystem.read(Puppet[:lastrunreport], :encoding => 'bom|utf-8') content = Puppet::Util::Json.load(json) expect(content["host"]).to eq(certname) end it 'allows mode overwrite' do Puppet.settings.setting(:lastrunreport).mode = '0644' indirection.save(report) if Puppet::Util::Platform.windows? mode = File.stat(file).mode else mode = Puppet::FileSystem.stat(file).mode end expect(mode & 07777).to eq(0644) end context 'when mode is invalid' do before do Puppet.settings.setting(:lastrunreport).mode = '9999' end after do Puppet.settings.setting(:lastrunreport).mode = '0644' end it 'raises Puppet::DevError ' do expect{ indirection.save(report) }.to raise_error(Puppet::DevError, "replace_file mode: 9999 is invalid") end end context 'when report cannot be saved' do it 'raises Error' do FileUtils.mkdir_p(file) expect { indirection.save(report) }.to raise_error(Errno::EISDIR, /last_run_report.json/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/report/yaml_spec.rb
spec/unit/indirector/report/yaml_spec.rb
require 'spec_helper' require 'puppet/transaction/report' require 'puppet/indirector/report/yaml' describe Puppet::Transaction::Report::Yaml do it "should be registered with the report indirection" do indirection = Puppet::Indirector::Indirection.instance(:report) expect(Puppet::Transaction::Report::Yaml.indirection).to equal(indirection) end it "should have its name set to :yaml" do expect(Puppet::Transaction::Report::Yaml.name).to eq(:yaml) end it "should unconditionally save/load from the --lastrunreport setting" do expect(subject.path(:me)).to eq(Puppet[:lastrunreport]) end describe '#save' do subject(:indirection) { described_class.indirection } let(:request) { described_class.new } let(:certname) { 'ziggy' } let(:report) do report = Puppet::Transaction::Report.new report.host = certname report end let(:file) { request.path(:me) } before do indirection.terminus_class = :yaml end it 'saves the instance of the report as YAML to disk' do indirection.save(report) content = Puppet::Util::Yaml.safe_load_file( Puppet[:lastrunreport], [Puppet::Transaction::Report] ) expect(content.host).to eq(certname) end it 'allows mode overwrite' do Puppet.settings.setting(:lastrunreport).mode = '0644' indirection.save(report) if Puppet::Util::Platform.windows? mode = File.stat(file).mode else mode = Puppet::FileSystem.stat(file).mode end expect(mode & 07777).to eq(0644) end context 'when mode is invalid' do before do Puppet.settings.setting(:lastrunreport).mode = '9999' end after do Puppet.settings.setting(:lastrunreport).mode = '0644' end it 'raises Puppet::DevError ' do expect{ indirection.save(report) }.to raise_error(Puppet::DevError, "replace_file mode: 9999 is invalid") end end context 'when repport is invalid' do it 'logs error' do expect(Puppet).to receive(:send_log).with(:err, /Could not save yaml ziggy: can't dump anonymous class/) report.configuration_version = Class.new indirection.save(report) end end context 'when report cannot be saved' do it 'raises Error' do FileUtils.mkdir_p(file) expect { indirection.save(report) }.to raise_error(Errno::EISDIR, /last_run_report.yaml/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_metadata/file_spec.rb
spec/unit/indirector/file_metadata/file_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/file' describe Puppet::Indirector::FileMetadata::File do it "should be registered with the file_metadata indirection" do expect(Puppet::Indirector::Terminus.terminus_class(:file_metadata, :file)).to equal(Puppet::Indirector::FileMetadata::File) end it "should be a subclass of the DirectFileServer terminus" do expect(Puppet::Indirector::FileMetadata::File.superclass).to equal(Puppet::Indirector::DirectFileServer) end describe "when creating the instance for a single found file" do before do @metadata = Puppet::Indirector::FileMetadata::File.new @path = File.expand_path('/my/local') @uri = Puppet::Util.path_to_uri(@path).to_s @data = double('metadata') allow(@data).to receive(:collect) expect(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true) @request = Puppet::Indirector::Request.new(:file_metadata, :find, @uri, nil) end it "should collect its attributes when a file is found" do expect(@data).to receive(:collect) expect(Puppet::FileServing::Metadata).to receive(:new).and_return(@data) expect(@metadata.find(@request)).to eq(@data) end end describe "when searching for multiple files" do before do @metadata = Puppet::Indirector::FileMetadata::File.new @path = File.expand_path('/my/local') @uri = Puppet::Util.path_to_uri(@path).to_s @request = Puppet::Indirector::Request.new(:file_metadata, :find, @uri, nil) end it "should collect the attributes of the instances returned" do expect(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true) expect(Puppet::FileServing::Fileset).to receive(:new).with(@path, @request).and_return(double("fileset")) expect(Puppet::FileServing::Fileset).to receive(:merge).and_return([["one", @path], ["two", @path]]) one = double("one", :collect => nil) expect(Puppet::FileServing::Metadata).to receive(:new).with(@path, {:relative_path => "one"}).and_return(one) two = double("two", :collect => nil) expect(Puppet::FileServing::Metadata).to receive(:new).with(@path, {:relative_path => "two"}).and_return(two) expect(@metadata.search(@request)).to eq([one, two]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_metadata/selector_spec.rb
spec/unit/indirector/file_metadata/selector_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/selector' describe Puppet::Indirector::FileMetadata::Selector do include PuppetSpec::Files it_should_behave_like "Puppet::FileServing::Files", :file_metadata end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_metadata/rest_spec.rb
spec/unit/indirector/file_metadata/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata' require 'puppet/indirector/file_metadata/rest' describe Puppet::Indirector::FileMetadata::Rest do let(:certname) { 'ziggy' } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } let(:model) { described_class.model } before :each do described_class.indirection.terminus_class = :rest end def metadata_response(metadata) { body: formatter.render(metadata), headers: {'Content-Type' => formatter.mime } } end context "when finding" do let(:uri) { %r{/puppet/v3/file_metadata/:mount/path/to/file} } let(:key) { "puppet:///:mount/path/to/file" } let(:metadata) { model.new('/path/to/file') } it "returns file metadata" do stub_request(:get, uri) .to_return(status: 200, **metadata_response(metadata)) result = model.indirection.find(key) expect(result.path).to eq('/path/to/file') end it "URL encodes special characters" do stub_request(:get, %r{/puppet/v3/file_metadata/:mount/path%20to%20file}) .to_return(status: 200, **metadata_response(metadata)) model.indirection.find('puppet:///:mount/path to file') end it "returns nil if the content doesn't exist" do stub_request(:get, uri).to_return(status: 404) expect(model.indirection.find(key)).to be_nil end it "raises if fail_on_404 is true" do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { model.indirection.find(key, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/file_metadata/:mount/path/to/file resulted in 404 with the message: {}}) end it "raises an error on HTTP 500" do stub_request(:get, uri).to_return(status: 500, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { model.indirection.find(key) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end it "connects to a specific host" do stub_request(:get, %r{https://example.com:8140/puppet/v3/file_metadata/:mount/path/to/file}) .to_return(status: 200, **metadata_response(metadata)) model.indirection.find("puppet://example.com:8140/:mount/path/to/file") end end context "when searching" do let(:uri) { %r{/puppet/v3/file_metadatas/:mount/path/to/dir} } let(:key) { "puppet:///:mount/path/to/dir" } let(:metadatas) { [model.new('/path/to/dir')] } it "returns an array of file metadata" do stub_request(:get, uri) .to_return(status: 200, **metadata_response(metadatas)) result = model.indirection.search(key) expect(result.first.path).to eq('/path/to/dir') end it "URL encodes special characters" do stub_request(:get, %r{/puppet/v3/file_metadatas/:mount/path%20to%20dir}) .to_return(status: 200, **metadata_response(metadatas)) model.indirection.search('puppet:///:mount/path to dir') end it "returns an empty array if the metadata doesn't exist" do stub_request(:get, uri).to_return(status: 404) expect(model.indirection.search(key)).to eq([]) end it "returns an empty array if the metadata doesn't exist and fail_on_404 is true" do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect(model.indirection.search(key, fail_on_404: true)).to eq([]) end it "raises an error on HTTP 500" do stub_request(:get, uri).to_return(status: 500, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { model.indirection.search(key) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end it "connects to a specific host" do stub_request(:get, %r{https://example.com:8140/puppet/v3/file_metadatas/:mount/path/to/dir}) .to_return(status: 200, **metadata_response(metadatas)) model.indirection.search("puppet://example.com:8140/:mount/path/to/dir") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_metadata/http_spec.rb
spec/unit/indirector/file_metadata/http_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata' require 'puppet/indirector/file_metadata/http' describe Puppet::Indirector::FileMetadata::Http do DEFAULT_HEADERS = { "Cache-Control" => "private, max-age=0", "Connection" => "close", "Content-Encoding" => "gzip", "Content-Type" => "text/html; charset=ISO-8859-1", "Date" => "Fri, 01 May 2020 17:16:00 GMT", "Expires" => "-1", "Server" => "gws" }.freeze let(:certname) { 'ziggy' } # The model is Puppet:FileServing::Metadata let(:model) { described_class.model } # The http terminus creates instances of HttpMetadata which subclass Metadata let(:metadata) { Puppet::FileServing::HttpMetadata.new(key) } let(:key) { "https://example.com/path/to/file" } # Digest::MD5.base64digest("") => "1B2M2Y8AsgTpgAmY7PhCfg==" let(:content_md5) { {"Content-MD5" => "1B2M2Y8AsgTpgAmY7PhCfg=="} } let(:last_modified) { {"Last-Modified" => "Wed, 01 Jan 2020 08:00:00 GMT"} } before :each do described_class.indirection.terminus_class = :http end context "when finding" do it "returns http file metadata" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS) result = model.indirection.find(key) expect(result.ftype).to eq('file') expect(result.path).to eq('/dev/null') expect(result.relative_path).to be_nil expect(result.destination).to be_nil expect(result.checksum).to match(%r{mtime}) expect(result.owner).to be_nil expect(result.group).to be_nil expect(result.mode).to be_nil end it "reports an md5 checksum if present in the response" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(content_md5)) result = model.indirection.find(key) expect(result.checksum_type).to eq(:md5) expect(result.checksum).to eq("{md5}d41d8cd98f00b204e9800998ecf8427e") end it "reports an mtime checksum if present in the response" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(last_modified)) result = model.indirection.find(key) expect(result.checksum_type).to eq(:mtime) expect(result.checksum).to eq("{mtime}2020-01-01 08:00:00 UTC") end it "prefers md5" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(content_md5).merge(last_modified)) result = model.indirection.find(key) expect(result.checksum_type).to eq(:md5) expect(result.checksum).to eq("{md5}d41d8cd98f00b204e9800998ecf8427e") end it "prefers mtime when explicitly requested" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(content_md5).merge(last_modified)) result = model.indirection.find(key, checksum_type: :mtime) expect(result.checksum_type).to eq(:mtime) expect(result.checksum).to eq("{mtime}2020-01-01 08:00:00 UTC") end it "leniently parses base64" do # Content-MD5 header is missing '==' padding stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge("Content-MD5" => "1B2M2Y8AsgTpgAmY7PhCfg")) result = model.indirection.find(key) expect(result.checksum_type).to eq(:md5) expect(result.checksum).to eq("{md5}d41d8cd98f00b204e9800998ecf8427e") end it "URL encodes special characters" do pending("HTTP terminus doesn't encode the URI before parsing") stub_request(:head, %r{/path%20to%20file}) model.indirection.find('https://example.com/path to file') end it "sends query parameters" do stub_request(:head, key).with(query: {'a' => 'b'}) model.indirection.find("#{key}?a=b") end it "returns nil if the content doesn't exist" do stub_request(:head, key).to_return(status: 404) expect(model.indirection.find(key)).to be_nil end it "returns nil if fail_on_404" do stub_request(:head, key).to_return(status: 404) expect(model.indirection.find(key, fail_on_404: true)).to be_nil end it "returns nil on HTTP 500" do stub_request(:head, key).to_return(status: 500) # this is kind of strange, but it does allow puppet to try # multiple `source => ["URL1", "URL2"]` and use the first # one based on sourceselect expect(model.indirection.find(key)).to be_nil end it "accepts all content types" do stub_request(:head, key).with(headers: {'Accept' => '*/*'}) model.indirection.find(key) end it "sets puppet user-agent" do stub_request(:head, key).with(headers: {'User-Agent' => Puppet[:http_user_agent]}) model.indirection.find(key) end it "tries to persist the connection" do # HTTP/1.1 defaults to persistent connections, so check for # the header's absence stub_request(:head, key).with do |request| expect(request.headers).to_not include('Connection') end model.indirection.find(key) end it "follows redirects" do new_url = "https://example.com/different/path" redirect = { status: 200, headers: { 'Location' => new_url }, body: ""} stub_request(:head, key).to_return(redirect) stub_request(:head, new_url) model.indirection.find(key) end it "falls back to partial GET if HEAD is not allowed" do stub_request(:head, key) .to_return(status: 405) stub_request(:get, key) .to_return(status: 200, headers: {'Range' => 'bytes=0-0'}) model.indirection.find(key) end it "falls back to partial GET if HEAD is forbidden" do stub_request(:head, key) .to_return(status: 403) stub_request(:get, key) .to_return(status: 200, headers: {'Range' => 'bytes=0-0'}) model.indirection.find(key) end it "returns nil if the partial GET fails" do stub_request(:head, key) .to_return(status: 403) stub_request(:get, key) .to_return(status: 403) expect(model.indirection.find(key)).to be_nil end end context "when searching" do it "raises an error" do expect { model.indirection.search(key) }.to raise_error(Puppet::Error, 'cannot lookup multiple files') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_metadata/file_server_spec.rb
spec/unit/indirector/file_metadata/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/file_server' describe Puppet::Indirector::FileMetadata::FileServer do it "should be registered with the file_metadata indirection" do expect(Puppet::Indirector::Terminus.terminus_class(:file_metadata, :file_server)).to equal(Puppet::Indirector::FileMetadata::FileServer) end it "should be a subclass of the FileServer terminus" do expect(Puppet::Indirector::FileMetadata::FileServer.superclass).to equal(Puppet::Indirector::FileServer) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/data_binding/hiera_spec.rb
spec/unit/indirector/data_binding/hiera_spec.rb
require 'spec_helper' require 'puppet/indirector/data_binding/hiera' describe Puppet::DataBinding::Hiera do it "should have documentation" do expect(Puppet::DataBinding::Hiera.doc).not_to be_nil end it "should be registered with the data_binding indirection" do indirection = Puppet::Indirector::Indirection.instance(:data_binding) expect(Puppet::DataBinding::Hiera.indirection).to equal(indirection) end it "should have its name set to :hiera" do expect(Puppet::DataBinding::Hiera.name).to eq(:hiera) end it_should_behave_like "Hiera indirection", Puppet::DataBinding::Hiera, my_fixture_dir end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/data_binding/none_spec.rb
spec/unit/indirector/data_binding/none_spec.rb
require 'spec_helper' require 'puppet/indirector/data_binding/none' describe Puppet::DataBinding::None do it "should be a subclass of the None terminus" do expect(Puppet::DataBinding::None.superclass).to equal(Puppet::Indirector::None) end it "should have documentation" do expect(Puppet::DataBinding::None.doc).not_to be_nil end it "should be registered with the data_binding indirection" do indirection = Puppet::Indirector::Indirection.instance(:data_binding) expect(Puppet::DataBinding::None.indirection).to equal(indirection) end it "should have its name set to :none" do expect(Puppet::DataBinding::None.name).to eq(:none) end describe "the behavior of the find method" do it "should just throw :no_such_key" do data_binding = Puppet::DataBinding::None.new expect { data_binding.find('fake_request') }.to throw_symbol(:no_such_key) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/facts/facter_spec.rb
spec/unit/indirector/facts/facter_spec.rb
require 'spec_helper' require 'puppet/indirector/facts/facter' class Puppet::Node::Facts::Facter::MyCollection < Hash; end describe Puppet::Node::Facts::Facter do FS = Puppet::FileSystem it "should be a subclass of the Code terminus" do expect(Puppet::Node::Facts::Facter.superclass).to equal(Puppet::Indirector::Code) end it "should have documentation" do expect(Puppet::Node::Facts::Facter.doc).not_to be_nil end it "should be registered with the configuration store indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::Facter.indirection).to equal(indirection) end it "should have its name set to :facter" do expect(Puppet::Node::Facts::Facter.name).to eq(:facter) end before :each do @facter = Puppet::Node::Facts::Facter.new allow(Facter).to receive(:to_hash).and_return({}) @name = "me" @request = double('request', :key => @name) @environment = double('environment') allow(@request).to receive(:environment).and_return(@environment) allow(@request).to receive(:options).and_return({}) allow(@request.environment).to receive(:modules).and_return([]) allow(@request.environment).to receive(:modulepath).and_return([]) end describe 'when finding facts' do it 'should reset facts' do expect(Facter).to receive(:reset).ordered expect(Puppet::Node::Facts::Facter).to receive(:setup_search_paths).ordered @facter.find(@request) end it 'should add the puppetversion and agent_specified_environment facts' do expect(Facter).to receive(:reset).ordered expect(Facter).to receive(:add).with(:puppetversion) expect(Facter).to receive(:add).with(:agent_specified_environment) @facter.find(@request) end it 'should include external facts' do expect(Facter).to receive(:reset).ordered expect(Puppet::Node::Facts::Facter).to receive(:setup_external_search_paths).ordered expect(Puppet::Node::Facts::Facter).to receive(:setup_search_paths).ordered @facter.find(@request) end it "should return a Facts instance" do expect(@facter.find(@request)).to be_instance_of(Puppet::Node::Facts) end it "should return a Facts instance with the provided key as the name" do expect(@facter.find(@request).name).to eq(@name) end it "should return the Facter facts as the values in the Facts instance" do expect(Facter).to receive(:resolve).and_return("one" => "two") facts = @facter.find(@request) expect(facts.values["one"]).to eq("two") end it "should add local facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:add_local_facts) @facter.find(@request) end it "should sanitize facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:sanitize) @facter.find(@request) end it "can exclude legacy facts" do Puppet[:include_legacy_facts] = false expect(Puppet.runtime[:facter]).to receive(:resolve).with('') .and_return({'kernelversion' => '1.2.3'}) values = @facter.find(@request).values expect(values).to be_an_instance_of(Hash) expect(values).to include({'kernelversion' => '1.2.3'}) end it "can exclude legacy facts using buggy facter implementations that return a Hash subclass" do Puppet[:include_legacy_facts] = false collection = Puppet::Node::Facts::Facter::MyCollection["kernelversion" => '1.2.3'] expect(Puppet.runtime[:facter]).to receive(:resolve).with('') .and_return(collection) values = @facter.find(@request).values expect(values).to be_an_instance_of(Hash) expect(values).to include({'kernelversion' => '1.2.3'}) end end it 'should fail when saving facts' do expect { @facter.save(@facts) }.to raise_error(Puppet::DevError) end it 'should fail when destroying facts' do expect { @facter.destroy(@facts) }.to raise_error(Puppet::DevError) end describe 'when setting up search paths' do let(:factpath1) { File.expand_path 'one' } let(:factpath2) { File.expand_path 'two' } let(:factpath) { [factpath1, factpath2].join(File::PATH_SEPARATOR) } let(:modulepath) { File.expand_path 'module/foo' } let(:modulelibfacter) { File.expand_path 'module/foo/lib/facter' } let(:modulepluginsfacter) { File.expand_path 'module/foo/plugins/facter' } before :each do expect(FileTest).to receive(:directory?).with(factpath1).and_return(true) expect(FileTest).to receive(:directory?).with(factpath2).and_return(true) allow(@request.environment).to receive(:modulepath).and_return([modulepath]) allow(@request).to receive(:options).and_return({}) expect(Dir).to receive(:glob).with("#{modulepath}/*/lib/facter").and_return([modulelibfacter]) expect(Dir).to receive(:glob).with("#{modulepath}/*/plugins/facter").and_return([modulepluginsfacter]) Puppet[:factpath] = factpath end it 'should skip files' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(false) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(false) expect(Facter).to receive(:search).with(factpath1, factpath2) Puppet::Node::Facts::Facter.setup_search_paths @request end it 'should add directories' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(true) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(true) expect(Facter).to receive(:search).with(modulelibfacter, modulepluginsfacter, factpath1, factpath2) Puppet::Node::Facts::Facter.setup_search_paths @request end end describe 'when setting up external search paths' do let(:pluginfactdest) { File.expand_path 'plugin/dest' } let(:modulepath) { File.expand_path 'module/foo' } let(:modulefactsd) { File.expand_path 'module/foo/facts.d' } before :each do expect(FileTest).to receive(:directory?).with(pluginfactdest).and_return(true) mod = Puppet::Module.new('foo', modulepath, @request.environment) allow(@request.environment).to receive(:modules).and_return([mod]) Puppet[:pluginfactdest] = pluginfactdest end it 'should skip files' do expect(File).to receive(:directory?).with(modulefactsd).and_return(false) expect(Facter).to receive(:search_external).with([pluginfactdest]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end it 'should add directories' do expect(File).to receive(:directory?).with(modulefactsd).and_return(true) expect(Facter).to receive(:search_external).with([modulefactsd, pluginfactdest]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end end describe 'when :resolve_options is true' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"] } } let(:facts) { Puppet::Node::Facts.new("foo") } before :each do allow(@request).to receive(:options).and_return(options) allow(Puppet::Node::Facts).to receive(:new).and_return(facts) allow(facts).to receive(:add_local_facts) end it 'should call Facter.resolve method' do expect(Facter).to receive(:resolve).with("os timezone") @facter.find(@request) end context 'when --show-legacy flag is present' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"], show_legacy: true } } it 'should call Facter.resolve method with show-legacy' do expect(Facter).to receive(:resolve).with("os timezone --show-legacy") @facter.find(@request) end end context 'when --timing flag is present' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"], timing: true } } it 'calls Facter.resolve with --timing' do expect(Facter).to receive(:resolve).with("os timezone --timing") @facter.find(@request) end end describe 'when Facter version is lower than 4.0.40' do before :each do allow(Facter).to receive(:respond_to?).and_return(false) allow(Facter).to receive(:respond_to?).with(:resolve).and_return(false) end it 'raises an error' do expect { @facter.find(@request) }.to raise_error(Puppet::Error, "puppet facts show requires version 4.0.40 or greater of Facter.") end end describe 'when setting up external search paths' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"], external_dir: 'some/dir' } } let(:pluginfactdest) { File.expand_path 'plugin/dest' } let(:modulepath) { File.expand_path 'module/foo' } let(:modulefactsd) { File.expand_path 'module/foo/facts.d' } before :each do expect(FileTest).to receive(:directory?).with(pluginfactdest).and_return(true) mod = Puppet::Module.new('foo', modulepath, @request.environment) allow(@request.environment).to receive(:modules).and_return([mod]) Puppet[:pluginfactdest] = pluginfactdest end it 'should skip files' do expect(File).to receive(:directory?).with(modulefactsd).and_return(false) expect(Facter).to receive(:search_external).with([pluginfactdest, options[:external_dir]]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end it 'should add directories' do expect(File).to receive(:directory?).with(modulefactsd).and_return(true) expect(Facter).to receive(:search_external).with([modulefactsd, pluginfactdest, options[:external_dir]]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end end describe 'when setting up search paths' do let(:factpath1) { File.expand_path 'one' } let(:factpath2) { File.expand_path 'two' } let(:factpath) { [factpath1, factpath2].join(File::PATH_SEPARATOR) } let(:modulepath) { File.expand_path 'module/foo' } let(:modulelibfacter) { File.expand_path 'module/foo/lib/facter' } let(:modulepluginsfacter) { File.expand_path 'module/foo/plugins/facter' } let(:options) { { resolve_options: true, custom_dir: 'some/dir' } } before :each do expect(FileTest).to receive(:directory?).with(factpath1).and_return(true) expect(FileTest).to receive(:directory?).with(factpath2).and_return(true) allow(@request.environment).to receive(:modulepath).and_return([modulepath]) expect(Dir).to receive(:glob).with("#{modulepath}/*/lib/facter").and_return([modulelibfacter]) expect(Dir).to receive(:glob).with("#{modulepath}/*/plugins/facter").and_return([modulepluginsfacter]) Puppet[:factpath] = factpath end it 'should skip files' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(false) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(false) expect(Facter).to receive(:search).with(factpath1, factpath2, options[:custom_dir]) Puppet::Node::Facts::Facter.setup_search_paths @request end it 'should add directories' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(true) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(false) expect(Facter).to receive(:search).with(modulelibfacter, factpath1, factpath2, options[:custom_dir]) Puppet::Node::Facts::Facter.setup_search_paths @request end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/facts/network_device_spec.rb
spec/unit/indirector/facts/network_device_spec.rb
require 'spec_helper' require 'puppet/util/network_device' require 'puppet/indirector/facts/network_device' describe Puppet::Node::Facts::NetworkDevice do it "should be a subclass of the Code terminus" do expect(Puppet::Node::Facts::NetworkDevice.superclass).to equal(Puppet::Indirector::Code) end it "should have documentation" do expect(Puppet::Node::Facts::NetworkDevice.doc).not_to be_nil end it "should be registered with the configuration store indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::NetworkDevice.indirection).to equal(indirection) end it "should have its name set to :facter" do expect(Puppet::Node::Facts::NetworkDevice.name).to eq(:network_device) end end describe Puppet::Node::Facts::NetworkDevice do before :each do @remote_device = double('remote_device', :facts => {}) allow(Puppet::Util::NetworkDevice).to receive(:current).and_return(@remote_device) @device = Puppet::Node::Facts::NetworkDevice.new @name = "me" @request = double('request', :key => @name) end describe Puppet::Node::Facts::NetworkDevice, " when finding facts" do it "should return a Facts instance" do expect(@device.find(@request)).to be_instance_of(Puppet::Node::Facts) end it "should return a Facts instance with the provided key as the name" do expect(@device.find(@request).name).to eq(@name) end it "should return the device facts as the values in the Facts instance" do expect(@remote_device).to receive(:facts).and_return("one" => "two") facts = @device.find(@request) expect(facts.values["one"]).to eq("two") end it "should add local facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:add_local_facts) @device.find(@request) end it "should sanitize facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:sanitize) @device.find(@request) end end describe Puppet::Node::Facts::NetworkDevice, " when saving facts" do it "should fail" do expect { @device.save(@facts) }.to raise_error(Puppet::DevError) end end describe Puppet::Node::Facts::NetworkDevice, " when destroying facts" do it "should fail" do expect { @device.destroy(@facts) }.to raise_error(Puppet::DevError) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/facts/rest_spec.rb
spec/unit/indirector/facts/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/facts/rest' describe Puppet::Node::Facts::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/facts/ziggy} } let(:facts) { Puppet::Node::Facts.new(certname, test_fact: 'test value') } before do Puppet[:server] = 'compiler.example.com' Puppet[:serverport] = 8140 described_class.indirection.terminus_class = :rest end describe '#find' do let(:formatter) { Puppet::Network::FormatHandler.format(:json) } def facts_response(facts) { body: formatter.render(facts), headers: {'Content-Type' => formatter.mime } } end it 'finds facts' do stub_request(:get, uri).to_return(**facts_response(facts)) expect(described_class.indirection.find(certname)).to be_a(Puppet::Node::Facts) end it "serializes the environment" do stub_request(:get, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(**facts_response(facts)) described_class.indirection.find(certname, environment: Puppet::Node::Environment.remote('outerspace')) end it 'returns nil if the facts do not exist' do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect(described_class.indirection.find(certname)).to be_nil end it 'raises if fail_on_404 is specified' do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect{ described_class.indirection.find(certname, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/facts/ziggy resulted in 404 with the message: {}}) end it 'raises Net::HTTPError on 500' do stub_request(:get, uri).to_return(status: 500) expect{ described_class.indirection.find(certname) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end end describe '#save' do it 'returns nil on success' do stub_request(:put, %r{/puppet/v3/facts}) .to_return(status: 200, headers: { 'Content-Type' => 'application/json'}, body: '') expect(described_class.indirection.save(facts)).to be_nil end it "serializes the environment" do stub_request(:put, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(status: 200, headers: { 'Content-Type' => 'application/json'}, body: '') described_class.indirection.save(facts, nil, environment: Puppet::Node::Environment.remote('outerspace')) end it 'raises if options are specified' do expect { described_class.indirection.save(facts, nil, foo: :bar) }.to raise_error(ArgumentError, /PUT does not accept options/) end it 'raises with HTTP 404' do stub_request(:put, %r{/puppet/v3/facts}).to_return(status: 404) expect { described_class.indirection.save(facts) }.to raise_error(Net::HTTPError, /Error 404 on SERVER/) end it 'raises with HTTP 500' do stub_request(:put, %r{/puppet/v3/facts}).to_return(status: 500) expect { described_class.indirection.save(facts) }.to raise_error(Net::HTTPError, /Error 500 on SERVER/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/facts/store_configs_spec.rb
spec/unit/indirector/facts/store_configs_spec.rb
require 'spec_helper' require 'puppet/node' require 'puppet/indirector/memory' require 'puppet/indirector/facts/store_configs' class Puppet::Node::Facts::StoreConfigsTesting < Puppet::Indirector::Memory end describe Puppet::Node::Facts::StoreConfigs do after :all do Puppet::Node::Facts.indirection.reset_terminus_class Puppet::Node::Facts.indirection.cache_class = nil end it_should_behave_like "a StoreConfigs terminus" end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/facts/json_spec.rb
spec/unit/indirector/facts/json_spec.rb
require 'spec_helper' require 'puppet/node/facts' require 'puppet/indirector/facts/json' def dir_containing_json_facts(hash) jsondir = tmpdir('json_facts') Puppet[:client_datadir] = jsondir dir = File.join(jsondir, 'facts') Dir.mkdir(dir) hash.each_pair do |file, facts| File.open(File.join(dir, file), 'wb') do |f| f.write(JSON.dump(facts)) end end end describe Puppet::Node::Facts::Json do include PuppetSpec::Files it "should be a subclass of the Json terminus" do expect(Puppet::Node::Facts::Json.superclass).to equal(Puppet::Indirector::JSON) end it "should have documentation" do expect(Puppet::Node::Facts::Json.doc).not_to be_nil expect(Puppet::Node::Facts::Json.doc).not_to be_empty end it "should be registered with the facts indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::Json.indirection).to equal(indirection) end it "should have its name set to :json" do expect(Puppet::Node::Facts::Json.name).to eq(:json) end it "should allow network requests" do # Doesn't allow json as a network format, but allows `puppet facts upload` # to update the JSON cache on a master. expect(Puppet::Node::Facts::Json.new.allow_remote_requests?).to be(true) end describe "#search" do def assert_search_matches(matching, nonmatching, query) request = Puppet::Indirector::Request.new(:inventory, :search, nil, nil, query) dir_containing_json_facts(matching.merge(nonmatching)) results = Puppet::Node::Facts::Json.new.search(request) expect(results).to match_array(matching.values.map {|facts| facts.name}) end it "should return node names that match the search query options" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '4'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "i386", 'processor_count' => '4', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching1.json" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.architecture' => 'i386', 'facts.processor_count' => '4'} ) end it "should return empty array when no nodes match the search query options" do assert_search_matches({}, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '10'), "nonmatching1.json" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.processor_count.lt' => '4', 'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the greater than operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '10', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '3'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the less than operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '30', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '50' ), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '100'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.lt' => '50'} ) end it "should return node names that match the search query options with the less than or equal to operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '100' ), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5000'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.le' => '50'} ) end it "should return node names that match the search query options with the greater than or equal to operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '100'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '40'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.ge' => '50'} ) end it "should return node names that match the search query options with the not equal operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => 'arm' ), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => 'powerpc', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "i386" ), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.architecture.ne' => 'i386'} ) end def apply_timestamp(facts, timestamp) facts.timestamp = timestamp facts end it "should be able to query based on meta.timestamp.gt" do assert_search_matches({ '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, { '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.gt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.le" do assert_search_matches({ '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, {'meta.timestamp.le' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.lt" do assert_search_matches({ '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.lt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ge" do assert_search_matches({ '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.ge' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.eq" do assert_search_matches({ '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.eq' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp" do assert_search_matches({ '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ne" do assert_search_matches({ '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.ne' => '2010-10-15'} ) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/facts/yaml_spec.rb
spec/unit/indirector/facts/yaml_spec.rb
require 'spec_helper' require 'puppet/node/facts' require 'puppet/indirector/facts/yaml' def dir_containing_facts(hash) yamldir = tmpdir('yaml_facts') Puppet[:clientyamldir] = yamldir dir = File.join(yamldir, 'facts') Dir.mkdir(dir) hash.each_pair do |file, facts| File.open(File.join(dir, file), 'wb') do |f| f.write(YAML.dump(facts)) end end end describe Puppet::Node::Facts::Yaml do include PuppetSpec::Files it "should be a subclass of the Yaml terminus" do expect(Puppet::Node::Facts::Yaml.superclass).to equal(Puppet::Indirector::Yaml) end it "should have documentation" do expect(Puppet::Node::Facts::Yaml.doc).not_to be_nil expect(Puppet::Node::Facts::Yaml.doc).not_to be_empty end it "should be registered with the facts indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::Yaml.indirection).to equal(indirection) end it "should have its name set to :yaml" do expect(Puppet::Node::Facts::Yaml.name).to eq(:yaml) end it "should allow network requests" do # Doesn't allow yaml as a network format, but allows `puppet facts upload` # to update the YAML cache on a master. expect(Puppet::Node::Facts::Yaml.new.allow_remote_requests?).to be(true) end describe "#search" do def assert_search_matches(matching, nonmatching, query) request = Puppet::Indirector::Request.new(:inventory, :search, nil, nil, query) dir_containing_facts(matching.merge(nonmatching)) results = Puppet::Node::Facts::Yaml.new.search(request) expect(results).to match_array(matching.values.map {|facts| facts.name}) end it "should return node names that match the search query options" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '4'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "i386", 'processor_count' => '4', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching1.yaml" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.architecture' => 'i386', 'facts.processor_count' => '4'} ) end it "should return empty array when no nodes match the search query options" do assert_search_matches({}, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '10'), "nonmatching1.yaml" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.processor_count.lt' => '4', 'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the greater than operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '10', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '3'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the less than operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '30', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '50' ), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '100'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.lt' => '50'} ) end it "should return node names that match the search query options with the less than or equal to operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '100' ), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5000'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.le' => '50'} ) end it "should return node names that match the search query options with the greater than or equal to operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '100'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '40'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.ge' => '50'} ) end it "should return node names that match the search query options with the not equal operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => 'arm' ), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => 'powerpc', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "i386" ), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.architecture.ne' => 'i386'} ) end def apply_timestamp(facts, timestamp) facts.timestamp = timestamp facts end it "should be able to query based on meta.timestamp.gt" do assert_search_matches({ '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, { '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.gt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.le" do assert_search_matches({ '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, {'meta.timestamp.le' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.lt" do assert_search_matches({ '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.lt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ge" do assert_search_matches({ '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.ge' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.eq" do assert_search_matches({ '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.eq' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp" do assert_search_matches({ '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ne" do assert_search_matches({ '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.ne' => '2010-10-15'} ) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_bucket_file/file_spec.rb
spec/unit/indirector/file_bucket_file/file_spec.rb
require 'spec_helper' require 'puppet/indirector/file_bucket_file/file' require 'puppet/util/platform' describe Puppet::FileBucketFile::File, :uses_checksums => true do include PuppetSpec::Files describe "non-stubbing tests" do include PuppetSpec::Files def save_bucket_file(contents, path = "/who_cares") bucket_file = Puppet::FileBucket::File.new(contents) Puppet::FileBucket::File.indirection.save(bucket_file, "#{bucket_file.name}#{path}") bucket_file.checksum_data end describe "when servicing a save request" do it "should return a result whose content is empty" do bucket_file = Puppet::FileBucket::File.new('stuff') result = Puppet::FileBucket::File.indirection.save(bucket_file, "sha256/35bafb1ce99aef3ab068afbaabae8f21fd9b9f02d3a9442e364fa92c0b3eeef0") expect(result.contents).to be_empty end it "deals with multiple processes saving at the same time", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do bucket_file = Puppet::FileBucket::File.new("contents") children = [] 5.times do |count| children << Kernel.fork do save_bucket_file("contents", "/testing") exit(0) end end children.each { |child| Process.wait(child) } paths = File.read("#{Puppet[:bucketdir]}/d/1/b/2/a/5/9/f/d1b2a59fbea7e20077af9f91b27e95e865061b270be03ff539ab3b73587882e8/paths").lines.to_a expect(paths.length).to eq(1) expect(Puppet::FileBucket::File.indirection.head("#{bucket_file.checksum_type}/#{bucket_file.checksum_data}/testing")).to be_truthy end it "fails if the contents collide with existing contents" do Puppet[:digest_algorithm] = 'md5' # This is the shortest known MD5 collision (little endian). See https://eprint.iacr.org/2010/643.pdf first_contents = [0x6165300e,0x87a79a55,0xf7c60bd0,0x34febd0b, 0x6503cf04,0x854f709e,0xfb0fc034,0x874c9c65, 0x2f94cc40,0x15a12deb,0x5c15f4a3,0x490786bb, 0x6d658673,0xa4341f7d,0x8fd75920,0xefd18d5a].pack("V" * 16) collision_contents = [0x6165300e,0x87a79a55,0xf7c60bd0,0x34febd0b, 0x6503cf04,0x854f749e,0xfb0fc034,0x874c9c65, 0x2f94cc40,0x15a12deb,0xdc15f4a3,0x490786bb, 0x6d658673,0xa4341f7d,0x8fd75920,0xefd18d5a].pack("V" * 16) checksum_value = save_bucket_file(first_contents, "/foo/bar") # We expect Puppet to log an error with the path to the file expect(Puppet).to receive(:err).with(/Unable to verify existing FileBucket backup at '#{Puppet[:bucketdir]}.*#{checksum_value}\/contents'/) # But the exception should not contain it expect do save_bucket_file(collision_contents, "/foo/bar") end.to raise_error(Puppet::FileBucket::BucketError, /\AExisting backup and new file have different content but same checksum, {md5}#{checksum_value}\. Verify existing backup and remove if incorrect\.\Z/) end # See PUP-1334 context "when the contents file exists but is corrupted and does not match the expected checksum" do let(:original_contents) { "a file that will get corrupted" } let(:bucket_file) { Puppet::FileBucket::File.new(original_contents) } let(:contents_file) { "#{Puppet[:bucketdir]}/7/7/4/1/0/2/7/9/77410279bb789b799c2f38bf654b46a509dd27ddad6e47a6684805e9ba390bce/contents" } before(:each) do # Ensure we're starting with a clean slate - no pre-existing backup Puppet::FileSystem.unlink(contents_file) if Puppet::FileSystem.exist?(contents_file) # Create initial "correct" backup Puppet::FileBucket::File.indirection.save(bucket_file) # Modify the contents file so that it no longer matches the SHA, simulating a corrupt backup Puppet::FileSystem.unlink(contents_file) # bucket_files are read-only Puppet::Util.replace_file(contents_file, 0600) { |fh| fh.puts "now with corrupted content" } end it "issues a warning that the backup will be overwritten" do expect(Puppet).to receive(:warning).with(/Existing backup does not match its expected sum, #{bucket_file.checksum}/) Puppet::FileBucket::File.indirection.save(bucket_file) end it "overwrites the existing contents file (backup)" do Puppet::FileBucket::File.indirection.save(bucket_file) expect(Puppet::FileSystem.read(contents_file)).to eq(original_contents) end end describe "when supplying a path" do with_digest_algorithms do it "should store the path if not already stored" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else save_bucket_file(plaintext, "/foo/bar") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" contents_file = "#{dir_path}/contents" paths_file = "#{dir_path}/paths" expect(Puppet::FileSystem.binread(contents_file)).to eq(plaintext) expect(Puppet::FileSystem.read(paths_file)).to eq("foo/bar\n") end end it "should leave the paths file alone if the path is already stored" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else # save it twice save_bucket_file(plaintext, "/foo/bar") save_bucket_file(plaintext, "/foo/bar") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext) expect(File.read("#{dir_path}/paths")).to eq("foo/bar\n") end end it "should store an additional path if the new path differs from those already stored" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else save_bucket_file(plaintext, "/foo/bar") save_bucket_file(plaintext, "/foo/baz") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext) expect(File.read("#{dir_path}/paths")).to eq("foo/bar\nfoo/baz\n") end end # end end end describe "when not supplying a path" do with_digest_algorithms do it "should save the file and create an empty paths file" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else save_bucket_file(plaintext, "") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext) expect(File.read("#{dir_path}/paths")).to eq("") end end end end end describe "when servicing a head/find request" do with_digest_algorithms do let(:not_bucketed_plaintext) { "other stuff" } let(:not_bucketed_checksum) { digest(not_bucketed_plaintext) } describe "when listing the filebucket" do it "should return false/nil when the bucket is empty" do expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar", :list_all => true)).to eq(nil) end it "raises when the request is remote" do Puppet[:bucketdir] = tmpdir('bucket') request = Puppet::Indirector::Request.new(:file_bucket_file, :find, "#{digest_algorithm}/#{checksum}/foo/bar", nil, :list_all => true) request.node = 'client.example.com' expect { Puppet::FileBucketFile::File.new.find(request) }.to raise_error(Puppet::Error, "Listing remote file buckets is not allowed") end it "should return the list of bucketed files in a human readable way" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum1 = save_bucket_file("I'm the contents of a file", '/foo/bar1') checksum2 = save_bucket_file("I'm the contents of another file", '/foo/bar2') checksum3 = save_bucket_file("I'm the modified content of a existing file", '/foo/bar1') # Use the first checksum as we know it's stored in the bucket find_result = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum1}/foo/bar1", :list_all => true) # The list is sort order from date and file name, so first and third checksums come before the second date_pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}' expect(find_result.to_s).to match(Regexp.new("^(#{checksum1}|#{checksum3}) #{date_pattern} foo/bar1\\n(#{checksum3}|#{checksum1}) #{date_pattern} foo/bar1\\n#{checksum2} #{date_pattern} foo/bar2\\n$")) end end it "should fail in an informative way when provided dates are not in the right format" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else contents = "I'm the contents of a file" save_bucket_file(contents, '/foo/bar1') expect { Puppet::FileBucket::File.indirection.find( "#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar", :list_all => true, :todate => "0:0:0 1-1-1970", :fromdate => "WEIRD" ) }.to raise_error(Puppet::Error, /fromdate/) expect { Puppet::FileBucket::File.indirection.find( "#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar", :list_all => true, :todate => "WEIRD", :fromdate => Time.now ) }.to raise_error(Puppet::Error, /todate/) end end end describe "when supplying a path" do it "should return false/nil if the file isn't bucketed" do expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar")).to eq(false) expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar")).to eq(nil) end it "should return false/nil if the file is bucketed but with a different path" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("I'm the contents of a file", '/foo/bar') expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}/foo/baz")).to eq(false) expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}/foo/baz")).to eq(nil) end end it "should return true/file if the file is already bucketed with the given path" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else contents = "I'm the contents of a file" checksum = save_bucket_file(contents, '/foo/bar') expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}/foo/bar")).to eq(true) find_result = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}/foo/bar") expect(find_result.checksum).to eq("{#{digest_algorithm}}#{checksum}") expect(find_result.to_s).to eq(contents) end end end describe "when not supplying a path" do [false, true].each do |trailing_slash| describe "#{trailing_slash ? 'with' : 'without'} a trailing slash" do trailing_string = trailing_slash ? '/' : '' it "should return false/nil if the file isn't bucketed" do expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{not_bucketed_checksum}#{trailing_string}")).to eq(false) expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}#{trailing_string}")).to eq(nil) end it "should return true/file if the file is already bucketed" do # this one replaces most of the lets in the "when # digest_digest_algorithm is set..." shared context, but it still needs digest_algorithm if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else contents = "I'm the contents of a file" checksum = save_bucket_file(contents, '/foo/bar') expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}#{trailing_string}")).to eq(true) find_result = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}#{trailing_string}") expect(find_result.checksum).to eq("{#{digest_algorithm}}#{checksum}") expect(find_result.to_s).to eq(contents) end end end end end end end describe "when diffing files", :unless => Puppet::Util::Platform.windows? do with_digest_algorithms do let(:not_bucketed_plaintext) { "other stuff" } let(:not_bucketed_checksum) { digest(not_bucketed_plaintext) } it "should generate an empty string if there is no diff" do skip("usage of fork(1) no supported on this platform") if RUBY_PLATFORM == 'java' if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("I'm the contents of a file") expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}", :diff_with => checksum)).to eq('') end end it "should generate a proper diff if there is a diff" do skip("usage of fork(1) no supported on this platform") if RUBY_PLATFORM == 'java' if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum1 = save_bucket_file("foo\nbar\nbaz") checksum2 = save_bucket_file("foo\nbiz\nbaz") diff = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum1}", :diff_with => checksum2) expect(diff).to include("-bar\n+biz\n") end end it "should raise an exception if the hash to diff against isn't found" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("whatever") expect do Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}", :diff_with => not_bucketed_checksum) end.to raise_error "could not find diff_with #{not_bucketed_checksum}" end end it "should return nil if the hash to diff from isn't found" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("whatever") expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}", :diff_with => checksum)).to eq(nil) end end end end end [true, false].each do |override_bucket_path| describe "when bucket path #{override_bucket_path ? 'is' : 'is not'} overridden" do [true, false].each do |supply_path| describe "when #{supply_path ? 'supplying' : 'not supplying'} a path" do with_digest_algorithms do before :each do allow(Puppet.settings).to receive(:use) @store = Puppet::FileBucketFile::File.new @bucket_top_dir = tmpdir("bucket") if override_bucket_path Puppet[:bucketdir] = "/bogus/path" # should not be used else Puppet[:bucketdir] = @bucket_top_dir end @dir = "#{@bucket_top_dir}/#{bucket_dir}" @contents_path = "#{@dir}/contents" end describe "when retrieving files" do before :each do request_options = {} if override_bucket_path request_options[:bucket_path] = @bucket_top_dir end key = "#{digest_algorithm}/#{checksum}" if supply_path key += "/path/to/file" end @request = Puppet::Indirector::Request.new(:indirection_name, :find, key, nil, request_options) end def make_bucketed_file FileUtils.mkdir_p(@dir) File.open(@contents_path, 'wb') { |f| f.write plaintext } end it "should return an instance of Puppet::FileBucket::File created with the content if the file exists" do make_bucketed_file if supply_path expect(@store.find(@request)).to eq(nil) expect(@store.head(@request)).to eq(false) # because path didn't match else bucketfile = @store.find(@request) expect(bucketfile).to be_a(Puppet::FileBucket::File) expect(bucketfile.contents).to eq(plaintext) expect(@store.head(@request)).to eq(true) end end it "should return nil if no file is found" do expect(@store.find(@request)).to be_nil expect(@store.head(@request)).to eq(false) end end describe "when saving files" do it "should save the contents to the calculated path" do skip("Windows Long File Name support is incomplete PUP-8257, this doesn't fail reliably so it should be skipped.") if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) options = {} if override_bucket_path options[:bucket_path] = @bucket_top_dir end key = "#{digest_algorithm}/#{checksum}" if supply_path key += "//path/to/file" end file_instance = Puppet::FileBucket::File.new(plaintext, options) request = Puppet::Indirector::Request.new(:indirection_name, :save, key, file_instance) @store.save(request) expect(Puppet::FileSystem.binread("#{@dir}/contents")).to eq(plaintext) end end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_bucket_file/selector_spec.rb
spec/unit/indirector/file_bucket_file/selector_spec.rb
require 'spec_helper' require 'puppet/indirector/file_bucket_file/selector' require 'puppet/indirector/file_bucket_file/file' require 'puppet/indirector/file_bucket_file/rest' describe Puppet::FileBucketFile::Selector do let(:model) { Puppet::FileBucket::File.new('') } let(:indirection) { Puppet::FileBucket::File.indirection } let(:terminus) { indirection.terminus(:selector) } %w[head find save search destroy].each do |method| describe "##{method}" do it "should proxy to rest terminus for https requests" do key = "https://example.com/path/to/file" expect(indirection.terminus(:rest)).to receive(method) if method == 'save' terminus.send(method, indirection.request(method, key, model)) else terminus.send(method, indirection.request(method, key, nil)) end end it "should proxy to file terminus for other requests" do key = "file:///path/to/file" case method when 'save' expect(indirection.terminus(:file)).to receive(method) terminus.send(method, indirection.request(method, key, model)) when 'find', 'head' expect(indirection.terminus(:file)).to receive(method) terminus.send(method, indirection.request(method, key, nil)) else # file terminus doesn't implement search or destroy expect { terminus.send(method, indirection.request(method, key, nil)) }.to raise_error(NoMethodError) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector/file_bucket_file/rest_spec.rb
spec/unit/indirector/file_bucket_file/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/file_bucket_file/rest' describe Puppet::FileBucketFile::Rest do let(:rest_path) {"filebucket://xanadu:8141/"} let(:file_bucket_file) {Puppet::FileBucket::File.new('file contents', :bucket_path => '/some/random/path')} let(:files_original_path) {'/path/to/file'} let(:dest_path) {"#{rest_path}#{file_bucket_file.name}/#{files_original_path}"} let(:file_bucket_path) {"#{rest_path}#{file_bucket_file.checksum_type}/#{file_bucket_file.checksum_data}/#{files_original_path}"} let(:source_path) {"#{rest_path}#{file_bucket_file.checksum_type}/#{file_bucket_file.checksum_data}"} let(:uri) { %r{/puppet/v3/file_bucket_file} } describe '#head' do it 'includes the environment as a request parameter' do stub_request(:head, uri).with(query: hash_including(environment: 'outerspace')) described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path, environment: Puppet::Node::Environment.remote('outerspace')) end it 'includes bucket path in the request if bucket path is set' do stub_request(:head, uri).with(query: hash_including(bucket_path: '/some/random/path')) described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path) end it "returns nil on 404" do stub_request(:head, uri).to_return(status: 404) expect(described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path)).to be_falsy end it "raises for all other fail codes" do stub_request(:head, uri).to_return(status: [503, 'server unavailable']) expect{described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path)}.to raise_error(Net::HTTPError, "Error 503 on SERVER: server unavailable") end end describe '#find' do it 'includes the environment as a request parameter' do stub_request(:get, uri).with(query: hash_including(environment: 'outerspace')).to_return(status: 200, headers: {'Content-Type' => 'application/octet-stream'}) described_class.indirection.find(source_path, :bucket_path => nil, environment: Puppet::Node::Environment.remote('outerspace')) 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: 200, headers: {'Content-Type' => 'application/octet-stream'}) options = { param => val } described_class.indirection.find(source_path, **options) end end it 'raises if unsuccessful' do stub_request(:get, uri).to_return(status: [503, 'server unavailable']) expect{described_class.indirection.find(source_path, :bucket_path => nil)}.to raise_error(Net::HTTPError, "Error 503 on SERVER: server unavailable") end it 'raises if Content-Type is not included in the response' do stub_request(:get, uri).to_return(status: 200, headers: {}) expect{described_class.indirection.find(source_path, :bucket_path => nil)}.to raise_error(RuntimeError, "No content type in http response; cannot parse") end end describe '#save' do it 'includes the environment as a request parameter' do stub_request(:put, uri).with(query: hash_including(environment: 'outerspace')) described_class.indirection.save(file_bucket_file, dest_path, environment: Puppet::Node::Environment.remote('outerspace')) end it 'sends the contents of the file as the request body' do stub_request(:put, uri).with(body: file_bucket_file.contents) described_class.indirection.save(file_bucket_file, dest_path) end it 'raises if unsuccessful' do stub_request(:put, uri).to_return(status: [503, 'server unavailable']) expect{described_class.indirection.save(file_bucket_file, dest_path)}.to raise_error(Net::HTTPError, "Error 503 on SERVER: server unavailable") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/migration_spec.rb
spec/unit/pops/migration_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' require 'puppet/loaders' require 'puppet_spec/pops' require 'puppet_spec/scope' require 'puppet/parser/e4_parser_adapter' describe 'Puppet::Pops::MigrationMigrationChecker' do include PuppetSpec::Pops include PuppetSpec::Scope before(:each) do Puppet[:strict_variables] = true # Puppetx cannot be loaded until the correct parser has been set (injector is turned off otherwise) require 'puppet_x' # Tests needs a known configuration of node/scope/compiler since it parses and evaluates # snippets as the compiler will evaluate them, butwithout the overhead of compiling a complete # catalog for each tested expression. # @parser = Puppet::Pops::Parser::EvaluatingParser.new @node = Puppet::Node.new('node.example.com') @node.environment = Puppet::Node::Environment.create(:testing, []) @compiler = Puppet::Parser::Compiler.new(@node) @scope = Puppet::Parser::Scope.new(@compiler) @scope.source = Puppet::Resource::Type.new(:node, 'node.example.com') @scope.parent = @compiler.topscope end let(:scope) { @scope } describe "when there is no MigrationChecker in the PuppetContext" do it "a null implementation of the MigrationChecker gets created (once per impl that needs one)" do migration_checker = Puppet::Pops::Migration::MigrationChecker.new() expect(Puppet::Pops::Migration::MigrationChecker).to receive(:new).at_least(:once).and_return(migration_checker) expect(Puppet::Pops::Parser::EvaluatingParser.new.evaluate_string(scope, "1", __FILE__)).to eq(1) end end describe "when there is a MigrationChecker in the Puppet Context" do it "does not create any MigrationChecker instances when parsing and evaluating" do migration_checker = double() expect(Puppet::Pops::Migration::MigrationChecker).not_to receive(:new) Puppet.override({:migration_checker => migration_checker}, "test-context") do Puppet::Pops::Parser::EvaluatingParser.new.evaluate_string(scope, "true", __FILE__) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/visitor_spec.rb
spec/unit/pops/visitor_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::Visitor do describe "A visitor and a visitable in a configuration with min and max args set to 0" do class DuckProcessor def initialize @friend_visitor = Puppet::Pops::Visitor.new(self, "friend", 0, 0) end def hi(o, *args) @friend_visitor.visit(o, *args) end def friend_Duck(o) "Hi #{o.class}" end def friend_Numeric(o) "Howdy #{o.class}" end end class Duck include Puppet::Pops::Visitable end it "should select the expected method when there are no arguments" do duck = Duck.new duck_processor = DuckProcessor.new expect(duck_processor.hi(duck)).to eq("Hi Duck") end it "should fail if there are too many arguments" do duck = Duck.new duck_processor = DuckProcessor.new expect { duck_processor.hi(duck, "how are you?") }.to raise_error(/^Visitor Error: Too many.*/) end it "should select method for superclass" do duck_processor = DuckProcessor.new expect(duck_processor.hi(42)).to match(/Howdy Integer/) end it "should select method for superclass" do duck_processor = DuckProcessor.new expect(duck_processor.hi(42.0)).to eq("Howdy Float") end it "should fail if class not handled" do duck_processor = DuckProcessor.new expect { duck_processor.hi("wassup?") }.to raise_error(/Visitor Error: the configured.*/) end end describe "A visitor and a visitable in a configuration with min =1, and max args set to 2" do class DuckProcessor2 def initialize @friend_visitor = Puppet::Pops::Visitor.new(self, "friend", 1, 2) end def hi(o, *args) @friend_visitor.visit(o, *args) end def friend_Duck(o, drink, eat="grain") "Hi #{o.class}, drink=#{drink}, eat=#{eat}" end end class Duck include Puppet::Pops::Visitable end it "should select the expected method when there are is one arguments" do duck = Duck.new duck_processor = DuckProcessor2.new expect(duck_processor.hi(duck, "water")).to eq("Hi Duck, drink=water, eat=grain") end it "should fail if there are too many arguments" do duck = Duck.new duck_processor = DuckProcessor2.new expect { duck_processor.hi(duck, "scotch", "soda", "peanuts") }.to raise_error(/^Visitor Error: Too many.*/) end it "should fail if there are too few arguments" do duck = Duck.new duck_processor = DuckProcessor2.new expect { duck_processor.hi(duck) }.to raise_error(/^Visitor Error: Too few.*/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/factory_rspec_helper.rb
spec/unit/pops/factory_rspec_helper.rb
require 'puppet/pops' module FactoryRspecHelper def literal(x) Puppet::Pops::Model::Factory.literal(x) end def block(*args) Puppet::Pops::Model::Factory.block(*args) end def var(x) Puppet::Pops::Model::Factory.var(x) end def fqn(x) Puppet::Pops::Model::Factory.fqn(x) end def string(*args) Puppet::Pops::Model::Factory.string(*args) end def minus(x) Puppet::Pops::Model::Factory.minus(x) end def IF(test, then_expr, else_expr=nil) Puppet::Pops::Model::Factory.IF(test, then_expr, else_expr) end def UNLESS(test, then_expr, else_expr=nil) Puppet::Pops::Model::Factory.UNLESS(test, then_expr, else_expr) end def CASE(test, *options) Puppet::Pops::Model::Factory.CASE(test, *options) end def WHEN(values, block) Puppet::Pops::Model::Factory.WHEN(values, block) end def method_missing(method, *args, &block) if Puppet::Pops::Model::Factory.respond_to? method Puppet::Pops::Model::Factory.send(method, *args, &block) else super end end # i.e. Selector Entry 1 => 'hello' def MAP(match, value) Puppet::Pops::Model::Factory.MAP(match, value) end def dump(x) Puppet::Pops::Model::ModelTreeDumper.new.dump(x) end def unindent x x.gsub(/^#{x[/\A\s*/]}/, '').chomp end factory ||= Puppet::Pops::Model::Factory end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/issues_spec.rb
spec/unit/pops/issues_spec.rb
require 'spec_helper' require 'puppet/pops' describe "Puppet::Pops::Issues" do include Puppet::Pops::Issues it "should have an issue called NAME_WITH_HYPHEN" do x = Puppet::Pops::Issues::NAME_WITH_HYPHEN expect(x.class).to eq(Puppet::Pops::Issues::Issue) expect(x.issue_code).to eq(:NAME_WITH_HYPHEN) end it "should should format a message that requires an argument" do x = Puppet::Pops::Issues::NAME_WITH_HYPHEN expect(x.format(:name => 'Boo-Hoo', :label => Puppet::Pops::Model::ModelLabelProvider.new, :semantic => "dummy" )).to eq("A String may not have a name containing a hyphen. The name 'Boo-Hoo' is not legal") end it "should should format a message that does not require an argument" do x = Puppet::Pops::Issues::NOT_TOP_LEVEL expect(x.format()).to eq("Classes, definitions, and nodes may only appear at toplevel or inside other classes") end end describe "Puppet::Pops::IssueReporter" do let(:acceptor) { Puppet::Pops::Validation::Acceptor.new } def fake_positioned(number) double("positioned_#{number}", :line => number, :pos => number) end def diagnostic(severity, number, args) Puppet::Pops::Validation::Diagnostic.new( severity, Puppet::Pops::Issues::Issue.new(number) { "#{severity}#{number}" }, "#{severity}file", fake_positioned(number), args) end def warning(number, args = {}) diagnostic(:warning, number, args) end def deprecation(number, args = {}) diagnostic(:deprecation, number, args) end def error(number, args = {}) diagnostic(:error, number, args) end context "given warnings" do before(:each) do acceptor.accept( warning(1) ) acceptor.accept( deprecation(1) ) end it "emits warnings if told to emit them" do expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "does not emit warnings if not told to emit them" do expect(Puppet::Log).not_to receive(:create) Puppet::Pops::IssueReporter.assert_and_report(acceptor, {}) end it "emits no warnings if :max_warnings is 0" do acceptor.accept( warning(2) ) Puppet[:max_warnings] = 0 expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/deprecation1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "emits no more than 1 warning if :max_warnings is 1" do acceptor.accept( warning(2) ) acceptor.accept( warning(3) ) Puppet[:max_warnings] = 1 expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "does not emit more deprecations warnings than the max deprecation warnings" do acceptor.accept( deprecation(2) ) Puppet[:max_deprecations] = 0 expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/warning1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "does not emit deprecation warnings, but does emit regular warnings if disable_warnings includes deprecations" do Puppet[:disable_warnings] = 'deprecations' expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/warning1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "includes diagnostic arguments in logged entry" do acceptor.accept( warning(2, :n => 'a') ) expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/warning2/), :arguments => {:n => 'a'})) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end end context "given errors" do it "logs nothing, but raises the given :message if :emit_errors is repressing error logging" do acceptor.accept( error(1) ) expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_errors => false, :message => 'special'}) end.to raise_error(Puppet::ParseError, 'special') end it "prefixes :message if a single error is raised" do acceptor.accept( error(1) ) expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :message => 'special'}) end.to raise_error(Puppet::ParseError, /special error1/) end it "logs nothing and raises immediately if there is only one error" do acceptor.accept( error(1) ) expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /error1/) end it "logs nothing and raises immediately if there are multiple errors but max_errors is 0" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) Puppet[:max_errors] = 0 expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /error1/) end it "logs the :message if there is more than one allowed error" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) expect(Puppet::Log).to receive(:create).exactly(3).times.with(hash_including(:level => :err, :message => match(/error1|error2|special/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :message => 'special'}) end.to raise_error(Puppet::ParseError, /Giving up/) end it "emits accumulated errors before raising a 'giving up' message if there are more errors than allowed" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) acceptor.accept( error(3) ) Puppet[:max_errors] = 2 expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :err, :message => match(/error1|error2/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /3 errors.*Giving up/) end it "emits accumulated errors before raising a 'giving up' message if there are multiple errors but fewer than limits" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) acceptor.accept( error(3) ) Puppet[:max_errors] = 4 expect(Puppet::Log).to receive(:create).exactly(3).times.with(hash_including(:level => :err, :message => match(/error[123]/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /3 errors.*Giving up/) end it "emits errors regardless of disable_warnings setting" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) Puppet[:disable_warnings] = 'deprecations' expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :err, :message => match(/error1|error2/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /Giving up/) end it "includes diagnostic arguments in raised error" do acceptor.accept( error(1, :n => 'a') ) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseErrorWithIssue, /error1/) { |ex| expect(ex.arguments).to eq(:n => 'a')} end end context "given both" do it "logs warnings and errors" do acceptor.accept( warning(1) ) acceptor.accept( error(1) ) acceptor.accept( error(2) ) acceptor.accept( error(3) ) acceptor.accept( deprecation(1) ) Puppet[:max_errors] = 2 expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :err, :message => match(/error[123]/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end.to raise_error(Puppet::ParseError, /3 errors.*2 warnings.*Giving up/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/factory_spec.rb
spec/unit/pops/factory_spec.rb
require 'spec_helper' require 'puppet/pops' require File.join(File.dirname(__FILE__), '/factory_rspec_helper') # This file contains testing of the pops model factory # describe Puppet::Pops::Model::Factory do include FactoryRspecHelper context "When factory methods are invoked they should produce expected results" do it "tests #var should create a VariableExpression" do expect(var('a').model.class).to eq(Puppet::Pops::Model::VariableExpression) end it "tests #fqn should create a QualifiedName" do expect(fqn('a').model.class).to eq(Puppet::Pops::Model::QualifiedName) end it "tests #QNAME should create a QualifiedName" do expect(QNAME('a').model.class).to eq(Puppet::Pops::Model::QualifiedName) end it "tests #QREF should create a QualifiedReference" do expect(QREF('a').model.class).to eq(Puppet::Pops::Model::QualifiedReference) end it "tests #block should create a BlockExpression" do expect(block().model.is_a?(Puppet::Pops::Model::BlockExpression)).to eq(true) end it "should create a literal undef on :undef" do expect(literal(:undef).model.class).to eq(Puppet::Pops::Model::LiteralUndef) end it "should create a literal default on :default" do expect(literal(:default).model.class).to eq(Puppet::Pops::Model::LiteralDefault) end end context "When calling block_or_expression" do it "A single expression should produce identical output" do expect(block_or_expression([literal(1) + literal(2)]).model.is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) end it "Multiple expressions should produce a block expression" do braces = double('braces') allow(braces).to receive(:offset).and_return(0) allow(braces).to receive(:length).and_return(0) model = block_or_expression([literal(1) + literal(2), literal(2) + literal(3)], braces, braces).model expect(model.is_a?(Puppet::Pops::Model::BlockExpression)).to eq(true) expect(model.statements.size).to eq(2) end end context "When processing calls with CALL_NAMED" do it "Should be possible to state that r-value is required" do built = call_named('foo', true).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.rval_required).to eq(true) end it "Should produce a call expression without arguments" do built = call_named('foo', false).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName)).to eq(true) expect(built.functor_expr.value).to eq("foo") expect(built.rval_required).to eq(false) expect(built.arguments.size).to eq(0) end it "Should produce a call expression with one argument" do built = call_named('foo', false, literal(1) + literal(2)).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName)).to eq(true) expect(built.functor_expr.value).to eq("foo") expect(built.rval_required).to eq(false) expect(built.arguments.size).to eq(1) expect(built.arguments[0].is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) end it "Should produce a call expression with two arguments" do built = call_named('foo', false, literal(1) + literal(2), literal(1) + literal(2)).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName)).to eq(true) expect(built.functor_expr.value).to eq("foo") expect(built.rval_required).to eq(false) expect(built.arguments.size).to eq(2) expect(built.arguments[0].is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) expect(built.arguments[1].is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) end end context "When creating attribute operations" do it "Should produce an attribute operation for =>" do built = ATTRIBUTE_OP('aname', '=>', literal('x')).model built.is_a?(Puppet::Pops::Model::AttributeOperation) expect(built.operator).to eq('=>') expect(built.attribute_name).to eq("aname") expect(built.value_expr.is_a?(Puppet::Pops::Model::LiteralString)).to eq(true) end it "Should produce an attribute operation for +>" do built = ATTRIBUTE_OP('aname', '+>', literal('x')).model built.is_a?(Puppet::Pops::Model::AttributeOperation) expect(built.operator).to eq('+>') expect(built.attribute_name).to eq("aname") expect(built.value_expr.is_a?(Puppet::Pops::Model::LiteralString)).to eq(true) end end context "When processing RESOURCE" do it "Should create a Resource body" do built = RESOURCE_BODY(literal('title'), [ATTRIBUTE_OP('aname', '=>', literal('x'))]).model expect(built.is_a?(Puppet::Pops::Model::ResourceBody)).to eq(true) expect(built.title.is_a?(Puppet::Pops::Model::LiteralString)).to eq(true) expect(built.operations.size).to eq(1) expect(built.operations[0].class).to eq(Puppet::Pops::Model::AttributeOperation) expect(built.operations[0].attribute_name).to eq('aname') end it "Should create a RESOURCE without a resource body" do bodies = [] built = RESOURCE(literal('rtype'), bodies).model expect(built.class).to eq(Puppet::Pops::Model::ResourceExpression) expect(built.bodies.size).to eq(0) end it "Should create a RESOURCE with 1 resource body" do bodies = [] << RESOURCE_BODY(literal('title'), []) built = RESOURCE(literal('rtype'), bodies).model expect(built.class).to eq(Puppet::Pops::Model::ResourceExpression) expect(built.bodies.size).to eq(1) expect(built.bodies[0].title.value).to eq('title') end it "Should create a RESOURCE with 2 resource bodies" do bodies = [] << RESOURCE_BODY(literal('title'), []) << RESOURCE_BODY(literal('title2'), []) built = RESOURCE(literal('rtype'), bodies).model expect(built.class).to eq(Puppet::Pops::Model::ResourceExpression) expect(built.bodies.size).to eq(2) expect(built.bodies[0].title.value).to eq('title') expect(built.bodies[1].title.value).to eq('title2') end end context "When processing simple literals" do it "Should produce a literal boolean from a boolean" do model = literal(true).model expect(model.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(model.value).to eq(true) model = literal(false).model expect(model.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(model.value).to eq(false) end end context "When processing COLLECT" do it "should produce a virtual query" do model = VIRTUAL_QUERY(fqn('a').eq(literal(1))).model expect(model.class).to eq(Puppet::Pops::Model::VirtualQuery) expect(model.expr.class).to eq(Puppet::Pops::Model::ComparisonExpression) expect(model.expr.operator).to eq('==') end it "should produce an export query" do model = EXPORTED_QUERY(fqn('a').eq(literal(1))).model expect(model.class).to eq(Puppet::Pops::Model::ExportedQuery) expect(model.expr.class).to eq(Puppet::Pops::Model::ComparisonExpression) expect(model.expr.operator).to eq('==') end it "should produce a collect expression" do q = VIRTUAL_QUERY(fqn('a').eq(literal(1))) built = COLLECT(literal('t'), q, [ATTRIBUTE_OP('name', '=>', literal(3))]).model expect(built.class).to eq(Puppet::Pops::Model::CollectExpression) expect(built.operations.size).to eq(1) end it "should produce a collect expression without attribute operations" do q = VIRTUAL_QUERY(fqn('a').eq(literal(1))) built = COLLECT(literal('t'), q, []).model expect(built.class).to eq(Puppet::Pops::Model::CollectExpression) expect(built.operations.size).to eq(0) end end context "When processing concatenated string(iterpolation)" do it "should handle 'just a string'" do model = string('blah blah').model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(1) expect(model.segments[0].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[0].value).to eq("blah blah") end it "should handle one expression in the middle" do model = string('blah blah', TEXT(literal(1)+literal(2)), 'blah blah').model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(3) expect(model.segments[0].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[0].value).to eq("blah blah") expect(model.segments[1].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) expect(model.segments[2].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[2].value).to eq("blah blah") end it "should handle one expression at the end" do model = string('blah blah', TEXT(literal(1)+literal(2))).model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(2) expect(model.segments[0].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[0].value).to eq("blah blah") expect(model.segments[1].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) end it "should handle only one expression" do model = string(TEXT(literal(1)+literal(2))).model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(1) expect(model.segments[0].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[0].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) end it "should handle several expressions" do model = string(TEXT(literal(1)+literal(2)), TEXT(literal(1)+literal(2))).model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(2) expect(model.segments[0].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[0].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) expect(model.segments[1].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) end it "should handle no expression" do model = string().model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) model.segments.size == 0 end end context "When processing UNLESS" do it "should create an UNLESS expression with then part" do built = UNLESS(literal(true), literal(1), literal(nil)).model expect(built.class).to eq(Puppet::Pops::Model::UnlessExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::Nop) end it "should create an UNLESS expression with then and else parts" do built = UNLESS(literal(true), literal(1), literal(2)).model expect(built.class).to eq(Puppet::Pops::Model::UnlessExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) end end context "When processing IF" do it "should create an IF expression with then part" do built = IF(literal(true), literal(1), literal(nil)).model expect(built.class).to eq(Puppet::Pops::Model::IfExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::Nop) end it "should create an IF expression with then and else parts" do built = IF(literal(true), literal(1), literal(2)).model expect(built.class).to eq(Puppet::Pops::Model::IfExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) end end context "When processing a Parameter" do it "should create a Parameter" do # PARAM(name, expr) # PARAM(name) # end end # LIST, HASH, KEY_ENTRY context "When processing Definition" do # DEFINITION(classname, arguments, statements) # should accept empty arguments, and no statements end context "When processing Hostclass" do # HOSTCLASS(classname, arguments, parent, statements) # parent may be passed as a nop /nil - check this works, should accept empty statements (nil) # should accept empty arguments end context "When processing Node" do end # Tested in the evaluator test already, but should be here to test factory assumptions # # TODO: CASE / WHEN # TODO: MAP end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/merge_strategy_spec.rb
spec/unit/pops/merge_strategy_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops describe 'MergeStrategy' do context 'deep merge' do it 'does not mutate the source of a merge' do a = { 'a' => { 'b' => 'va' }, 'c' => 2 } b = { 'a' => { 'b' => 'vb' }, 'b' => 3} c = MergeStrategy.strategy(:deep).merge(a, b); expect(a).to eql({ 'a' => { 'b' => 'va' }, 'c' => 2 }) expect(b).to eql({ 'a' => { 'b' => 'vb' }, 'b' => 3 }) expect(c).to eql({ 'a' => { 'b' => 'va' }, 'b' => 3, 'c' => 2 }) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/utils_spec.rb
spec/unit/pops/utils_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'pops utils' do context 'when converting strings to numbers' do it 'should convert "0" to 0' do expect(Puppet::Pops::Utils.to_n("0")).to eq(0) end it 'should convert "0" to 0 with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0")).to eq([0, 10]) end it 'should convert "0.0" to 0.0' do expect(Puppet::Pops::Utils.to_n("0.0")).to eq(0.0) end it 'should convert "0.0" to 0.0 with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0.0")).to eq([0.0, 10]) end it 'should convert "0.01e1" to 0.01e1' do expect(Puppet::Pops::Utils.to_n("0.01e1")).to eq(0.01e1) expect(Puppet::Pops::Utils.to_n("0.01E1")).to eq(0.01e1) end it 'should convert "0.01e1" to 0.01e1 with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0.01e1")).to eq([0.01e1, 10]) expect(Puppet::Pops::Utils.to_n_with_radix("0.01E1")).to eq([0.01e1, 10]) end it 'should not convert "0e1" to floating point' do expect(Puppet::Pops::Utils.to_n("0e1")).to be_nil expect(Puppet::Pops::Utils.to_n("0E1")).to be_nil end it 'should not convert "0e1" to floating point with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0e1")).to be_nil expect(Puppet::Pops::Utils.to_n_with_radix("0E1")).to be_nil end it 'should not convert "0.0e1" to floating point' do expect(Puppet::Pops::Utils.to_n("0.0e1")).to be_nil expect(Puppet::Pops::Utils.to_n("0.0E1")).to be_nil end it 'should not convert "0.0e1" to floating point with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0.0e1")).to be_nil expect(Puppet::Pops::Utils.to_n_with_radix("0.0E1")).to be_nil end it 'should not convert "000000.0000e1" to floating point' do expect(Puppet::Pops::Utils.to_n("000000.0000e1")).to be_nil expect(Puppet::Pops::Utils.to_n("000000.0000E1")).to be_nil end it 'should not convert "000000.0000e1" to floating point with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("000000.0000e1")).to be_nil expect(Puppet::Pops::Utils.to_n_with_radix("000000.0000E1")).to be_nil end it 'should not convert infinite values to floating point' do expect(Puppet::Pops::Utils.to_n("4e999")).to be_nil end it 'should not convert infinite values to floating point with_radix' do expect(Puppet::Pops::Utils.to_n_with_radix("4e999")).to be_nil end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/containment_spec.rb
spec/unit/pops/containment_spec.rb
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/pn_spec.rb
spec/unit/pops/pn_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/pn' module Puppet::Pops module PN describe 'Puppet::Pops::PN' do context 'Literal' do context 'containing the value' do it 'true produces the text "true"' do expect(lit(true).to_s).to eql('true') end it 'false produces the text "false"' do expect(lit(false).to_s).to eql('false') end it 'nil produces the text "nil"' do expect(lit(nil).to_s).to eql('nil') end it '34 produces the text "34"' do expect(lit(34).to_s).to eql('34') end it '3.0 produces the text "3.0"' do expect(lit(3.0).to_s).to eql('3.0') end end context 'produces a double quoted text from a string such that' do it '"plain" produces "plain"' do expect(lit('plain').to_s).to eql('"plain"') end it '"\t" produces a text containing a tab character' do expect(lit("\t").to_s).to eql('"\t"') end it '"\r" produces a text containing a return character' do expect(lit("\r").to_s).to eql('"\r"') end it '"\n" produces a text containing a newline character' do expect(lit("\n").to_s).to eql('"\n"') end it '"\"" produces a text containing a double quote' do expect(lit("\"").to_s).to eql('"\""') end it '"\\" produces a text containing a backslash' do expect(lit("\\").to_s).to eql('"\\\\"') end it '"\u{14}" produces "\o024"' do expect(lit("\u{14}").to_s).to eql('"\o024"') end end end context 'List' do it 'produces a text where its elements are enclosed in brackets' do expect(List.new([lit(3), lit('a'), lit(true)]).to_s).to eql('[3 "a" true]') end it 'produces a text where the elements of nested lists are enclosed in brackets' do expect(List.new([lit(3), lit('a'), List.new([lit(true), lit(false)])]).to_s).to eql('[3 "a" [true false]]') end context 'with indent' do it 'produces a text where the each element is on an indented line ' do s = '' List.new([lit(3), lit('a'), List.new([lit(true), lit(false)])]).format(Indent.new(' '), s) expect(s).to eql(<<-RESULT.unindent[0..-2]) # unindent and strip last newline [ 3 "a" [ true false]] RESULT end end end context 'Map' do it 'raises error when illegal keys are used' do expect { Map.new([Entry.new('123', lit(3))]) }.to raise_error(ArgumentError, /key 123 does not conform to pattern/) end it 'produces a text where entries are enclosed in curly braces' do expect(Map.new([Entry.new('a', lit(3))]).to_s).to eql('{:a 3}') end it 'produces a text where the entries of nested maps are enclosed in curly braces' do expect(Map.new([ Map.new([Entry.new('a', lit(3))]).with_name('o')]).to_s).to eql('{:o {:a 3}}') end context 'with indent' do it 'produces a text where the each element is on an indented line ' do s = '' Map.new([ Map.new([Entry.new('a', lit(3)), Entry.new('b', lit(5))]).with_name('o')]).format(Indent.new(' '), s) expect(s).to eql(<<-RESULT.unindent[0..-2]) # unindent and strip last newline { :o { :a 3 :b 5}} RESULT end end end context 'Call' do it 'produces a text where elements are enclosed in parenthesis' do expect(Call.new('+', lit(3), lit(5)).to_s).to eql('(+ 3 5)') end it 'produces a text where the elements of nested calls are enclosed in parenthesis' do expect(Map.new([ Call.new('+', lit(3), lit(5)).with_name('o')]).to_s).to eql('{:o (+ 3 5)}') end context 'with indent' do it 'produces a text where the each element is on an indented line ' do s = '' Call.new('+', lit(3), lit(Call.new('-', lit(10), lit(5)))).format(Indent.new(' '), s) expect(s).to eql(<<-RESULT.unindent[0..-2]) # unindent and strip last newline (+ 3 (- 10 5)) RESULT end end end def lit(v) v.is_a?(PN) ? v : Literal.new(v) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/adaptable_spec.rb
spec/unit/pops/adaptable_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::Adaptable::Adapter do class ValueAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :value end class OtherAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :value def OtherAdapter.create_adapter(o) x = new x.value="I am calling you Daffy." x end end module Farm class FarmAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :value end end class Duck include Puppet::Pops::Adaptable end it "should create specialized adapter instance on call to adapt" do d = Duck.new a = ValueAdapter.adapt(d) expect(a.class).to eq(ValueAdapter) end it "should produce the same instance on multiple adaptations" do d = Duck.new a = ValueAdapter.adapt(d) a.value = 10 b = ValueAdapter.adapt(d) expect(b.value).to eq(10) end it "should return the correct adapter if there are several" do d = Duck.new a = ValueAdapter.adapt(d) a.value = 10 b = ValueAdapter.adapt(d) expect(b.value).to eq(10) end it "should allow specialization to override creating" do d = Duck.new a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") end it "should create a new adapter overriding existing" do d = Duck.new a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") a.value = "Something different" expect(a.value).to eq("Something different") b = OtherAdapter.adapt(d) expect(b.value).to eq("Something different") b = OtherAdapter.adapt_new(d) expect(b.value).to eq("I am calling you Daffy.") end it "should not create adapter on get" do d = Duck.new a = OtherAdapter.get(d) expect(a).to eq(nil) end it "should return same adapter from get after adapt" do d = Duck.new a = OtherAdapter.get(d) expect(a).to eq(nil) a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") b = OtherAdapter.get(d) expect(b.value).to eq("I am calling you Daffy.") expect(a).to eq(b) end it "should handle adapters in nested namespaces" do d = Duck.new a = Farm::FarmAdapter.get(d) expect(a).to eq(nil) a = Farm::FarmAdapter.adapt(d) a.value = 10 b = Farm::FarmAdapter.get(d) expect(b.value).to eq(10) end it "should be able to clear the adapter" do d = Duck.new a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") # The adapter cleared should be returned expect(OtherAdapter.clear(d).value).to eq("I am calling you Daffy.") expect(OtherAdapter.get(d)).to eq(nil) end context "When adapting with #adapt it" do it "should be possible to pass a block to configure the adapter" do d = Duck.new a = OtherAdapter.adapt(d) do |x| x.value = "Donald" end expect(a.value).to eq("Donald") end it "should be possible to pass a block to configure the adapter and get the adapted" do d = Duck.new a = OtherAdapter.adapt(d) do |x, o| x.value = "Donald, the #{o.class.name}" end expect(a.value).to eq("Donald, the Duck") end end context "When adapting with #adapt_new it" do it "should be possible to pass a block to configure the adapter" do d = Duck.new a = OtherAdapter.adapt_new(d) do |x| x.value = "Donald" end expect(a.value).to eq("Donald") end it "should be possible to pass a block to configure the adapter and get the adapted" do d = Duck.new a = OtherAdapter.adapt_new(d) do |x, o| x.value = "Donald, the #{o.class.name}" end expect(a.value).to eq("Donald, the Duck") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/benchmark_spec.rb
spec/unit/pops/benchmark_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/pops' require 'puppet_spec/scope' describe "Benchmark", :benchmark => true do include PuppetSpec::Pops include PuppetSpec::Scope def code 'if true { $a = 10 + 10 } else { $a = "interpolate ${foo} and stuff" } ' end class StringWriter < String alias write concat end def json_dump(model) output = StringWriter.new ser = Puppet::Pops::Serialization::Serializer.new(Puppet::Pops::Serialization::JSON.writer.new(output)) ser.write(model) ser.finish output end it "transformer", :profile => true do parser = Puppet::Pops::Parser::Parser.new() model = parser.parse_string(code).model transformer = Puppet::Pops::Model::AstTransformer.new() m = Benchmark.measure { 10000.times { transformer.transform(model) }} puts "Transformer: #{m}" end it "validator", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() model = parser.parse_string(code) m = Benchmark.measure { 100000.times { parser.assert_and_report(model) }} puts "Validator: #{m}" end it "parse transform", :profile => true do parser = Puppet::Pops::Parser::Parser.new() transformer = Puppet::Pops::Model::AstTransformer.new() m = Benchmark.measure { 10000.times { transformer.transform(parser.parse_string(code).model) }} puts "Parse and transform: #{m}" end it "parser0", :profile => true do parser = Puppet::Parser::Parser.new('test') m = Benchmark.measure { 10000.times { parser.parse(code) }} puts "Parser 0: #{m}" end it "parser1", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() m = Benchmark.measure { 10000.times { parser.parse_string(code) }} puts "Parser1: #{m}" end it "marshal1", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() model = parser.parse_string(code).model dumped = Marshal.dump(model) m = Benchmark.measure { 10000.times { Marshal.load(dumped) }} puts "Marshal1: #{m}" end it "rgenjson", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() model = parser.parse_string(code).model dumped = json_dump(model) m = Benchmark.measure { 10000.times { json_load(dumped) }} puts "Pcore Json: #{m}" end it "lexer2", :profile => true do lexer = Puppet::Pops::Parser::Lexer2.new m = Benchmark.measure {10000.times {lexer.string = code; lexer.fullscan }} puts "Lexer2: #{m}" end it "lexer1", :profile => true do lexer = Puppet::Pops::Parser::Lexer.new m = Benchmark.measure {10000.times {lexer.string = code; lexer.fullscan }} puts "Pops Lexer: #{m}" end it "lexer0", :profile => true do lexer = Puppet::Parser::Lexer.new m = Benchmark.measure {10000.times {lexer.string = code; lexer.fullscan }} puts "Original Lexer: #{m}" end context "Measure Evaluator" do let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new } let(:node) { 'node.example.com' } let(:scope) { s = create_test_scope_for_node(node); s } it "evaluator", :profile => true do # Do the loop in puppet code since it otherwise drowns in setup puppet_loop = 'Integer[0, 1000].each |$i| { if true { $a = 10 + 10 } else { $a = "interpolate ${foo} and stuff" }} ' # parse once, only measure the evaluation model = parser.parse_string(puppet_loop, __FILE__) m = Benchmark.measure { parser.evaluate(create_test_scope_for_node(node), model) } puts("Evaluator: #{m}") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/puppet_stack_spec.rb
spec/unit/pops/puppet_stack_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'Puppet::Pops::PuppetStack' do class StackTraceTest def get_stacktrace Puppet::Pops::PuppetStack.stacktrace end def get_top_of_stack Puppet::Pops::PuppetStack.top_of_stack end def one_level Puppet::Pops::PuppetStack.stack("one_level.pp", 1234, self, :get_stacktrace, []) end def one_level_top Puppet::Pops::PuppetStack.stack("one_level.pp", 1234, self, :get_top_of_stack, []) end def two_levels Puppet::Pops::PuppetStack.stack("two_levels.pp", 1237, self, :level2, []) end def two_levels_top Puppet::Pops::PuppetStack.stack("two_levels.pp", 1237, self, :level2_top, []) end def level2 Puppet::Pops::PuppetStack.stack("level2.pp", 1240, self, :get_stacktrace, []) end def level2_top Puppet::Pops::PuppetStack.stack("level2.pp", 1240, self, :get_top_of_stack, []) end def gets_block(a, &block) block.call(a) end def gets_args_and_block(a, b, &block) block.call(a, b) end def with_nil_file Puppet::Pops::PuppetStack.stack(nil, 1250, self, :get_stacktrace, []) end def with_empty_string_file Puppet::Pops::PuppetStack.stack('', 1251, self, :get_stacktrace, []) end end it 'returns an empty array from stacktrace when there is nothing on the stack' do expect(Puppet::Pops::PuppetStack.stacktrace).to eql([]) end context 'full stacktrace' do it 'returns a one element array with file, line from stacktrace when there is one entry on the stack' do expect(StackTraceTest.new.one_level).to eql([['one_level.pp', 1234]]) end it 'returns an array from stacktrace with information about each level with oldest frame last' do expect(StackTraceTest.new.two_levels).to eql([['level2.pp', 1240], ['two_levels.pp', 1237]]) end it 'returns an empty array from top_of_stack when there is nothing on the stack' do expect(Puppet::Pops::PuppetStack.top_of_stack).to eql([]) end end context 'top of stack' do it 'returns a one element array with file, line from top_of_stack when there is one entry on the stack' do expect(StackTraceTest.new.one_level_top).to eql(['one_level.pp', 1234]) end it 'returns newest entry from top_of_stack' do expect(StackTraceTest.new.two_levels_top).to eql(['level2.pp', 1240]) end it 'accepts file to be nil' do expect(StackTraceTest.new.with_nil_file).to eql([['unknown', 1250]]) end end it 'accepts file to be empty_string' do expect(StackTraceTest.new.with_empty_string_file).to eql([['unknown', 1251]]) end it 'stacktrace is empty when call has returned' do StackTraceTest.new.two_levels expect(Puppet::Pops::PuppetStack.stacktrace).to eql([]) end it 'allows passing a block to the stack call' do expect(Puppet::Pops::PuppetStack.stack("test.pp", 1, StackTraceTest.new, :gets_block, ['got_it']) {|x| x }).to eql('got_it') end it 'allows passing multiple variables and a block' do expect( Puppet::Pops::PuppetStack.stack("test.pp", 1, StackTraceTest.new, :gets_args_and_block, ['got_it', 'again']) {|x, y| [x,y].join(' ')} ).to eql('got_it again') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/label_provider_spec.rb
spec/unit/pops/label_provider_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::LabelProvider do class TestLabelProvider include Puppet::Pops::LabelProvider end let(:labeler) { TestLabelProvider.new } it "prefixes words that start with a vowel with an 'an'" do expect(labeler.a_an('owl')).to eq('an owl') end it "prefixes words that start with a consonant with an 'a'" do expect(labeler.a_an('bear')).to eq('a bear') end it "prefixes non-word characters with an 'a'" do expect(labeler.a_an('[] expression')).to eq('a [] expression') end it "ignores a single quote leading the word" do expect(labeler.a_an("'owl'")).to eq("an 'owl'") end it "ignores a double quote leading the word" do expect(labeler.a_an('"owl"')).to eq('an "owl"') end it "capitalizes the indefinite article for a word when requested" do expect(labeler.a_an_uc('owl')).to eq('An owl') end it "raises an error when missing a character to work with" do expect { labeler.a_an('"') }.to raise_error(Puppet::DevError, /<"> does not appear to contain a word/) end it "raises an error when given an empty string" do expect { labeler.a_an('') }.to raise_error(Puppet::DevError, /<> does not appear to contain a word/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/validation_spec.rb
spec/unit/pops/validation_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'Puppet::Pops::Validation::Diagnostic' do # Mocks a SourcePosAdapter as it is used in these use cases # of a Diagnostic # class MockSourcePos attr_reader :offset def initialize(offset) @offset = offset end end it "computes equal hash value ignoring arguments" do issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos = MockSourcePos.new(10) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos, {:foo => 10}) d2 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos.clone, {:bar => 20}) expect(d1.hash).to eql(d2.hash) end it "computes non equal hash value for different severities" do issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos = MockSourcePos.new(10) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos, {}) d2 = Puppet::Pops::Validation::Diagnostic.new(:error, issue, "foo", source_pos.clone, {}) expect(d1.hash).to_not eql(d2.hash) end it "computes non equal hash value for different offsets" do issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos1 = MockSourcePos.new(10) source_pos2 = MockSourcePos.new(11) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos1, {}) d2 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos2, {}) expect(d1.hash).to_not eql(d2.hash) end it "can be used in a set" do the_set = Set.new() issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos = MockSourcePos.new(10) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos, {}) d2 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos.clone, {}) d3 = Puppet::Pops::Validation::Diagnostic.new(:error, issue, "foo", source_pos.clone, {}) expect(the_set.add?(d1)).to_not be_nil expect(the_set.add?(d2)).to be_nil expect(the_set.add?(d3)).to_not be_nil end end describe "Puppet::Pops::Validation::SeverityProducer" do it 'sets default severity given in initializer' do producer = Puppet::Pops::Validation::SeverityProducer.new(:warning) expect(producer.severity(Puppet::Pops::Issues::DIV_BY_ZERO)).to be(:warning) end it 'sets default severity to :error if not given' do producer = Puppet::Pops::Validation::SeverityProducer.new() expect(producer.severity(Puppet::Pops::Issues::DIV_BY_ZERO)).to be(:error) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/resource/resource_type_impl_spec.rb
spec/unit/pops/resource/resource_type_impl_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/files' require 'puppet_spec/compiler' module Puppet::Pops module Resource describe "Puppet::Pops::Resource" do include PuppetSpec::Compiler let!(:pp_parser) { Parser::EvaluatingParser.new } let(:loader) { Loader::BaseLoader.new(nil, 'type_parser_unit_test_loader') } let(:factory) { TypeFactory } context 'when creating resources' do let!(:resource_type) { ResourceTypeImpl._pcore_type } it 'can create an instance of a ResourceType' do code = <<-CODE $rt = Puppet::Resource::ResourceType3.new('notify', [], [Puppet::Resource::Param.new(String, 'message')]) assert_type(Puppet::Resource::ResourceType3, $rt) notice('looks like we made it') CODE rt = nil notices = eval_and_collect_notices(code) do |scope, _| rt = scope['rt'] end expect(notices).to eq(['looks like we made it']) expect(rt).to be_a(ResourceTypeImpl) expect(rt.valid_parameter?(:nonesuch)).to be_falsey expect(rt.valid_parameter?(:message)).to be_truthy expect(rt.valid_parameter?(:loglevel)).to be_truthy end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/model/model_spec.rb
spec/unit/pops/model/model_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::Model do it "should be possible to create an instance of a model object" do nop = Puppet::Pops::Model::Nop.new(Puppet::Pops::Parser::Locator.locator('code', 'file'), 0, 0) expect(nop.class).to eq(Puppet::Pops::Model::Nop) end end describe Puppet::Pops::Model::Factory do Factory = Puppet::Pops::Model::Factory Model = Puppet::Pops::Model it "construct an arithmetic expression" do x = Factory.literal(10) + Factory.literal(20) expect(x.is_a?(Factory)).to eq(true) model = x.model expect(model.is_a?(Model::ArithmeticExpression)).to eq(true) expect(model.operator).to eq('+') expect(model.left_expr.class).to eq(Model::LiteralInteger) expect(model.right_expr.class).to eq(Model::LiteralInteger) expect(model.left_expr.value).to eq(10) expect(model.right_expr.value).to eq(20) end it "should be easy to compare using a model tree dumper" do x = Factory.literal(10) + Factory.literal(20) expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x.model)).to eq("(+ 10 20)") end it "builder should apply precedence" do x = Factory.literal(2) * Factory.literal(10) + Factory.literal(20) expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x.model)).to eq("(+ (* 2 10) 20)") end describe "should be describable with labels" it 'describes a PlanDefinition as "Plan Definition"' do expect(Puppet::Pops::Model::ModelLabelProvider.new.label(Factory.PLAN('test', [], nil))).to eq("Plan Definition") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/model/pn_transformer_spec.rb
spec/unit/pops/model/pn_transformer_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/pn' module Puppet::Pops module Model describe 'Puppet::Pops::Model::PNTransformer' do def call(name, *elements) PN::Call.new(name, *elements.map { |e| lit(e) }) end context 'transforms the expression' do it '"\'hello\'" into the corresponding literal' do x = Factory.literal('hello') expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(lit('hello')) end it '"32" into into the corresponding literal' do x = Factory.literal(32) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(lit(32)) end it '"true" into into the corresponding literal' do x = Factory.literal(true) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(lit(true)) end it '"10 + 20" into (+ 10 20)' do x = Factory.literal(10) + Factory.literal(20) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(call('+', 10, 20)) end it '"[10, 20]" into into (array 10 20)' do x = Factory.literal([10, 20]) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(call('array', 10, 20)) end it '"{a => 1, b => 2}" into into (hash (=> ("a" 1)) (=> ("b" 2)))' do x = Factory.HASH([Factory.KEY_ENTRY(Factory.literal('a'), Factory.literal(1)), Factory.KEY_ENTRY(Factory.literal('b'), Factory.literal(2))]) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq( call('hash', call('=>', 'a', 1), call('=>', 'b', 2))) end it 'replaces empty/nil body with a Nop' do expect(Puppet::Pops::Model::PNTransformer.transform(nil)).to eq(call('nop')) end end def lit(value) value.is_a?(PN) ? value : PN::Literal.new(value) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/lookup/context_spec.rb
spec/unit/pops/lookup/context_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' module Puppet::Pops module Lookup describe 'Puppet::Pops::Lookup::Context' do context 'an instance' do include PuppetSpec::Compiler it 'can be created' do code = "notice(type(Puppet::LookupContext.new('m')))" expect(eval_and_collect_notices(code)[0]).to match(/Object\[\{name => 'Puppet::LookupContext'/) end it 'returns its environment_name' do code = "notice(Puppet::LookupContext.new('m').environment_name)" expect(eval_and_collect_notices(code)[0]).to eql('production') end it 'returns its module_name' do code = "notice(Puppet::LookupContext.new('m').module_name)" expect(eval_and_collect_notices(code)[0]).to eql('m') end it 'can use an undef module_name' do code = "notice(type(Puppet::LookupContext.new(undef).module_name))" expect(eval_and_collect_notices(code)[0]).to eql('Undef') end it 'can store and retrieve a value using the cache' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache('ze_key', 'ze_value') notice($ctx.cached_value('ze_key')) PUPPET expect(eval_and_collect_notices(code)[0]).to eql('ze_value') end it 'the cache method returns the value that is cached' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') notice($ctx.cache('ze_key', 'ze_value')) PUPPET expect(eval_and_collect_notices(code)[0]).to eql('ze_value') end it 'can store and retrieve a hash using the cache' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second)) end it 'can use the cache to merge hashes' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cache_all({ 'v3' => 'third', 'v4' => 'fourth' }) $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second v3 third v4 fourth)) end it 'can use the cache to merge hashes and individual entries' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cache('v3', 'third') $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second v3 third)) end it 'can iterate the cache using one argument block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cached_entries |$entry| { notice($entry[0]); notice($entry[1]) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second)) end it 'can replace individual cached entries' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cache('v2', 'changed') $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 changed)) end it 'can replace multiple cached entries' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second', 'v3' => 'third' }) $ctx.cache_all({ 'v1' => 'one', 'v3' => 'three' }) $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 one v2 second v3 three)) end it 'cached_entries returns an Iterable when called without a block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $iter = $ctx.cached_entries notice(type($iter, generalized)) $iter.each |$entry| { notice($entry[0]); notice($entry[1]) } PUPPET expect(eval_and_collect_notices(code)).to eql(['Iterator[Tuple[String, String, 2, 2]]', 'v1', 'first', 'v2', 'second']) end it 'will throw :no_such_key when not_found is called' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.not_found PUPPET expect { eval_and_collect_notices(code) }.to throw_symbol(:no_such_key) end context 'with cached_file_data' do include PuppetSpec::Files let(:code_dir) { Puppet[:environmentpath] } let(:env_name) { 'testing' } let(:env_dir) { File.join(code_dir, env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } let(:data_yaml) { 'data.yaml' } let(:data_path) { File.join(populated_env_dir, 'data', data_yaml) } let(:populated_env_dir) do dir_contained_in(code_dir, { env_name => { 'data' => { data_yaml => <<-YAML.unindent a: value a YAML } } } ) PuppetSpec::Files.record_tmp(File.join(env_dir)) env_dir end it 'can use cached_file_data without a block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') notice($yaml_data) PUPPET expect(eval_and_collect_notices(code, node)).to eql(["a: value a\n"]) end it 'can use cached_file_data with a block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET expect(eval_and_collect_notices(code, node)).to eql(["{parsed => a: value a\n}"]) end context 'and multiple compilations' do before(:each) { Puppet.settings[:environment_timeout] = 'unlimited' } it 'will reuse cached_file_data and not call block again' do code1 = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET code2 = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => 'should not be called' } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code1 Puppet::Parser::Compiler.compile(node) Puppet[:code] = code2 Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs.uniq.size).to eql(1) end it 'will invalidate cache if file changes size' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code Puppet::Parser::Compiler.compile(node) # Change content size! File.write(data_path, "a: value is now A\n") Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs).to eql(["{parsed => a: value a\n}", "{parsed => a: value is now A\n}"]) end it 'will invalidate cache if file changes mtime' do old_mtime = Puppet::FileSystem.stat(data_path).mtime code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code Puppet::Parser::Compiler.compile(node) # Write content with the same size File.write(data_path, "a: value b\n") # Ensure mtime is at least 1 second ahead FileUtils.touch(data_path, mtime: old_mtime + 1) Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs).to eql(["{parsed => a: value a\n}", "{parsed => a: value b\n}"]) end it 'will invalidate cache if file changes inode' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code Puppet::Parser::Compiler.compile(node) # Change inode! File.delete(data_path); # Write content with the same size File.write(data_path, "a: value b\n") Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs).to eql(["{parsed => a: value a\n}", "{parsed => a: value b\n}"]) end end end context 'when used in an Invocation' do let(:node) { Puppet::Node.new('test') } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:invocation) { Invocation.new(compiler.topscope) } let(:invocation_with_explain) { Invocation.new(compiler.topscope, {}, {}, true) } def compile_and_get_notices(code, scope_vars = {}) Puppet[:code] = code scope = compiler.topscope scope_vars.each_pair { |k,v| scope.setvar(k, v) } node.environment.check_for_reparse logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } logs end it 'will not call explain unless explanations are active' do invocation.lookup('dummy', nil) do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.explain || { notice('stop calling'); 'bad' } PUPPET expect(compile_and_get_notices(code)).to be_empty end end it 'will call explain when explanations are active' do invocation_with_explain.lookup('dummy', nil) do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.explain || { notice('called'); 'good' } PUPPET expect(compile_and_get_notices(code)).to eql(['called']) end expect(invocation_with_explain.explainer.explain).to eql("good\n") end it 'will call interpolate to resolve interpolation' do invocation.lookup('dummy', nil) do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') notice($ctx.interpolate('-- %{testing} --')) PUPPET expect(compile_and_get_notices(code, { 'testing' => 'called' })).to eql(['-- called --']) end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/lookup/lookup_spec.rb
spec/unit/pops/lookup/lookup_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/pops' require 'deep_merge/core' module Puppet::Pops module Lookup describe 'The lookup API' do include PuppetSpec::Files let(:env_name) { 'spec' } let(:code_dir) { Puppet[:environmentpath] } let(:env_dir) { File.join(code_dir, env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:pal_compiler) { Puppet::Pal::ScriptCompiler.new(compiler) } let(:scope) { compiler.topscope } let(:invocation) { Invocation.new(scope) } let(:code_dir_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent a: a (from global) d: d (from global) mod::e: mod::e (from global) YAML } } end let(:env_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent b: b (from environment) d: d (from environment) mod::f: mod::f (from environment) YAML } } end let(:mod_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent mod::c: mod::c (from module) mod::e: mod::e (from module) mod::f: mod::f (from module) mod::g: :symbol: symbol key value key: string key value 6: integer key value -4: negative integer key value 2.7: float key value '6': string integer key value YAML } } end let(:populated_env_dir) do all_content = code_dir_content.merge(env_name => env_content.merge('modules' => { 'mod' => mod_content })) dir_contained_in(code_dir, all_content) all_content.keys.each { |key| PuppetSpec::Files.record_tmp(File.join(code_dir, key)) } env_dir end before(:each) do Puppet[:hiera_config] = File.join(code_dir, 'hiera.yaml') Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env)) end after(:each) do Puppet.pop_context end context 'when doing automatic parameter lookup' do let(:mod_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent mod::x: mod::x (from module) YAML }, 'manifests' => { 'init.pp' => <<-PUPPET.unindent class mod($x) { notify { $x: } } PUPPET } } end let(:logs) { [] } let(:debugs) { logs.select { |log| log.level == :debug }.map { |log| log.message } } it 'includes APL in explain output when debug is enabled' do Puppet[:log_level] = 'debug' Puppet[:code] = 'include mod' Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile end expect(debugs).to include(/Found key: "mod::x" value: "mod::x \(from module\)"/) end end context 'when hiera YAML data is corrupt' do let(:mod_content) do { 'hiera.yaml' => 'version: 5', 'data' => { 'common.yaml' => <<-YAML.unindent --- #mod::classes: - cls1 - cls2 mod::somevar: 1 YAML }, } end let(:msg) { /file does not contain a valid yaml hash/ } %w(off warning).each do |strict| it "logs a warning when --strict is '#{strict}'" do Puppet[:strict] = strict logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(Lookup.lookup('mod::somevar', nil, nil, true, nil, invocation)).to be_nil end expect(logs.map(&:message)).to contain_exactly(msg) end end it 'fails when --strict is "error"' do Puppet[:strict] = 'error' expect { Lookup.lookup('mod::somevar', nil, nil, true, nil, invocation) }.to raise_error(msg) end end context 'when hiera YAML data is empty' do let(:mod_content) do { 'hiera.yaml' => 'version: 5', 'data' => { 'common.yaml' => '' }, } end let(:msg) { /file does not contain a valid yaml hash/ } %w(off warning error).each do |strict| it "logs a warning when --strict is '#{strict}'" do Puppet[:strict] = strict logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(Lookup.lookup('mod::somevar', nil, nil, true, nil, invocation)).to be_nil end expect(logs.map(&:message)).to contain_exactly(msg) end end end context 'when doing lookup' do it 'finds data in global layer' do expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'finds data in environment layer' do expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('b (from environment)') end it 'global layer wins over environment layer' do expect(Lookup.lookup('d', nil, 'not found', true, nil, invocation)).to eql('d (from global)') end it 'finds data in module layer' do expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('mod::c (from module)') end it 'global layer wins over module layer' do expect(Lookup.lookup('mod::e', nil, 'not found', true, nil, invocation)).to eql('mod::e (from global)') end it 'environment layer wins over module layer' do expect(Lookup.lookup('mod::f', nil, 'not found', true, nil, invocation)).to eql('mod::f (from environment)') end it 'returns the correct types for hash keys' do expect(Lookup.lookup('mod::g', nil, 'not found', true, nil, invocation)).to eql( { 'symbol' => 'symbol key value', 'key' => 'string key value', 6 => 'integer key value', -4 => 'negative integer key value', 2.7 => 'float key value', '6' => 'string integer key value' } ) end it 'can navigate a hash with an integer key using a dotted key' do expect(Lookup.lookup('mod::g.6', nil, 'not found', true, nil, invocation)).to eql('integer key value') end it 'can navigate a hash with a negative integer key using a dotted key' do expect(Lookup.lookup('mod::g.-4', nil, 'not found', true, nil, invocation)).to eql('negative integer key value') end it 'can navigate a hash with an string integer key using a dotted key with quoted integer' do expect(Lookup.lookup("mod::g.'6'", nil, 'not found', true, nil, invocation)).to eql('string integer key value') end context "with 'global_only' set to true in the invocation" do let(:invocation) { Invocation.new(scope).set_global_only } it 'finds data in global layer' do expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'does not find data in environment layer' do expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('not found') end it 'does not find data in module layer' do expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('not found') end end context "with 'global_only' set to true in the lookup adapter" do it 'finds data in global layer' do invocation.lookup_adapter.set_global_only expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'does not find data in environment layer' do invocation.lookup_adapter.set_global_only expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('not found') end it 'does not find data in module layer' do invocation.lookup_adapter.set_global_only expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('not found') end end context 'with subclassed lookup adpater' do let(:other_dir) { tmpdir('other') } let(:other_dir_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 hierarchy: - name: Common path: common.yaml - name: More path: more.yaml YAML 'data' => { 'common.yaml' => <<-YAML.unindent, a: a (from other global) d: d (from other global) mixed_adapter_hash: a: ab: value a.ab (from other common global) ad: value a.ad (from other common global) mod::e: mod::e (from other global) lookup_options: mixed_adapter_hash: merge: deep YAML 'more.yaml' => <<-YAML.unindent mixed_adapter_hash: a: aa: value a.aa (from other more global) ac: value a.ac (from other more global) YAML } } end let(:populated_other_dir) do dir_contained_in(other_dir, other_dir_content) other_dir end before(:each) do eval(<<-RUBY.unindent) class SpecialLookupAdapter < LookupAdapter def initialize(compiler) super set_global_only set_global_hiera_config_path(File.join('#{populated_other_dir}', 'hiera.yaml')) end end RUBY end after(:each) do Puppet::Pops::Lookup.send(:remove_const, :SpecialLookupAdapter) end let(:other_invocation) { Invocation.new(scope, EMPTY_HASH, EMPTY_HASH, nil, SpecialLookupAdapter) } it 'finds different data in global layer' do expect(Lookup.lookup('a', nil, nil, false, nil, other_invocation)).to eql('a (from other global)') expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'does not find data in environment layer' do expect(Lookup.lookup('b', nil, 'not found', true, nil, other_invocation)).to eql('not found') expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('b (from environment)') end it 'does not find data in module layer' do expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, other_invocation)).to eql('not found') expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('mod::c (from module)') end it 'resolves lookup options using the custom adapter' do expect(Lookup.lookup('mixed_adapter_hash', nil, 'not found', true, nil, other_invocation)).to eql( { 'a' => { 'aa' => 'value a.aa (from other more global)', 'ab' => 'value a.ab (from other common global)', 'ac' => 'value a.ac (from other more global)', 'ad' => 'value a.ad (from other common global)' } } ) end end end context 'when using plan_hierarchy' do let(:code_dir_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 plan_hierarchy: - path: foo.yaml name: Common YAML 'data' => { 'foo.yaml' => <<-YAML.unindent pop: star YAML } } end it 'uses plan_hierarchy when using ScriptCompiler' do Puppet.override(pal_compiler: pal_compiler) do expect(Lookup.lookup('pop', nil, nil, true, nil, invocation)).to eq('star') end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/lookup/interpolation_spec.rb
spec/unit/pops/lookup/interpolation_spec.rb
require 'spec_helper' require 'puppet' module Puppet::Pops describe 'Puppet::Pops::Lookup::Interpolation' do include Lookup::SubLookup class InterpolationTestAdapter < Lookup::LookupAdapter include Lookup::SubLookup def initialize(data, interpolator) @data = data @interpolator = interpolator end def track(name) end def lookup(name, lookup_invocation, merge) track(name) segments = split_key(name) root_key = segments.shift found = @data[root_key] found = sub_lookup(name, lookup_invocation, segments, found) unless segments.empty? @interpolator.interpolate(found, lookup_invocation, true) end # ignore requests for lookup options when testing interpolation def lookup_lookup_options(_, _) nil end end let(:interpolator) { Class.new { include Lookup::Interpolation }.new } let(:scope) { {} } let(:data) { {} } let(:adapter) { InterpolationTestAdapter.new(data, interpolator) } let(:lookup_invocation) { Lookup::Invocation.new(scope, {}, {}, nil) } before(:each) do allow_any_instance_of(Lookup::Invocation).to receive(:lookup_adapter).and_return(adapter) end def expect_lookup(*keys) keys.each { |key| expect(adapter).to receive(:track).with(key) } end context 'when the invocation has a default falsey values' do let(:lookup_invocation) { Lookup::Invocation.new(scope, {}, {'key' => false, 'key2' => nil}, nil) } it 'converts boolean false to a "false" string in interpolation' do expect(interpolator.interpolate('%{key}', lookup_invocation, true)).to eq("false") end it 'converts nil to an empty string in interpolation' do expect(interpolator.interpolate('%{key2}', lookup_invocation, true)).to eq("") end end context 'when interpolating nested data' do let(:nested_hash) { {'a' => {'aa' => "%{alias('aaa')}"}} } let(:scope) { { 'ds1' => 'a', 'ds2' => 'b' } } let(:data) { { 'aaa' => {'b' => {'bb' => "%{alias('bbb')}"}}, 'bbb' => ["%{alias('ccc')}"], 'ccc' => 'text', 'ddd' => "%{literal('%')}{ds1}_%{literal('%')}{ds2}", } } it 'produces a nested hash with arrays from nested aliases with hashes and arrays' do expect_lookup('aaa', 'bbb', 'ccc') expect(interpolator.interpolate(nested_hash, lookup_invocation, true)).to eq('a' => {'aa' => {'b' => {'bb' => ['text']}}}) end it "'%{lookup('key')} will interpolate the returned value'" do expect_lookup('ddd') expect(interpolator.interpolate("%{lookup('ddd')}", lookup_invocation, true)).to eq('a_b') end it "'%{alias('key')} will not interpolate the returned value'" do expect_lookup('ddd') expect(interpolator.interpolate("%{alias('ddd')}", lookup_invocation, true)).to eq('%{ds1}_%{ds2}') end end context 'when interpolating boolean scope values' do let(:scope) { { 'yes' => true, 'no' => false } } it 'produces the string true' do expect(interpolator.interpolate('should yield %{yes}', lookup_invocation, true)).to eq('should yield true') end it 'produces the string false' do expect(interpolator.interpolate('should yield %{no}', lookup_invocation, true)).to eq('should yield false') end end context 'when there are empty interpolations %{} in data' do let(:empty_interpolation) { 'clown%{}shoe' } let(:empty_interpolation_as_escape) { 'clown%%{}{shoe}s' } let(:only_empty_interpolation) { '%{}' } let(:empty_namespace) { '%{::}' } let(:whitespace1) { '%{ :: }' } let(:whitespace2) { '%{ }' } it 'should produce an empty string for the interpolation' do expect(interpolator.interpolate(empty_interpolation, lookup_invocation, true)).to eq('clownshoe') end it 'the empty interpolation can be used as an escape mechanism' do expect(interpolator.interpolate(empty_interpolation_as_escape, lookup_invocation, true)).to eq('clown%{shoe}s') end it 'the value can consist of only an empty escape' do expect(interpolator.interpolate(only_empty_interpolation, lookup_invocation, true)).to eq('') end it 'the value can consist of an empty namespace %{::}' do expect(interpolator.interpolate(empty_namespace, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ :: }' do expect(interpolator.interpolate(whitespace1, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ }' do expect(interpolator.interpolate(whitespace2, lookup_invocation, true)).to eq('') end end context 'when there are quoted empty interpolations %{} in data' do let(:empty_interpolation) { 'clown%{""}shoe' } let(:empty_interpolation_as_escape) { 'clown%%{""}{shoe}s' } let(:only_empty_interpolation) { '%{""}' } let(:empty_namespace) { '%{"::"}' } let(:whitespace1) { '%{ "::" }' } let(:whitespace2) { '%{ "" }' } it 'should produce an empty string for the interpolation' do expect(interpolator.interpolate(empty_interpolation, lookup_invocation, true)).to eq('clownshoe') end it 'the empty interpolation can be used as an escape mechanism' do expect(interpolator.interpolate(empty_interpolation_as_escape, lookup_invocation, true)).to eq('clown%{shoe}s') end it 'the value can consist of only an empty escape' do expect(interpolator.interpolate(only_empty_interpolation, lookup_invocation, true)).to eq('') end it 'the value can consist of an empty namespace %{"::"}' do expect(interpolator.interpolate(empty_namespace, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ "::" }' do expect(interpolator.interpolate(whitespace1, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ "" }' do expect(interpolator.interpolate(whitespace2, lookup_invocation, true)).to eq('') end end context 'when using dotted keys' do let(:data) { { 'a.b' => '(lookup) a dot b', 'a' => { 'd' => '(lookup) a dot d is a hash entry', 'd.x' => '(lookup) a dot d.x is a hash entry', 'd.z' => { 'g' => '(lookup) a dot d.z dot g is a hash entry'} }, 'a.x' => { 'd' => '(lookup) a.x dot d is a hash entry', 'd.x' => '(lookup) a.x dot d.x is a hash entry', 'd.z' => { 'g' => '(lookup) a.x dot d.z dot g is a hash entry' } }, 'x.1' => '(lookup) x dot 1', 'key' => 'subkey' } } let(:scope) { { 'a.b' => '(scope) a dot b', 'a' => { 'd' => '(scope) a dot d is a hash entry', 'd.x' => '(scope) a dot d.x is a hash entry', 'd.z' => { 'g' => '(scope) a dot d.z dot g is a hash entry'} }, 'a.x' => { 'd' => '(scope) a.x dot d is a hash entry', 'd.x' => '(scope) a.x dot d.x is a hash entry', 'd.z' => { 'g' => '(scope) a.x dot d.z dot g is a hash entry' } }, 'x.1' => '(scope) x dot 1', } } it 'should find an entry using a quoted interpolation' do expect(interpolator.interpolate("a dot c: %{'a.b'}", lookup_invocation, true)).to eq('a dot c: (scope) a dot b') end it 'should find an entry using a quoted interpolation with method lookup' do expect_lookup("'a.b'") expect(interpolator.interpolate("a dot c: %{lookup(\"'a.b'\")}", lookup_invocation, true)).to eq('a dot c: (lookup) a dot b') end it 'should find an entry using a quoted interpolation with method alias' do expect_lookup("'a.b'") expect(interpolator.interpolate("%{alias(\"'a.b'\")}", lookup_invocation, true)).to eq('(lookup) a dot b') end it 'should use a dotted key to navigate into a structure when it is not quoted' do expect(interpolator.interpolate('a dot e: %{a.d}', lookup_invocation, true)).to eq('a dot e: (scope) a dot d is a hash entry') end it 'should report a key missing and replace with empty string when a dotted key is used to navigate into a structure and then not found' do expect(interpolator.interpolate('a dot n: %{a.n}', lookup_invocation, true)).to eq('a dot n: ') end it 'should use a dotted key to navigate into a structure when it is not quoted with method lookup' do expect_lookup('a.d') expect(interpolator.interpolate("a dot e: %{lookup('a.d')}", lookup_invocation, true)).to eq('a dot e: (lookup) a dot d is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is last' do expect(interpolator.interpolate("a dot ex: %{a.'d.x'}", lookup_invocation, true)).to eq('a dot ex: (scope) a dot d.x is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is last and method is lookup' do expect_lookup("a.'d.x'") expect(interpolator.interpolate("a dot ex: %{lookup(\"a.'d.x'\")}", lookup_invocation, true)).to eq('a dot ex: (lookup) a dot d.x is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is first' do expect(interpolator.interpolate("a dot xe: %{'a.x'.d}", lookup_invocation, true)).to eq('a dot xe: (scope) a.x dot d is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is first and method is lookup' do expect_lookup("'a.x'.d") expect(interpolator.interpolate("a dot xe: %{lookup(\"'a.x'.d\")}", lookup_invocation, true)).to eq('a dot xe: (lookup) a.x dot d is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle' do expect(interpolator.interpolate("a dot xm: %{a.'d.z'.g}", lookup_invocation, true)).to eq('a dot xm: (scope) a dot d.z dot g is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle and method is lookup' do expect_lookup("a.'d.z'.g") expect(interpolator.interpolate("a dot xm: %{lookup(\"a.'d.z'.g\")}", lookup_invocation, true)).to eq('a dot xm: (lookup) a dot d.z dot g is a hash entry') end it 'should use a mix of several quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle' do expect(interpolator.interpolate("a dot xx: %{'a.x'.'d.z'.g}", lookup_invocation, true)).to eq('a dot xx: (scope) a.x dot d.z dot g is a hash entry') end it 'should use a mix of several quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle and method is lookup' do expect_lookup("'a.x'.'d.z'.g") expect(interpolator.interpolate("a dot xx: %{lookup(\"'a.x'.'d.z'.g\")}", lookup_invocation, true)).to eq('a dot xx: (lookup) a.x dot d.z dot g is a hash entry') end it 'should find an entry using using a quoted interpolation on dotted key containing numbers' do expect(interpolator.interpolate("x dot 2: %{'x.1'}", lookup_invocation, true)).to eq('x dot 2: (scope) x dot 1') end it 'should find an entry using using a quoted interpolation on dotted key containing numbers using method lookup' do expect_lookup("'x.1'") expect(interpolator.interpolate("x dot 2: %{lookup(\"'x.1'\")}", lookup_invocation, true)).to eq('x dot 2: (lookup) x dot 1') end it 'should not find a subkey when the dotted key is quoted' do expect(interpolator.interpolate("a dot f: %{'a.d'}", lookup_invocation, true)).to eq('a dot f: ') end it 'should not find a subkey when the dotted key is quoted with method lookup' do expect_lookup("'a.d'") expect(interpolator.interpolate("a dot f: %{lookup(\"'a.d'\")}", lookup_invocation, true)).to eq('a dot f: ') end it 'should not find a subkey that is matched within a string' do expect{ interpolator.interpolate("%{lookup('key.subkey')}", lookup_invocation, true) }.to raise_error( /Got String when a hash-like object was expected to access value using 'subkey' from key 'key.subkey'/) end end context 'when dealing with non alphanumeric characters' do let(:data) { { 'a key with whitespace' => 'value for a ws key', 'ws_key' => '%{alias("a key with whitespace")}', '\#@!&%|' => 'not happy', 'angry' => '%{alias("\#@!&%|")}', '!$\%!' => { '\#@!&%|' => 'not happy at all' }, 'very_angry' => '%{alias("!$\%!.\#@!&%|")}', 'a key with' => { 'nested whitespace' => 'value for nested ws key', ' untrimmed whitespace ' => 'value for untrimmed ws key' } } } it 'allows keys with white space' do expect_lookup('ws_key', 'a key with whitespace') expect(interpolator.interpolate("%{lookup('ws_key')}", lookup_invocation, true)).to eq('value for a ws key') end it 'allows keys with non alphanumeric characters' do expect_lookup('angry', '\#@!&%|') expect(interpolator.interpolate("%{lookup('angry')}", lookup_invocation, true)).to eq('not happy') end it 'allows dotted keys with non alphanumeric characters' do expect_lookup('very_angry', '!$\%!.\#@!&%|') expect(interpolator.interpolate("%{lookup('very_angry')}", lookup_invocation, true)).to eq('not happy at all') end it 'allows dotted keys with nested white space' do expect_lookup('a key with.nested whitespace') expect(interpolator.interpolate("%{lookup('a key with.nested whitespace')}", lookup_invocation, true)).to eq('value for nested ws key') end it 'will trim each key element' do expect_lookup(' a key with . nested whitespace ') expect(interpolator.interpolate("%{lookup(' a key with . nested whitespace ')}", lookup_invocation, true)).to eq('value for nested ws key') end it 'will not trim quoted key element' do expect_lookup(' a key with ." untrimmed whitespace "') expect(interpolator.interpolate("%{lookup(' a key with .\" untrimmed whitespace \"')}", lookup_invocation, true)).to eq('value for untrimmed ws key') end it 'will not trim spaces outside of quoted key element' do expect_lookup(' a key with . " untrimmed whitespace " ') expect(interpolator.interpolate("%{lookup(' a key with . \" untrimmed whitespace \" ')}", lookup_invocation, true)).to eq('value for untrimmed ws key') end end context 'when dealing with bad keys' do it 'should produce an error when different quotes are used on either side' do expect { interpolator.interpolate("%{'the.key\"}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{'the.key\"}") end it 'should produce an if there is only one quote' do expect { interpolator.interpolate("%{the.'key}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{the.'key}") end it 'should produce an error for an empty segment' do expect { interpolator.interpolate('%{the..key}', lookup_invocation, true)}.to raise_error("Syntax error in string: %{the..key}") end it 'should produce an error for an empty quoted segment' do expect { interpolator.interpolate("%{the.''.key}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{the.''.key}") end it 'should produce an error for an partly quoted segment' do expect { interpolator.interpolate("%{the.'pa'key}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{the.'pa'key}") end it 'should produce an error when different quotes are used on either side in a method argument' do expect { interpolator.interpolate("%{lookup('the.key\")}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{lookup('the.key\")}") end it 'should produce an error unless a known interpolation method is used' do expect { interpolator.interpolate("%{flubber(\"hello\")}", lookup_invocation, true)}.to raise_error("Unknown interpolation method 'flubber'") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/access_ops_spec.rb
spec/unit/pops/evaluator/access_ops_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' require 'puppet/pops/types/type_factory' require 'base64' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl/AccessOperator' do include EvaluatorRspecHelper def range(from, to) Puppet::Pops::Types::TypeFactory.range(from, to) end def float_range(from, to) Puppet::Pops::Types::TypeFactory.float_range(from, to) end def binary(s) # Note that the factory is not aware of Binary and cannot operate on a # literal binary. Instead, it must create a call to Binary.new() with the base64 encoded # string as an argument CALL_NAMED(QREF("Binary"), true, [infer(Base64.strict_encode64(s))]) end context 'The evaluator when operating on a String' do it 'can get a single character using a single key index to []' do expect(evaluate(literal('abc').access_at(1))).to eql('b') end it 'can get the last character using the key -1 in []' do expect(evaluate(literal('abc').access_at(-1))).to eql('c') end it 'can get a substring by giving two keys' do expect(evaluate(literal('abcd').access_at(1,2))).to eql('bc') # flattens keys expect(evaluate(literal('abcd').access_at([1,2]))).to eql('bc') end it 'produces empty string for a substring out of range' do expect(evaluate(literal('abc').access_at(100))).to eql('') end it 'raises an error if arity is wrong for []' do expect{evaluate(literal('abc').access_at)}.to raise_error(/String supports \[\] with one or two arguments\. Got 0/) expect{evaluate(literal('abc').access_at(1,2,3))}.to raise_error(/String supports \[\] with one or two arguments\. Got 3/) end end context 'The evaluator when operating on a Binary' do it 'can get a single character using a single key index to []' do expect(evaluate(binary('abc').access_at(1)).binary_buffer).to eql('b') end it 'can get the last character using the key -1 in []' do expect(evaluate(binary('abc').access_at(-1)).binary_buffer).to eql('c') end it 'can get a substring by giving two keys' do expect(evaluate(binary('abcd').access_at(1,2)).binary_buffer).to eql('bc') # flattens keys expect(evaluate(binary('abcd').access_at([1,2])).binary_buffer).to eql('bc') end it 'produces empty string for a substring out of range' do expect(evaluate(binary('abc').access_at(100)).binary_buffer).to eql('') end it 'raises an error if arity is wrong for []' do expect{evaluate(binary('abc').access_at)}.to raise_error(/String supports \[\] with one or two arguments\. Got 0/) expect{evaluate(binary('abc').access_at(1,2,3))}.to raise_error(/String supports \[\] with one or two arguments\. Got 3/) end end context 'The evaluator when operating on an Array' do it 'is tested with the correct assumptions' do expect(literal([1,2,3]).access_at(1).model_class <= Puppet::Pops::Model::AccessExpression).to eql(true) end it 'can get an element using a single key index to []' do expect(evaluate(literal([1,2,3]).access_at(1))).to eql(2) end it 'can get the last element using the key -1 in []' do expect(evaluate(literal([1,2,3]).access_at(-1))).to eql(3) end it 'can get a slice of elements using two keys' do expect(evaluate(literal([1,2,3,4]).access_at(1,2))).to eql([2,3]) # flattens keys expect(evaluate(literal([1,2,3,4]).access_at([1,2]))).to eql([2,3]) end it 'produces nil for a missing entry' do expect(evaluate(literal([1,2,3]).access_at(100))).to eql(nil) end it 'raises an error if arity is wrong for []' do expect{evaluate(literal([1,2,3,4]).access_at)}.to raise_error(/Array supports \[\] with one or two arguments\. Got 0/) expect{evaluate(literal([1,2,3,4]).access_at(1,2,3))}.to raise_error(/Array supports \[\] with one or two arguments\. Got 3/) end end context 'The evaluator when operating on a Hash' do it 'can get a single element giving a single key to []' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3}).access_at('b'))).to eql(2) end it 'can lookup an array' do expect(evaluate(literal({[1]=>10,[2]=>20}).access_at([2]))).to eql(20) end it 'produces nil for a missing key' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3}).access_at('x'))).to eql(nil) end it 'can get multiple elements by giving multiple keys to []' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3, 'd'=>4}).access_at('b', 'd'))).to eql([2, 4]) end it 'compacts the result when using multiple keys' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3, 'd'=>4}).access_at('b', 'x'))).to eql([2]) end it 'produces an empty array if none of multiple given keys were missing' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3, 'd'=>4}).access_at('x', 'y'))).to eql([]) end it 'raises an error if arity is wrong for []' do expect{evaluate(literal({'a'=>1,'b'=>2,'c'=>3}).access_at)}.to raise_error(/Hash supports \[\] with one or more arguments\. Got 0/) end end context "When applied to a type it" do let(:types) { Puppet::Pops::Types::TypeFactory } # Integer # it 'produces an Integer[from, to]' do expr = fqr('Integer').access_at(1, 3) expect(evaluate(expr)).to eql(range(1,3)) # arguments are flattened expr = fqr('Integer').access_at([1, 3]) expect(evaluate(expr)).to eql(range(1,3)) end it 'produces an Integer[1]' do expr = fqr('Integer').access_at(1) expect(evaluate(expr)).to eql(range(1,:default)) end it 'gives an error for Integer[from, <from]' do expr = fqr('Integer').access_at(1,0) expect{evaluate(expr)}.to raise_error(/'from' must be less or equal to 'to'/) end it 'produces an error for Integer[] if there are more than 2 keys' do expr = fqr('Integer').access_at(1,2,3) expect { evaluate(expr)}.to raise_error(/with one or two arguments/) end # Float # it 'produces a Float[from, to]' do expr = fqr('Float').access_at(1, 3) expect(evaluate(expr)).to eql(float_range(1.0,3.0)) # arguments are flattened expr = fqr('Float').access_at([1, 3]) expect(evaluate(expr)).to eql(float_range(1.0,3.0)) end it 'produces a Float[1.0]' do expr = fqr('Float').access_at(1.0) expect(evaluate(expr)).to eql(float_range(1.0,:default)) end it 'produces a Float[1]' do expr = fqr('Float').access_at(1) expect(evaluate(expr)).to eql(float_range(1.0,:default)) end it 'gives an error for Float[from, <from]' do expr = fqr('Float').access_at(1.0,0.0) expect{evaluate(expr)}.to raise_error(/'from' must be less or equal to 'to'/) end it 'produces an error for Float[] if there are more than 2 keys' do expr = fqr('Float').access_at(1,2,3) expect { evaluate(expr)}.to raise_error(/with one or two arguments/) end # Hash Type # it 'produces a Hash[0, 0] from the expression Hash[0, 0]' do expr = fqr('Hash').access_at(0, 0) expect(evaluate(expr)).to be_the_type(types.hash_of(types.default, types.default, types.range(0, 0))) end it 'produces a Hash[Scalar,String] from the expression Hash[Scalar, String]' do expr = fqr('Hash').access_at(fqr('Scalar'), fqr('String')) expect(evaluate(expr)).to be_the_type(types.hash_of(types.string, types.scalar)) # arguments are flattened expr = fqr('Hash').access_at([fqr('Scalar'), fqr('String')]) expect(evaluate(expr)).to be_the_type(types.hash_of(types.string, types.scalar)) end it 'gives an error if only one type is specified ' do expr = fqr('Hash').access_at(fqr('String')) expect {evaluate(expr)}.to raise_error(/accepts 2 to 4 arguments/) end it 'produces a Hash[Scalar,String] from the expression Hash[Integer, Array][Integer, String]' do expr = fqr('Hash').access_at(fqr('Integer'), fqr('Array')).access_at(fqr('Integer'), fqr('String')) expect(evaluate(expr)).to be_the_type(types.hash_of(types.string, types.integer)) end it "gives an error if parameter is not a type" do expr = fqr('Hash').access_at('String') expect { evaluate(expr)}.to raise_error(/Hash-Type\[\] arguments must be types/) end # Array Type # it 'produces an Array[0, 0] from the expression Array[0, 0]' do expr = fqr('Array').access_at(0, 0) expect(evaluate(expr)).to be_the_type(types.array_of(types.default, types.range(0, 0))) # arguments are flattened expr = fqr('Array').access_at([fqr('String')]) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) end it 'produces an Array[String] from the expression Array[String]' do expr = fqr('Array').access_at(fqr('String')) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) # arguments are flattened expr = fqr('Array').access_at([fqr('String')]) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) end it 'produces an Array[String] from the expression Array[Integer][String]' do expr = fqr('Array').access_at(fqr('Integer')).access_at(fqr('String')) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) end it 'produces a size constrained Array when the last two arguments specify this' do expr = fqr('Array').access_at(fqr('String'), 1) expected_t = types.array_of(String, types.range(1, :default)) expect(evaluate(expr)).to be_the_type(expected_t) expr = fqr('Array').access_at(fqr('String'), 1, 2) expected_t = types.array_of(String, types.range(1, 2)) expect(evaluate(expr)).to be_the_type(expected_t) end it "Array parameterization gives an error if parameter is not a type" do expr = fqr('Array').access_at('String') expect { evaluate(expr)}.to raise_error(/Array-Type\[\] arguments must be types/) end # Timespan Type # it 'produdes a Timespan type with a lower bound' do expr = fqr('Timespan').access_at({fqn('hours') => literal(3)}) expect(evaluate(expr)).to be_the_type(types.timespan({'hours' => 3})) end it 'produdes a Timespan type with an upper bound' do expr = fqr('Timespan').access_at(literal(:default), {fqn('hours') => literal(9)}) expect(evaluate(expr)).to be_the_type(types.timespan(nil, {'hours' => 9})) end it 'produdes a Timespan type with both lower and upper bounds' do expr = fqr('Timespan').access_at({fqn('hours') => literal(3)}, {fqn('hours') => literal(9)}) expect(evaluate(expr)).to be_the_type(types.timespan({'hours' => 3}, {'hours' => 9})) end # Timestamp Type # it 'produdes a Timestamp type with a lower bound' do expr = fqr('Timestamp').access_at(literal('2014-12-12T13:14:15 CET')) expect(evaluate(expr)).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET')) end it 'produdes a Timestamp type with an upper bound' do expr = fqr('Timestamp').access_at(literal(:default), literal('2016-08-23T17:50:00 CET')) expect(evaluate(expr)).to be_the_type(types.timestamp(nil, '2016-08-23T17:50:00 CET')) end it 'produdes a Timestamp type with both lower and upper bounds' do expr = fqr('Timestamp').access_at(literal('2014-12-12T13:14:15 CET'), literal('2016-08-23T17:50:00 CET')) expect(evaluate(expr)).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET', '2016-08-23T17:50:00 CET')) end # Tuple Type # it 'produces a Tuple[String] from the expression Tuple[String]' do expr = fqr('Tuple').access_at(fqr('String')) expect(evaluate(expr)).to be_the_type(types.tuple([String])) # arguments are flattened expr = fqr('Tuple').access_at([fqr('String')]) expect(evaluate(expr)).to be_the_type(types.tuple([String])) end it "Tuple parameterization gives an error if parameter is not a type" do expr = fqr('Tuple').access_at('String') expect { evaluate(expr)}.to raise_error(/Tuple-Type, Cannot use String where Any-Type is expected/) end it 'produces a varargs Tuple when the last two arguments specify size constraint' do expr = fqr('Tuple').access_at(fqr('String'), 1) expected_t = types.tuple([String], types.range(1, :default)) expect(evaluate(expr)).to be_the_type(expected_t) expr = fqr('Tuple').access_at(fqr('String'), 1, 2) expected_t = types.tuple([String], types.range(1, 2)) expect(evaluate(expr)).to be_the_type(expected_t) end # Pattern Type # it 'creates a PPatternType instance when applied to a Pattern' do regexp_expr = fqr('Pattern').access_at('foo') expect(evaluate(regexp_expr)).to eql(Puppet::Pops::Types::TypeFactory.pattern('foo')) end # Regexp Type # it 'creates a Regexp instance when applied to a Pattern' do regexp_expr = fqr('Regexp').access_at('foo') expect(evaluate(regexp_expr)).to eql(Puppet::Pops::Types::TypeFactory.regexp('foo')) # arguments are flattened regexp_expr = fqr('Regexp').access_at(['foo']) expect(evaluate(regexp_expr)).to eql(Puppet::Pops::Types::TypeFactory.regexp('foo')) end # Class # it 'produces a specific class from Class[classname]' do expr = fqr('Class').access_at(fqn('apache')) expect(evaluate(expr)).to be_the_type(types.host_class('apache')) expr = fqr('Class').access_at(literal('apache')) expect(evaluate(expr)).to be_the_type(types.host_class('apache')) end it 'produces an array of Class when args are in an array' do # arguments are flattened expr = fqr('Class').access_at([fqn('apache')]) expect(evaluate(expr)[0]).to be_the_type(types.host_class('apache')) end it 'produces undef for Class if arg is undef' do # arguments are flattened expr = fqr('Class').access_at(nil) expect(evaluate(expr)).to be_nil end it 'produces empty array for Class if arg is [undef]' do # arguments are flattened expr = fqr('Class').access_at([]) expect(evaluate(expr)).to be_eql([]) expr = fqr('Class').access_at([nil]) expect(evaluate(expr)).to be_eql([]) end it 'raises error if access is to no keys' do expr = fqr('Class').access_at(fqn('apache')).access_at expect { evaluate(expr) }.to raise_error(/Evaluation Error: Class\[apache\]\[\] accepts 1 or more arguments\. Got 0/) end it 'produces a collection of classes when multiple class names are given' do expr = fqr('Class').access_at(fqn('apache'), literal('nginx')) result = evaluate(expr) expect(result[0]).to be_the_type(types.host_class('apache')) expect(result[1]).to be_the_type(types.host_class('nginx')) end it 'removes leading :: in class name' do expr = fqr('Class').access_at('::evoe') expect(evaluate(expr)).to be_the_type(types.host_class('evoe')) end it 'raises error if the name is not a valid name' do expr = fqr('Class').access_at('fail-whale') expect { evaluate(expr) }.to raise_error(/Illegal name/) end it 'downcases capitalized class names' do expr = fqr('Class').access_at('My::Class') expect(evaluate(expr)).to be_the_type(types.host_class('my::class')) end it 'gives an error if no keys are given as argument' do expr = fqr('Class').access_at expect {evaluate(expr)}.to raise_error(/Evaluation Error: Class\[\] accepts 1 or more arguments. Got 0/) end it 'produces an empty array if the keys reduce to empty array' do expr = fqr('Class').access_at(literal([[],[]])) expect(evaluate(expr)).to be_eql([]) end # Resource it 'produces a specific resource type from Resource[type]' do expr = fqr('Resource').access_at(fqr('File')) expect(evaluate(expr)).to be_the_type(types.resource('File')) expr = fqr('Resource').access_at(literal('File')) expect(evaluate(expr)).to be_the_type(types.resource('File')) end it 'does not allow the type to be specified in an array' do # arguments are flattened expr = fqr('Resource').access_at([fqr('File')]) expect{evaluate(expr)}.to raise_error(Puppet::ParseError, /must be a resource type or a String/) end it 'produces a specific resource reference type from File[title]' do expr = fqr('File').access_at(literal('/tmp/x')) expect(evaluate(expr)).to be_the_type(types.resource('File', '/tmp/x')) end it 'produces a collection of specific resource references when multiple titles are used' do # Using a resource type expr = fqr('File').access_at(literal('x'),literal('y')) result = evaluate(expr) expect(result[0]).to be_the_type(types.resource('File', 'x')) expect(result[1]).to be_the_type(types.resource('File', 'y')) # Using generic resource expr = fqr('Resource').access_at(fqr('File'), literal('x'),literal('y')) result = evaluate(expr) expect(result[0]).to be_the_type(types.resource('File', 'x')) expect(result[1]).to be_the_type(types.resource('File', 'y')) end it 'produces undef for Resource if arg is undef' do # arguments are flattened expr = fqr('File').access_at(nil) expect(evaluate(expr)).to be_nil end it 'gives an error if no keys are given as argument to Resource' do expr = fqr('Resource').access_at expect {evaluate(expr)}.to raise_error(/Evaluation Error: Resource\[\] accepts 1 or more arguments. Got 0/) end it 'produces an empty array if the type is given, and keys reduce to empty array for Resource' do expr = fqr('Resource').access_at(fqr('File'),literal([[],[]])) expect(evaluate(expr)).to be_eql([]) end it 'gives an error i no keys are given as argument to a specific Resource type' do expr = fqr('File').access_at expect {evaluate(expr)}.to raise_error(/Evaluation Error: File\[\] accepts 1 or more arguments. Got 0/) end it 'produces an empty array if the keys reduce to empty array for a specific Resource tyoe' do expr = fqr('File').access_at(literal([[],[]])) expect(evaluate(expr)).to be_eql([]) end it 'gives an error if resource is not found' do expr = fqr('File').access_at(fqn('x')).access_at(fqn('y')) expect {evaluate(expr)}.to raise_error(/Resource not found: File\['x'\]/) end # NotUndef Type # it 'produces a NotUndef instance' do type_expr = fqr('NotUndef') expect(evaluate(type_expr)).to eql(Puppet::Pops::Types::TypeFactory.not_undef()) end it 'produces a NotUndef instance with contained type' do type_expr = fqr('NotUndef').access_at(fqr('Integer')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.not_undef(tf.integer)) end it 'produces a NotUndef instance with String type when given a literal String' do type_expr = fqr('NotUndef').access_at(literal('hey')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to be_the_type(tf.not_undef(tf.string('hey'))) end it 'Produces Optional instance with String type when using a String argument' do type_expr = fqr('Optional').access_at(literal('hey')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to be_the_type(tf.optional(tf.string('hey'))) end # Type Type # it 'creates a Type instance when applied to a Type' do type_expr = fqr('Type').access_at(fqr('Integer')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.type_type(tf.integer)) # arguments are flattened type_expr = fqr('Type').access_at([fqr('Integer')]) expect(evaluate(type_expr)).to eql(tf.type_type(tf.integer)) end # Ruby Type # it 'creates a Ruby Type instance when applied to a Ruby Type' do type_expr = fqr('Runtime').access_at('ruby','String') tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.ruby_type('String')) # arguments are flattened type_expr = fqr('Runtime').access_at(['ruby', 'String']) expect(evaluate(type_expr)).to eql(tf.ruby_type('String')) end # Callable Type # it 'produces Callable instance without return type' do type_expr = fqr('Callable').access_at(fqr('String')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.callable(String)) end it 'produces Callable instance with parameters and return type' do type_expr = fqr('Callable').access_at([fqr('String')], fqr('Integer')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.callable([String], Integer)) end # Variant Type it 'does not allow Variant declarations with non-type arguments' do type_expr = fqr('Variant').access_at(fqr('Integer'), 'not a type') expect { evaluate(type_expr) }.to raise_error(/Cannot use String where Any-Type is expected/) end end matcher :be_the_type do |type| calc = Puppet::Pops::Types::TypeCalculator.new match do |actual| calc.assignable?(actual, type) && calc.assignable?(type, actual) end failure_message do |actual| "expected #{type.to_s}, but was #{actual.to_s}" end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/logical_ops_spec.rb
spec/unit/pops/evaluator/logical_ops_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do include EvaluatorRspecHelper context "When the evaluator performs boolean operations" do context "using operator AND" do it "true && true == true" do expect(evaluate(literal(true).and(literal(true)))).to eq(true) end it "false && true == false" do expect(evaluate(literal(false).and(literal(true)))).to eq(false) end it "true && false == false" do expect(evaluate(literal(true).and(literal(false)))).to eq(false) end it "false && false == false" do expect(evaluate(literal(false).and(literal(false)))).to eq(false) end end context "using operator OR" do it "true || true == true" do expect(evaluate(literal(true).or(literal(true)))).to eq(true) end it "false || true == true" do expect(evaluate(literal(false).or(literal(true)))).to eq(true) end it "true || false == true" do expect(evaluate(literal(true).or(literal(false)))).to eq(true) end it "false || false == false" do expect(evaluate(literal(false).or(literal(false)))).to eq(false) end end context "using operator NOT" do it "!false == true" do expect(evaluate(literal(false).not())).to eq(true) end it "!true == false" do expect(evaluate(literal(true).not())).to eq(false) end end context "on values requiring boxing to Boolean" do it "'x' == true" do expect(evaluate(literal('x').not())).to eq(false) end it "'' == true" do expect(evaluate(literal('').not())).to eq(false) end it ":undef == false" do expect(evaluate(literal(:undef).not())).to eq(true) end end context "connectives should stop when truth is obtained" do it "true && false && error == false (and no failure)" do expect(evaluate(literal(false).and(literal('0xwtf') + literal(1)).and(literal(true)))).to eq(false) end it "false || true || error == true (and no failure)" do expect(evaluate(literal(true).or(literal('0xwtf') + literal(1)).or(literal(false)))).to eq(true) end it "false || false || error == error (false positive test)" do # TODO: Change the exception type expect {evaluate(literal(true).and(literal('0xwtf') + literal(1)).or(literal(false)))}.to raise_error(Puppet::ParseError) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/basic_expressions_spec.rb
spec/unit/pops/evaluator/basic_expressions_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do include EvaluatorRspecHelper context "When the evaluator evaluates literals" do it 'should evaluator numbers to numbers' do expect(evaluate(literal(1))).to eq(1) expect(evaluate(literal(3.14))).to eq(3.14) end it 'should evaluate strings to string' do expect(evaluate(literal('banana'))).to eq('banana') end it 'should evaluate booleans to booleans' do expect(evaluate(literal(false))).to eq(false) expect(evaluate(literal(true))).to eq(true) end it 'should evaluate names to strings' do expect(evaluate(fqn('banana'))).to eq('banana') end it 'should evaluator types to types' do array_type = Puppet::Pops::Types::PArrayType::DEFAULT expect(evaluate(fqr('Array'))).to eq(array_type) end end context "When the evaluator evaluates Lists" do it "should create an Array when evaluating a LiteralList" do expect(evaluate(literal([1,2,3]))).to eq([1,2,3]) end it "[...[...[]]] should create nested arrays without trouble" do expect(evaluate(literal([1,[2.0, 2.1, [2.2]],[3.0, 3.1]]))).to eq([1,[2.0, 2.1, [2.2]],[3.0, 3.1]]) end it "[2 + 2] should evaluate expressions in entries" do x = literal([literal(2) + literal(2)]); expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x)).to eq("([] (+ 2 2))") expect(evaluate(x)[0]).to eq(4) end it "[1,2,3] == [1,2,3] == true" do expect(evaluate(literal([1,2,3]).eq(literal([1,2,3])))).to eq(true); end it "[1,2,3] != [2,3,4] == true" do expect(evaluate(literal([1,2,3]).ne(literal([2,3,4])))).to eq(true); end it "[1, 2, 3][2] == 3" do expect(evaluate(literal([1,2,3]))[2]).to eq(3) end end context "When the evaluator evaluates Hashes" do it "should create a Hash when evaluating a LiteralHash" do expect(evaluate(literal({'a'=>1,'b'=>2}))).to eq({'a'=>1,'b'=>2}) end it "{...{...{}}} should create nested hashes without trouble" do expect(evaluate(literal({'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}))).to eq({'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}) end it "{'a'=> 2 + 2} should evaluate values in entries" do expect(evaluate(literal({'a'=> literal(2) + literal(2)}))['a']).to eq(4) end it "{'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2} == true" do expect(evaluate(literal({'a'=> 1, 'b'=>2}).eq(literal({'a'=> 1, 'b'=>2})))).to eq(true); end it "{'a'=> 1, 'b'=>2} != {'x'=> 1, 'y'=>3} == true" do expect(evaluate(literal({'a'=> 1, 'b'=>2}).ne(literal({'x'=> 1, 'y'=>3})))).to eq(true); end it "{'a' => 1, 'b' => 2}['b'] == 2" do expect(evaluate(literal({:a => 1, :b => 2}).access_at(:b))).to eq(2) end end context 'When the evaluator evaluates a Block' do it 'an empty block evaluates to nil' do expect(evaluate(block())).to eq(nil) end it 'a block evaluates to its last expression' do expect(evaluate(block(literal(1), literal(2)))).to eq(2) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/literal_evaluator_spec.rb
spec/unit/pops/evaluator/literal_evaluator_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/literal_evaluator' describe "Puppet::Pops::Evaluator::LiteralEvaluator" do let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new } let(:leval) { Puppet::Pops::Evaluator::LiteralEvaluator.new } { "1" => 1, "3.14" => 3.14, "true" => true, "false" => false, "'1'" => '1', "'a'" => 'a', '"a"' => 'a', 'a' => 'a', 'a::b' => 'a::b', 'Boolean[true]' => [true], 'Integer[1]' => [1], 'Integer[-1]' => [-1], 'Integer[-5, -1]' => [-5, -1], 'Integer[-5, 5]' => [-5, 5], # we can't actually represent MIN_INTEGER below, because it's lexed as # UnaryMinusExpression containing a positive LiteralInteger and the integer # must be <= MAX_INTEGER. Therefore, the effective minimum is one greater. "Integer[#{Puppet::Pops::MIN_INTEGER + 1}]" => [-0x7FFFFFFFFFFFFFFF], "Integer[0, #{Puppet::Pops::MAX_INTEGER}]" => [0, 0x7FFFFFFFFFFFFFFF], 'Integer[0, default]' => [0, :default], 'Integer[Infinity]' => ['infinity'], 'Float[Infinity]' => ['infinity'], 'Array[Integer, 1]' => ['integer', 1], 'Hash[Integer, String, 1, 3]' => ['integer', 'string', 1, 3], 'Regexp[/-1/]' => [/-1/], 'Sensitive[-1]' => [-1], 'Timespan[-5, 5]' => [-5, 5], 'Timestamp["2012-10-10", 1]' => ['2012-10-10', 1], 'Undef' => 'undef', 'File' => "file", # special values 'default' => :default, '/.*/' => /.*/, # collections '[1,2,3]' => [1,2,3], '{a=>1,b=>2}' => {'a' => 1, 'b' => 2}, }.each do |source, result| it "evaluates '#{source}' to #{result}" do expect(leval.literal(parser.parse_string(source))).to eq(result) end end it "evaluates undef to nil" do expect(leval.literal(parser.parse_string('undef'))).to be_nil end [ '', '1+1', '[1,2, 1+2]', '{a=>1+1}', '"x$y"', '"x${y}z"', 'Integer[1-3]', 'Integer[-1-3]', 'Optional[[String]]' ].each do |source| it "throws :not_literal for non literal expression '#{source}'" do expect{leval.literal(parser.parse_string(source))}.to throw_symbol(:not_literal) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/evaluating_parser_spec.rb
spec/unit/pops/evaluator/evaluating_parser_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' require 'puppet/loaders' require 'puppet_spec/pops' require 'puppet_spec/scope' require 'puppet/parser/e4_parser_adapter' # relative to this spec file (./) does not work as this file is loaded by rspec #require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do include PuppetSpec::Pops include PuppetSpec::Scope before(:each) do Puppet[:strict_variables] = true Puppet[:data_binding_terminus] = 'none' # Tests needs a known configuration of node/scope/compiler since it parses and evaluates # snippets as the compiler will evaluate them, butwithout the overhead of compiling a complete # catalog for each tested expression. # @parser = Puppet::Pops::Parser::EvaluatingParser.new @node = Puppet::Node.new('node.example.com') @node.environment = environment @compiler = Puppet::Parser::Compiler.new(@node) @scope = Puppet::Parser::Scope.new(@compiler) @scope.source = Puppet::Resource::Type.new(:node, 'node.example.com') @scope.parent = @compiler.topscope Puppet.push_context(:loaders => @compiler.loaders) end after(:each) do Puppet.pop_context end let(:environment) { Puppet::Node::Environment.create(:testing, []) } let(:parser) { @parser } let(:scope) { @scope } types = Puppet::Pops::Types::TypeFactory context "When evaluator evaluates literals" do { "1" => 1, "010" => 8, "0x10" => 16, "3.14" => 3.14, "0.314e1" => 3.14, "31.4e-1" => 3.14, "'1'" => '1', "'banana'" => 'banana', '"banana"' => 'banana', "banana" => 'banana', "banana::split" => 'banana::split', "false" => false, "true" => true, "Array" => types.array_of_any, "/.*/" => /.*/ }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end it 'should error when it encounters an unknown resource' do expect {parser.evaluate_string(scope, '$a = SantaClause', __FILE__)}.to raise_error(/Resource type not found: SantaClause/) end it 'should error when it encounters an unknown resource with a parameter' do expect {parser.evaluate_string(scope, '$b = ToothFairy[emea]', __FILE__)}.to raise_error(/Resource type not found: ToothFairy/) end end context "When the evaluator evaluates Lists and Hashes" do { "[]" => [], "[1,2,3]" => [1,2,3], "[1,[2.0, 2.1, [2.2]],[3.0, 3.1]]" => [1,[2.0, 2.1, [2.2]],[3.0, 3.1]], "[2 + 2]" => [4], "[1,2,3] == [1,2,3]" => true, "[1,2,3] != [2,3,4]" => true, "[1,2,3] == [2,2,3]" => false, "[1,2,3] != [1,2,3]" => false, "[1,2,3][2]" => 3, "[1,2,3] + [4,5]" => [1,2,3,4,5], "[1,2,3, *[4,5]]" => [1,2,3,4,5], "[1,2,3, (*[4,5])]" => [1,2,3,4,5], "[1,2,3, ((*[4,5]))]" => [1,2,3,4,5], "[1,2,3] + [[4,5]]" => [1,2,3,[4,5]], "[1,2,3] + 4" => [1,2,3,4], "[1,2,3] << [4,5]" => [1,2,3,[4,5]], "[1,2,3] << {'a' => 1, 'b'=>2}" => [1,2,3,{'a' => 1, 'b'=>2}], "[1,2,3] << 4" => [1,2,3,4], "[1,2,3,4] - [2,3]" => [1,4], "[1,2,3,4] - [2,5]" => [1,3,4], "[1,2,3,4] - 2" => [1,3,4], "[1,2,3,[2],4] - 2" => [1,3,[2],4], "[1,2,3,[2,3],4] - [[2,3]]" => [1,2,3,4], "[1,2,3,3,2,4,2,3] - [2,3]" => [1,4], "[1,2,3,['a',1],['b',2]] - {'a' => 1, 'b'=>2}" => [1,2,3], "[1,2,3,{'a'=>1,'b'=>2}] - [{'a' => 1, 'b'=>2}]" => [1,2,3], "[1,2,3] + {'a' => 1, 'b'=>2}" => [1,2,3,['a',1],['b',2]], }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "[1,2,3][a]" => :error, }.each do |source, result| it "should parse and raise error for '#{source}'" do expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError) end end { "{}" => {}, "{'a'=>1,'b'=>2}" => {'a'=>1,'b'=>2}, "{'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}" => {'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}, "{'a'=> 2 + 2}" => {'a'=> 4}, "{'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2}" => true, "{'a'=> 1, 'b'=>2} != {'x'=> 1, 'b'=>2}" => true, "{'a'=> 1, 'b'=>2} == {'a'=> 2, 'b'=>3}" => false, "{'a'=> 1, 'b'=>2} != {'a'=> 1, 'b'=>2}" => false, "{a => 1, b => 2}[b]" => 2, "{2+2 => sum, b => 2}[4]" => 'sum', "{'a'=>1, 'b'=>2} + {'c'=>3}" => {'a'=>1,'b'=>2,'c'=>3}, "{'a'=>1, 'b'=>2} + {'b'=>3}" => {'a'=>1,'b'=>3}, "{'a'=>1, 'b'=>2} + ['c', 3, 'b', 3]" => {'a'=>1,'b'=>3, 'c'=>3}, "{'a'=>1, 'b'=>2} + [['c', 3], ['b', 3]]" => {'a'=>1,'b'=>3, 'c'=>3}, "{'a'=>1, 'b'=>2} - {'b' => 3}" => {'a'=>1}, "{'a'=>1, 'b'=>2, 'c'=>3} - ['b', 'c']" => {'a'=>1}, "{'a'=>1, 'b'=>2, 'c'=>3} - 'c'" => {'a'=>1, 'b'=>2}, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "{'a' => 1, 'b'=>2} << 1" => :error, }.each do |source, result| it "should parse and raise error for '#{source}'" do expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError) end end end context "When the evaluator perform comparisons" do { "'a' == 'a'" => true, "'a' == 'b'" => false, "'a' != 'a'" => false, "'a' != 'b'" => true, "'a' < 'b' " => true, "'a' < 'a' " => false, "'b' < 'a' " => false, "'a' <= 'b'" => true, "'a' <= 'a'" => true, "'b' <= 'a'" => false, "'a' > 'b' " => false, "'a' > 'a' " => false, "'b' > 'a' " => true, "'a' >= 'b'" => false, "'a' >= 'a'" => true, "'b' >= 'a'" => true, "'a' == 'A'" => true, "'a' != 'A'" => false, "'a' > 'A'" => false, "'a' >= 'A'" => true, "'A' < 'a'" => false, "'A' <= 'a'" => true, "1 == 1" => true, "1 == 2" => false, "1 != 1" => false, "1 != 2" => true, "1 < 2 " => true, "1 < 1 " => false, "2 < 1 " => false, "1 <= 2" => true, "1 <= 1" => true, "2 <= 1" => false, "1 > 2 " => false, "1 > 1 " => false, "2 > 1 " => true, "1 >= 2" => false, "1 >= 1" => true, "2 >= 1" => true, "1 == 1.0 " => true, "1 < 1.1 " => true, "1.0 == 1 " => true, "1.0 < 2 " => true, "'1.0' < 'a'" => true, "'1.0' < '' " => false, "'1.0' < ' '" => false, "'a' > '1.0'" => true, "/.*/ == /.*/ " => true, "/.*/ != /a.*/" => true, "true == true " => true, "false == false" => true, "true == false" => false, "Timestamp(1) < Timestamp(2)" => true, "Timespan(1) < Timespan(2)" => true, "Timestamp(1) > Timestamp(2)" => false, "Timespan(1) > Timespan(2)" => false, "Timestamp(1) == Timestamp(1)" => true, "Timespan(1) == Timespan(1)" => true, "1 < Timestamp(2)" => true, "1 < Timespan(2)" => true, "1 > Timestamp(2)" => false, "1 > Timespan(2)" => false, "1 == Timestamp(1)" => true, "1 == Timespan(1)" => true, "1.0 < Timestamp(2)" => true, "1.0 < Timespan(2)" => true, "1.0 > Timestamp(2)" => false, "1.0 > Timespan(2)" => false, "1.0 == Timestamp(1)" => true, "1.0 == Timespan(1)" => true, "Timestamp(1) < 2" => true, "Timespan(1) < 2" => true, "Timestamp(1) > 2" => false, "Timespan(1) > 2" => false, "Timestamp(1) == 1" => true, "Timespan(1) == 1" => true, "Timestamp(1) < 2.0" => true, "Timespan(1) < 2.0" => true, "Timestamp(1) > 2.0" => false, "Timespan(1) > 2.0" => false, "Timestamp(1) == 1.0" => true, "Timespan(1) == 1.0" => true, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "a > 1" => /String > Integer/, "a >= 1" => /String >= Integer/, "a < 1" => /String < Integer/, "a <= 1" => /String <= Integer/, "1 > a" => /Integer > String/, "1 >= a" => /Integer >= String/, "1 < a" => /Integer < String/, "1 <= a" => /Integer <= String/, }.each do | source, error| it "should not allow comparison of String and Number '#{source}'" do expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(error) end end { "'a' =~ /.*/" => true, "'a' =~ '.*'" => true, "/.*/ != /a.*/" => true, "'a' !~ /b.*/" => true, "'a' !~ 'b.*'" => true, '$x = a; a =~ "$x.*"' => true, "a =~ Pattern['a.*']" => true, "a =~ Regexp['a.*']" => false, # String is not subtype of Regexp. PUP-957 "$x = /a.*/ a =~ $x" => true, "$x = Pattern['a.*'] a =~ $x" => true, "1 =~ Integer" => true, "1 !~ Integer" => false, "undef =~ NotUndef" => false, "undef !~ NotUndef" => true, "[1,2,3] =~ Array[Integer[1,10]]" => true, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "666 =~ /6/" => :error, "[a] =~ /a/" => :error, "{a=>1} =~ /a/" => :error, "/a/ =~ /a/" => :error, "Array =~ /A/" => :error, }.each do |source, result| it "should parse and raise error for '#{source}'" do expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError) end end { "1 in [1,2,3]" => true, "4 in [1,2,3]" => false, "a in {x=>1, a=>2}" => true, "z in {x=>1, a=>2}" => false, "ana in bananas" => true, "xxx in bananas" => false, "/ana/ in bananas" => true, "/xxx/ in bananas" => false, "FILE in profiler" => false, # FILE is a type, not a String "'FILE' in profiler" => true, "String[1] in bananas" => false, # Philosophically true though :-) "ana in 'BANANAS'" => true, "/ana/ in 'BANANAS'" => false, "/ANA/ in 'BANANAS'" => true, "xxx in 'BANANAS'" => false, "[2,3] in [1,[2,3],4]" => true, "[2,4] in [1,[2,3],4]" => false, "[a,b] in ['A',['A','B'],'C']" => true, "[x,y] in ['A',['A','B'],'C']" => false, "a in {a=>1}" => true, "x in {a=>1}" => false, "'A' in {a=>1}" => true, "'X' in {a=>1}" => false, "a in {'A'=>1}" => true, "x in {'A'=>1}" => false, "/xxx/ in {'aaaxxxbbb'=>1}" => true, "/yyy/ in {'aaaxxxbbb'=>1}" => false, "15 in [1, 0xf]" => true, "15 in [1, '0xf']" => false, "'15' in [1, 0xf]" => false, "15 in [1, 115]" => false, "1 in [11, '111']" => false, "'1' in [11, '111']" => false, "Array[Integer] in [2, 3]" => false, "Array[Integer] in [2, [3, 4]]" => true, "Array[Integer] in [2, [a, 4]]" => false, "Integer in { 2 =>'a'}" => true, "Integer[5,10] in [1,5,3]" => true, "Integer[5,10] in [1,2,3]" => false, "Integer in {'a'=>'a'}" => false, "Integer in {'a'=>1}" => false, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "if /(ana)/ in bananas {$1}" => 'ana', "if /(xyz)/ in bananas {$1} else {$1}" => nil, "$a = bananas =~ /(ana)/; $b = /(xyz)/ in bananas; $1" => 'ana', "$a = xyz =~ /(xyz)/; $b = /(ana)/ in bananas; $1" => 'ana', "if /p/ in [pineapple, bananas] {$0}" => 'p', "if /b/ in [pineapple, bananas] {$0}" => 'b', }.each do |source, result| it "sets match variables for a regexp search using in such that '#{source}' produces '#{result}'" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { 'Any' => ['NotUndef', 'Data', 'Scalar', 'Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern', 'Collection', 'Array', 'Hash', 'CatalogEntry', 'Resource', 'Class', 'Undef', 'File' ], # Note, Data > Collection is false (so not included) 'Data' => ['ScalarData', 'Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern', 'Array[Data]', 'Hash[String,Data]',], 'Scalar' => ['Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern'], 'Numeric' => ['Integer', 'Float'], 'CatalogEntry' => ['Class', 'Resource', 'File'], 'Integer[1,10]' => ['Integer[2,3]'], }.each do |general, specials| specials.each do |special | it "should compute that #{general} > #{special}" do expect(parser.evaluate_string(scope, "#{general} > #{special}", __FILE__)).to eq(true) end it "should compute that #{special} < #{general}" do expect(parser.evaluate_string(scope, "#{special} < #{general}", __FILE__)).to eq(true) end it "should compute that #{general} != #{special}" do expect(parser.evaluate_string(scope, "#{special} != #{general}", __FILE__)).to eq(true) end end end { 'Integer[1,10] > Integer[2,3]' => true, 'Integer[1,10] == Integer[2,3]' => false, 'Integer[1,10] > Integer[0,5]' => false, 'Integer[1,10] > Integer[1,10]' => false, 'Integer[1,10] >= Integer[1,10]' => true, 'Integer[1,10] == Integer[1,10]' => true, }.each do |source, result| it "should parse and evaluate the integer range comparison expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end end context "When the evaluator performs arithmetic" do context "on Integers" do { "2+2" => 4, "2 + 2" => 4, "7 - 3" => 4, "6 * 3" => 18, "6 / 3" => 2, "6 % 3" => 0, "10 % 3" => 1, "-(6/3)" => -2, "-6/3 " => -2, "8 >> 1" => 4, "8 << 1" => 16, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end context "on Floats" do { "2.2 + 2.2" => 4.4, "7.7 - 3.3" => 4.4, "6.1 * 3.1" => 18.91, "6.6 / 3.3" => 2.0, "-(6.0/3.0)" => -2.0, "-6.0/3.0 " => -2.0, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "3.14 << 2" => :error, "3.14 >> 2" => :error, "6.6 % 3.3" => 0.0, "10.0 % 3.0" => 1.0, }.each do |source, result| it "should parse and raise error for '#{source}'" do expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError) end end end context "on strings requiring boxing to Numeric" do # turn strict mode off so behavior is not stubbed out before :each do Puppet[:strict] = :off end let(:logs) { [] } let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } let(:debugs) { logs.select { |log| log.level == :debug }.map { |log| log.message } } { "'2' + '2'" => 4, "'-2' + '2'" => 0, "'- 2' + '2'" => 0, '"-\t 2" + "2"' => 0, "'+2' + '2'" => 4, "'+ 2' + '2'" => 4, "'2.2' + '2.2'" => 4.4, "'-2.2' + '2.2'" => 0.0, "'0xF7' + '010'" => 0xFF, "'0xF7' + '0x8'" => 0xFF, "'0367' + '010'" => 0xFF, "'012.3' + '010'" => 20.3, "'-0x2' + '0x4'" => 2, "'+0x2' + '0x4'" => 6, "'-02' + '04'" => 2, "'+02' + '04'" => 6, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "'2' + 2" => 2, "'4' - 2" => 4, "'2' * 2" => 2, "'2' / 1" => 2, "'8' >> 1" => 8, "'4' << 1" => 4, "'10' % 3" => 10, }.each do |source, coerced_val| it "should warn about numeric coercion in '#{source}' when strict = warning" do Puppet[:strict] = :warning expect(Puppet::Pops::Evaluator::Runtime3Support::EvaluationError).not_to receive(:new) collect_notices(source) expect(warnings).to include(/The string '#{coerced_val}' was automatically coerced to the numerical value #{coerced_val}/) end it "should not warn about numeric coercion in '#{source}' if strict = off" do Puppet[:strict] = :off expect(Puppet::Pops::Evaluator::Runtime3Support::EvaluationError).not_to receive(:new) collect_notices(source) expect(warnings).to_not include(/The string '#{coerced_val}' was automatically coerced to the numerical value #{coerced_val}/) end it "should error when finding numeric coercion in '#{source}' if strict = error" do Puppet[:strict] = :error expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error {|error| expect(error.message).to match(/The string '#{coerced_val}' was automatically coerced to the numerical value #{coerced_val}/) expect(error.backtrace.first).to match(/runtime3_support\.rb.+optionally_fail/) } end end { "'0888' + '010'" => :error, "'0xWTF' + '010'" => :error, "'0x12.3' + '010'" => :error, '"-\n 2" + "2"' => :error, '"-\v 2" + "2"' => :error, '"-2\n" + "2"' => :error, '"-2\n " + "2"' => :error, }.each do |source, result| it "should parse and raise error for '#{source}'" do expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError) end end end end end # arithmetic context "When the evaluator evaluates assignment" do { "$a = 5" => 5, "$a = 5; $a" => 5, "$a = 5; $b = 6; $a" => 5, "$a = $b = 5; $a == $b" => true, "[$a] = 1 $a" => 1, "[$a] = [1] $a" => 1, "[$a, $b] = [1,2] $a+$b" => 3, "[$a, [$b, $c]] = [1,[2, 3]] $a+$b+$c" => 6, "[$a] = {a => 1} $a" => 1, "[$a, $b] = {a=>1,b=>2} $a+$b" => 3, "[$a, [$b, $c]] = {a=>1,[b,c] =>{b=>2, c=>3}} $a+$b+$c" => 6, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end [ "[a,b,c] = [1,2,3]", "[a,b,c] = {b=>2,c=>3,a=>1}", "[$a, $b] = 1", "[$a, $b] = [1,2,3]", "[$a, [$b,$c]] = [1,[2]]", "[$a, [$b,$c]] = [1,[2,3,4]]", "[$a, $b] = {a=>1}", "[$a, [$b, $c]] = {a=>1, b =>{b=>2, c=>3}}", ].each do |source| it "should parse and evaluate the expression '#{source}' to error" do expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(Puppet::ParseError) end end end context "When the evaluator evaluates conditionals" do { "if true {5}" => 5, "if false {5}" => nil, "if false {2} else {5}" => 5, "if false {2} elsif true {5}" => 5, "if false {2} elsif false {5}" => nil, "unless false {5}" => 5, "unless true {5}" => nil, "unless true {2} else {5}" => 5, "unless true {} else {5}" => 5, "$a = if true {5} $a" => 5, "$a = if false {5} $a" => nil, "$a = if false {2} else {5} $a" => 5, "$a = if false {2} elsif true {5} $a" => 5, "$a = if false {2} elsif false {5} $a" => nil, "$a = unless false {5} $a" => 5, "$a = unless true {5} $a" => nil, "$a = unless true {2} else {5} $a" => 5, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "case 1 { 1 : { yes } }" => 'yes', "case 2 { 1,2,3 : { yes} }" => 'yes', "case 2 { 1,3 : { no } 2: { yes} }" => 'yes', "case 2 { 1,3 : { no } 5: { no } default: { yes }}" => 'yes', "case 2 { 1,3 : { no } 5: { no } }" => nil, "case 'banana' { 1,3 : { no } /.*ana.*/: { yes } }" => 'yes', "case 'banana' { /.*(ana).*/: { $1 } }" => 'ana', "case [1] { Array : { yes } }" => 'yes', "case [1] { Array[String] : { no } Array[Integer]: { yes } }" => 'yes', "case 1 { Integer : { yes } Type[Integer] : { no } }" => 'yes', "case Integer { Integer : { no } Type[Integer] : { yes } }" => 'yes', # supports unfold "case ringo { *[paul, john, ringo, george] : { 'beatle' } }" => 'beatle', "case ringo { (*[paul, john, ringo, george]) : { 'beatle' } }" => 'beatle', "case undef { undef : { 'yes' } }" => 'yes', "case undef { *undef : { 'no' } default :{ 'yes' }}" => 'yes', "case [green, 2, whatever] { [/ee/, Integer[0,10], default] : { 'yes' } default :{ 'no' }}" => 'yes', "case [green, 2, whatever] { default :{ 'no' } [/ee/, Integer[0,10], default] : { 'yes' }}" => 'yes', "case {a=>1, b=>2, whatever=>3, extra => ignored} { { a => Integer[0,5], b => Integer[0,5], whatever => default } : { 'yes' } default : { 'no' }}" => 'yes', }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "2 ? { 1 => no, 2 => yes}" => 'yes', "3 ? { 1 => no, 2 => no, default => yes }" => 'yes', "3 ? { 1 => no, default => yes, 3 => no }" => 'no', "3 ? { 1 => no, 3 => no, default => yes }" => 'no', "4 ? { 1 => no, default => yes, 3 => no }" => 'yes', "4 ? { 1 => no, 3 => no, default => yes }" => 'yes', "'banana' ? { /.*(ana).*/ => $1 }" => 'ana', "[2] ? { Array[String] => yes, Array => yes}" => 'yes', "ringo ? *[paul, john, ringo, george] => 'beatle'" => 'beatle', "ringo ? (*[paul, john, ringo, george]) => 'beatle'"=> 'beatle', "undef ? undef => 'yes'" => 'yes', "undef ? {*undef => 'no', default => 'yes'}" => 'yes', "[green, 2, whatever] ? { [/ee/, Integer[0,10], default ] => 'yes', default => 'no'}" => 'yes', "{a=>1, b=>2, whatever=>3, extra => ignored} ? {{ a => Integer[0,5], b => Integer[0,5], whatever => default } => 'yes', default => 'no' }" => 'yes', }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end it 'fails if a selector does not match' do expect{parser.evaluate_string(scope, "2 ? 3 => 4")}.to raise_error(/No matching entry for selector parameter with value '2'/) end end context "When evaluator evaluated unfold" do { "*[1,2,3]" => [1,2,3], "*1" => [1], "*'a'" => ['a'] }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end it "should parse and evaluate the expression '*{a=>10, b=>20} to [['a',10],['b',20]]" do result = parser.evaluate_string(scope, '*{a=>10, b=>20}', __FILE__) expect(result).to include(['a', 10]) expect(result).to include(['b', 20]) end it "should create an array from an Iterator" do expect(parser.evaluate_string(scope, '[1,2,3].reverse_each', __FILE__).is_a?(Array)).to be(false) result = parser.evaluate_string(scope, '*[1,2,3].reverse_each', __FILE__) expect(result).to eql([3,2,1]) end end context "When evaluator performs [] operations" do { "[1,2,3][0]" => 1, "[1,2,3][2]" => 3, "[1,2,3][3]" => nil, "[1,2,3][-1]" => 3, "[1,2,3][-2]" => 2, "[1,2,3][-4]" => nil, "[1,2,3,4][0,2]" => [1,2], "[1,2,3,4][1,3]" => [2,3,4], "[1,2,3,4][-2,2]" => [3,4], "[1,2,3,4][-3,2]" => [2,3], "[1,2,3,4][3,5]" => [4], "[1,2,3,4][5,2]" => [], "[1,2,3,4][0,-1]" => [1,2,3,4], "[1,2,3,4][0,-2]" => [1,2,3], "[1,2,3,4][0,-4]" => [1], "[1,2,3,4][0,-5]" => [], "[1,2,3,4][-5,2]" => [1], "[1,2,3,4][-5,-3]" => [1,2], "[1,2,3,4][-6,-3]" => [1,2], "[1,2,3,4][2,-3]" => [], "[1,*[2,3],4]" => [1,2,3,4], "[1,*[2,3],4][1]" => 2, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "{a=>1, b=>2, c=>3}[a]" => 1, "{a=>1, b=>2, c=>3}[c]" => 3, "{a=>1, b=>2, c=>3}[x]" => nil, "{a=>1, b=>2, c=>3}[c,b]" => [3,2], "{a=>1, b=>2, c=>3}[a,b,c]" => [1,2,3], "{a=>{b=>{c=>'it works'}}}[a][b][c]" => 'it works', "$a = {undef => 10} $a[free_lunch]" => nil, "$a = {undef => 10} $a[undef]" => 10, "$a = {undef => 10} $a[$a[free_lunch]]" => 10, "$a = {} $a[free_lunch] == undef" => true, }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end { "'abc'[0]" => 'a', "'abc'[2]" => 'c', "'abc'[-1]" => 'c', "'abc'[-2]" => 'b', "'abc'[-3]" => 'a', "'abc'[-4]" => '', "'abc'[3]" => '', "abc[0]" => 'a', "abc[2]" => 'c', "abc[-1]" => 'c', "abc[-2]" => 'b', "abc[-3]" => 'a', "abc[-4]" => '', "abc[3]" => '', "'abcd'[0,2]" => 'ab', "'abcd'[1,3]" => 'bcd', "'abcd'[-2,2]" => 'cd', "'abcd'[-3,2]" => 'bc', "'abcd'[3,5]" => 'd', "'abcd'[5,2]" => '', "'abcd'[0,-1]" => 'abcd', "'abcd'[0,-2]" => 'abc', "'abcd'[0,-4]" => 'a', "'abcd'[0,-5]" => '', "'abcd'[-5,2]" => 'a', "'abcd'[-5,-3]" => 'ab', "'abcd'[-6,-3]" => 'ab', "'abcd'[2,-3]" => '', }.each do |source, result| it "should parse and evaluate the expression '#{source}' to #{result}" do expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result) end end # Type operations (full set tested by tests covering type calculator) { "Array[Integer]" => types.array_of(types.integer), "Array[Integer,1]" => types.array_of(types.integer, types.range(1, :default)), "Array[Integer,1,2]" => types.array_of(types.integer, types.range(1, 2)), "Array[Integer,Integer[1,2]]" => types.array_of(types.integer, types.range(1, 2)), "Array[Integer,Integer[1]]" => types.array_of(types.integer, types.range(1, :default)), "Hash[Integer,Integer]" => types.hash_of(types.integer, types.integer), "Hash[Integer,Integer,1]" => types.hash_of(types.integer, types.integer, types.range(1, :default)), "Hash[Integer,Integer,1,2]" => types.hash_of(types.integer, types.integer, types.range(1, 2)), "Hash[Integer,Integer,Integer[1,2]]" => types.hash_of(types.integer, types.integer, types.range(1, 2)), "Hash[Integer,Integer,Integer[1]]" => types.hash_of(types.integer, types.integer, types.range(1, :default)), "Resource[File]" => types.resource('File'), "Resource['File']" => types.resource(types.resource('File')), "File[foo]" => types.resource('file', 'foo'), "File[foo, bar]" => [types.resource('file', 'foo'), types.resource('file', 'bar')], "Pattern[a, /b/, Pattern[c], Regexp[d]]" => types.pattern('a', 'b', 'c', 'd'), "String[1,2]" => types.string(types.range(1, 2)), "String[Integer[1,2]]" => types.string(types.range(1, 2)),
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/string_interpolation_spec.rb
spec/unit/pops/evaluator/string_interpolation_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do include EvaluatorRspecHelper context "When evaluator performs string interpolation" do it "should interpolate a bare word as a variable name, \"${var}\"" do a_block = block(var('a').set(literal(10)), string('value is ', text(fqn('a')), ' yo')) expect(evaluate(a_block)).to eq('value is 10 yo') end it "should interpolate a variable in a text expression, \"${$var}\"" do a_block = block(var('a').set(literal(10)), string('value is ', text(var(fqn('a'))), ' yo')) expect(evaluate(a_block)).to eq('value is 10 yo') end it "should interpolate a variable, \"$var\"" do a_block = block(var('a').set(literal(10)), string('value is ', var(fqn('a')), ' yo')) expect(evaluate(a_block)).to eq('value is 10 yo') end it "should interpolate any expression in a text expression, \"${$var*2}\"" do a_block = block(var('a').set(literal(5)), string('value is ', text(var(fqn('a')) * literal(2)) , ' yo')) expect(evaluate(a_block)).to eq('value is 10 yo') end it "should interpolate any expression without a text expression, \"${$var*2}\"" do # there is no concrete syntax for this, but the parser can generate this simpler # equivalent form where the expression is not wrapped in a TextExpression a_block = block(var('a').set(literal(5)), string('value is ', var(fqn('a')) * literal(2) , ' yo')) expect(evaluate(a_block)).to eq('value is 10 yo') end # TODO: Add function call tests - Pending implementation of calls in the evaluator end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/evaluator_rspec_helper.rb
spec/unit/pops/evaluator/evaluator_rspec_helper.rb
require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' require File.join(File.dirname(__FILE__), '/../factory_rspec_helper') module EvaluatorRspecHelper include FactoryRspecHelper # Evaluate a Factory wrapper round a model object in top scope + named scope # Optionally pass two or three model objects (typically blocks) to be executed # in top scope, named scope, and then top scope again. If a named_scope is used, it must # be preceded by the name of the scope. # The optional block is executed before the result of the last specified model object # is evaluated. This block gets the top scope as an argument. The intent is to pass # a block that asserts the state of the top scope after the operations. # def evaluate in_top_scope, scopename="x", in_named_scope = nil, in_top_scope_again = nil, &block node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) # compiler creates the top scope if one is not present top_scope = compiler.topscope() # top_scope = Puppet::Parser::Scope.new(compiler) evaluator = Puppet::Pops::Evaluator::EvaluatorImpl.new Puppet.override(:loaders => compiler.loaders) do result = evaluator.evaluate(in_top_scope.model, top_scope) if in_named_scope other_scope = Puppet::Parser::Scope.new(compiler) result = evaluator.evaluate(in_named_scope.model, other_scope) end if in_top_scope_again result = evaluator.evaluate(in_top_scope_again.model, top_scope) end if block_given? block.call(top_scope) end result end end # Evaluate a Factory wrapper round a model object in top scope + local scope # Optionally pass two or three model objects (typically blocks) to be executed # in top scope, local scope, and then top scope again # The optional block is executed before the result of the last specified model object # is evaluated. This block gets the top scope as an argument. The intent is to pass # a block that asserts the state of the top scope after the operations. # def evaluate_l in_top_scope, in_local_scope = nil, in_top_scope_again = nil, &block node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) # compiler creates the top scope if one is not present top_scope = compiler.topscope() evaluator = Puppet::Pops::Evaluator::EvaluatorImpl.new Puppet.override(:loaders => compiler.loaders) do result = evaluator.evaluate(in_top_scope.model, top_scope) if in_local_scope # This is really bad in 3.x scope top_scope.with_guarded_scope do top_scope.new_ephemeral(true) result = evaluator.evaluate(in_local_scope.model, top_scope) end end if in_top_scope_again result = evaluator.evaluate(in_top_scope_again.model, top_scope) end if block_given? block.call(top_scope) end result end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/json_strict_literal_evaluator_spec.rb
spec/unit/pops/evaluator/json_strict_literal_evaluator_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/json_strict_literal_evaluator' describe "Puppet::Pops::Evaluator::JsonStrictLiteralEvaluator" do let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new } let(:leval) { Puppet::Pops::Evaluator::JsonStrictLiteralEvaluator.new } { "1" => 1, "3.14" => 3.14, "true" => true, "false" => false, "'1'" => '1', "'a'" => 'a', '"a"' => 'a', 'a' => 'a', 'a::b' => 'a::b', 'undef' => nil, # collections '[1,2,3]' => [1,2,3], '{a=>1,b=>2}' => {'a' => 1, 'b' => 2}, '[undef]' => [nil], '{a=>undef}' => { 'a' => nil } }.each do |source, result| it "evaluates '#{source}' to #{result}" do expect(leval.literal(parser.parse_string(source))).to eq(result) end end [ '1+1', 'File', '[1,2, 1+2]', '{a=>1+1}', 'Integer[1]', '"x$y"', '"x${y}z"' ].each do |source| it "throws :not_literal for non literal expression '#{source}'" do expect{leval.literal(parser.parse_string('1+1'))}.to throw_symbol(:not_literal) end end [ 'default', '/.*/', '{1=>100}', '{undef => 10}', '{default => 10}', '{/.*/ => 10}', '{"ok" => {1 => 100}}', '[default]', '[[default]]', '[/.*/]', '[[/.*/]]', '[{1 => 100}]', ].each do |source| it "throws :not_literal for values not representable as pure JSON '#{source}'" do expect{leval.literal(parser.parse_string('1+1'))}.to throw_symbol(:not_literal) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/variables_spec.rb
spec/unit/pops/evaluator/variables_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' # This file contains basic testing of variable references and assignments # using a top scope and a local scope. # It does not test variables and named scopes. # # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Impl::EvaluatorImpl' do include EvaluatorRspecHelper context "When the evaluator deals with variables" do context "it should handle" do it "simple assignment and dereference" do expect(evaluate_l(block( var('a').set(literal(2)+literal(2)), var('a')))).to eq(4) end it "local scope shadows top scope" do top_scope_block = block( var('a').set(literal(2)+literal(2)), var('a')) local_scope_block = block( var('a').set(var('a') + literal(2)), var('a')) expect(evaluate_l(top_scope_block, local_scope_block)).to eq(6) end it "shadowed in local does not affect parent scope" do top_scope_block = block( var('a').set(literal(2)+literal(2)), var('a')) local_scope_block = block( var('a').set(var('a') + literal(2)), var('a')) top_scope_again = var('a') expect(evaluate_l(top_scope_block, local_scope_block, top_scope_again)).to eq(4) end it "access to global names works in top scope" do top_scope_block = block( var('a').set(literal(2)+literal(2)), var('::a')) expect(evaluate_l(top_scope_block)).to eq(4) end it "access to global names works in local scope" do top_scope_block = block( var('a').set(literal(2)+literal(2))) local_scope_block = block( var('a').set(literal(100)), var('b').set(var('::a')+literal(2)), var('b')) expect(evaluate_l(top_scope_block, local_scope_block)).to eq(6) end it "can not change a variable value in same scope" do expect { evaluate_l(block(var('a').set(literal(10)), var('a').set(literal(20)))) }.to raise_error(/Cannot reassign variable '\$a'/) end context "access to numeric variables" do it "without a match" do expect(evaluate_l(block(literal(2) + literal(2), [var(0), var(1), var(2), var(3)]))).to eq([nil, nil, nil, nil]) end it "after a match" do expect(evaluate_l(block(literal('abc') =~ literal(/(a)(b)(c)/), [var(0), var(1), var(2), var(3)]))).to eq(['abc', 'a', 'b', 'c']) end it "after a failed match" do expect(evaluate_l(block(literal('abc') =~ literal(/(x)(y)(z)/), [var(0), var(1), var(2), var(3)]))).to eq([nil, nil, nil, nil]) end it "a failed match does not alter previous match" do expect(evaluate_l(block( literal('abc') =~ literal(/(a)(b)(c)/), literal('abc') =~ literal(/(x)(y)(z)/), [var(0), var(1), var(2), var(3)]))).to eq(['abc', 'a', 'b', 'c']) end it "a new match completely shadows previous match" do expect(evaluate_l(block( literal('abc') =~ literal(/(a)(b)(c)/), literal('abc') =~ literal(/(a)bc/), [var(0), var(1), var(2), var(3)]))).to eq(['abc', 'a', nil, nil]) end it "after a match with variable referencing a non existing group" do expect(evaluate_l(block(literal('abc') =~ literal(/(a)(b)(c)/), [var(0), var(1), var(2), var(3), var(4)]))).to eq(['abc', 'a', 'b', 'c', nil]) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/deferred_resolver_spec.rb
spec/unit/pops/evaluator/deferred_resolver_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' Puppet::Type.newtype(:test_deferred) do newparam(:name) newproperty(:value) end describe Puppet::Pops::Evaluator::DeferredResolver do include PuppetSpec::Compiler let(:environment) { Puppet::Node::Environment.create(:testing, []) } let(:facts) { Puppet::Node::Facts.new('node.example.com') } def compile_and_resolve_catalog(code, preprocess = false) catalog = compile_to_catalog(code) described_class.resolve_and_replace(facts, catalog, environment, preprocess) catalog end it 'resolves deferred values in a catalog' do catalog = compile_and_resolve_catalog(<<~END, true) notify { "deferred": message => Deferred("join", [[1,2,3], ":"]) } END expect(catalog.resource(:notify, 'deferred')[:message]).to eq('1:2:3') end it 'lazily resolves deferred values in a catalog' do catalog = compile_and_resolve_catalog(<<~END) notify { "deferred": message => Deferred("join", [[1,2,3], ":"]) } END deferred = catalog.resource(:notify, 'deferred')[:message] expect(deferred.resolve).to eq('1:2:3') end it 'lazily resolves nested deferred values in a catalog' do catalog = compile_and_resolve_catalog(<<~END) $args = Deferred("inline_epp", ["<%= 'a,b,c' %>"]) notify { "deferred": message => Deferred("split", [$args, ","]) } END deferred = catalog.resource(:notify, 'deferred')[:message] expect(deferred.resolve).to eq(["a", "b", "c"]) end it 'marks the parameter as sensitive when passed an array containing a Sensitive instance' do catalog = compile_and_resolve_catalog(<<~END) test_deferred { "deferred": value => Deferred('join', [['a', Sensitive('b')], ':']) } END resource = catalog.resource(:test_deferred, 'deferred') expect(resource.sensitive_parameters).to eq([:value]) end it 'marks the parameter as sensitive when passed a hash containing a Sensitive key' do catalog = compile_and_resolve_catalog(<<~END) test_deferred { "deferred": value => Deferred('keys', [{Sensitive('key') => 'value'}]) } END resource = catalog.resource(:test_deferred, 'deferred') expect(resource.sensitive_parameters).to eq([:value]) end it 'marks the parameter as sensitive when passed a hash containing a Sensitive value' do catalog = compile_and_resolve_catalog(<<~END) test_deferred { "deferred": value => Deferred('values', [{key => Sensitive('value')}]) } END resource = catalog.resource(:test_deferred, 'deferred') expect(resource.sensitive_parameters).to eq([:value]) end it 'marks the parameter as sensitive when passed a nested Deferred containing a Sensitive type' do catalog = compile_and_resolve_catalog(<<~END) $vars = {'token' => Deferred('new', [Sensitive, "hello"])} test_deferred { "deferred": value => Deferred('inline_epp', ['<%= $token %>', $vars]) } END resource = catalog.resource(:test_deferred, 'deferred') expect(resource.sensitive_parameters).to eq([:value]) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/conditionals_spec.rb
spec/unit/pops/evaluator/conditionals_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') # This file contains testing of Conditionals, if, case, unless, selector # describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do include EvaluatorRspecHelper context "When the evaluator evaluates" do context "an if expression" do it 'should output the expected result when dumped' do expect(dump(IF(literal(true), literal(2), literal(5)))).to eq unindent(<<-TEXT (if true (then 2) (else 5)) TEXT ) end it 'if true {5} == 5' do expect(evaluate(IF(literal(true), literal(5)))).to eq(5) end it 'if false {5} == nil' do expect(evaluate(IF(literal(false), literal(5)))).to eq(nil) end it 'if false {2} else {5} == 5' do expect(evaluate(IF(literal(false), literal(2), literal(5)))).to eq(5) end it 'if false {2} elsif true {5} == 5' do expect(evaluate(IF(literal(false), literal(2), IF(literal(true), literal(5))))).to eq(5) end it 'if false {2} elsif false {5} == nil' do expect(evaluate(IF(literal(false), literal(2), IF(literal(false), literal(5))))).to eq(nil) end end context "an unless expression" do it 'should output the expected result when dumped' do expect(dump(UNLESS(literal(true), literal(2), literal(5)))).to eq unindent(<<-TEXT (unless true (then 2) (else 5)) TEXT ) end it 'unless false {5} == 5' do expect(evaluate(UNLESS(literal(false), literal(5)))).to eq(5) end it 'unless true {5} == nil' do expect(evaluate(UNLESS(literal(true), literal(5)))).to eq(nil) end it 'unless true {2} else {5} == 5' do expect(evaluate(UNLESS(literal(true), literal(2), literal(5)))).to eq(5) end it 'unless true {2} elsif true {5} == 5' do # not supported by concrete syntax expect(evaluate(UNLESS(literal(true), literal(2), IF(literal(true), literal(5))))).to eq(5) end it 'unless true {2} elsif false {5} == nil' do # not supported by concrete syntax expect(evaluate(UNLESS(literal(true), literal(2), IF(literal(false), literal(5))))).to eq(nil) end end context "a case expression" do it 'should output the expected result when dumped' do expect(dump(CASE(literal(2), WHEN(literal(1), literal('wat')), WHEN([literal(2), literal(3)], literal('w00t')) ))).to eq unindent(<<-TEXT (case 2 (when (1) (then 'wat')) (when (2 3) (then 'w00t'))) TEXT ) expect(dump(CASE(literal(2), WHEN(literal(1), literal('wat')), WHEN([literal(2), literal(3)], literal('w00t')) ).default(literal(4)))).to eq unindent(<<-TEXT (case 2 (when (1) (then 'wat')) (when (2 3) (then 'w00t')) (when (:default) (then 4))) TEXT ) end it "case 1 { 1 : { 'w00t'} } == 'w00t'" do expect(evaluate(CASE(literal(1), WHEN(literal(1), literal('w00t'))))).to eq('w00t') end it "case 2 { 1,2,3 : { 'w00t'} } == 'w00t'" do expect(evaluate(CASE(literal(2), WHEN([literal(1), literal(2), literal(3)], literal('w00t'))))).to eq('w00t') end it "case 2 { 1,3 : {'wat'} 2: { 'w00t'} } == 'w00t'" do expect(evaluate(CASE(literal(2), WHEN([literal(1), literal(3)], literal('wat')), WHEN(literal(2), literal('w00t'))))).to eq('w00t') end it "case 2 { 1,3 : {'wat'} 5: { 'wat'} default: {'w00t'}} == 'w00t'" do expect(evaluate(CASE(literal(2), WHEN([literal(1), literal(3)], literal('wat')), WHEN(literal(5), literal('wat'))).default(literal('w00t')) )).to eq('w00t') end it "case 2 { 1,3 : {'wat'} 5: { 'wat'} } == nil" do expect(evaluate(CASE(literal(2), WHEN([literal(1), literal(3)], literal('wat')), WHEN(literal(5), literal('wat'))) )).to eq(nil) end it "case 'banana' { 1,3 : {'wat'} /.*ana.*/: { 'w00t'} } == w00t" do expect(evaluate(CASE(literal('banana'), WHEN([literal(1), literal(3)], literal('wat')), WHEN(literal(/.*ana.*/), literal('w00t'))) )).to eq('w00t') end context "with regular expressions" do it "should set numeric variables from the match" do expect(evaluate(CASE(literal('banana'), WHEN([literal(1), literal(3)], literal('wat')), WHEN(literal(/.*(ana).*/), var(1))) )).to eq('ana') end end end context "select expressions" do it 'should output the expected result when dumped' do expect(dump(literal(2).select( MAP(literal(1), literal('wat')), MAP(literal(2), literal('w00t')) ))).to eq("(? 2 (1 => 'wat') (2 => 'w00t'))") end it "1 ? {1 => 'w00t'} == 'w00t'" do expect(evaluate(literal(1).select(MAP(literal(1), literal('w00t'))))).to eq('w00t') end it "2 ? {1 => 'wat', 2 => 'w00t'} == 'w00t'" do expect(evaluate(literal(2).select( MAP(literal(1), literal('wat')), MAP(literal(2), literal('w00t')) ))).to eq('w00t') end it "3 ? {1 => 'wat', 2 => 'wat', default => 'w00t'} == 'w00t'" do expect(evaluate(literal(3).select( MAP(literal(1), literal('wat')), MAP(literal(2), literal('wat')), MAP(literal(:default), literal('w00t')) ))).to eq('w00t') end it "3 ? {1 => 'wat', default => 'w00t', 2 => 'wat'} == 'w00t'" do expect(evaluate(literal(3).select( MAP(literal(1), literal('wat')), MAP(literal(:default), literal('w00t')), MAP(literal(2), literal('wat')) ))).to eq('w00t') end it "should set numerical variables from match" do expect(evaluate(literal('banana').select( MAP(literal(1), literal('wat')), MAP(literal(/.*(ana).*/), var(1)) ))).to eq('ana') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/collections_ops_spec.rb
spec/unit/pops/evaluator/collections_ops_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' require 'puppet/pops/types/type_factory' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl/Concat/Delete' do include EvaluatorRspecHelper context 'The evaluator when operating on an Array' do it 'concatenates another array using +' do expect(evaluate(literal([1,2,3]) + literal([4,5]))).to eql([1,2,3,4,5]) end it 'concatenates another nested array using +' do expect(evaluate(literal([1,2,3]) + literal([[4,5]]))).to eql([1,2,3,[4,5]]) end it 'concatenates a hash by converting it to array' do expect(evaluate(literal([1,2,3]) + literal({'a' => 1, 'b'=>2}))).to eql([1,2,3,['a',1],['b',2]]) end it 'concatenates a non array value with +' do expect(evaluate(literal([1,2,3]) + literal(4))).to eql([1,2,3,4]) end it 'appends another array using <<' do expect(evaluate(literal([1,2,3]) << literal([4,5]))).to eql([1,2,3,[4,5]]) end it 'appends a hash without conversion when << operator is used' do expect(evaluate(literal([1,2,3]) << literal({'a' => 1, 'b'=>2}))).to eql([1,2,3,{'a' => 1, 'b'=>2}]) end it 'appends another non array using <<' do expect(evaluate(literal([1,2,3]) << literal(4))).to eql([1,2,3,4]) end it 'computes the difference with another array using -' do expect(evaluate(literal([1,2,3,4]) - literal([2,3]))).to eql([1,4]) end it 'computes the difference with a non array using -' do expect(evaluate(literal([1,2,3,4]) - literal(2))).to eql([1,3,4]) end it 'does not recurse into nested arrays when computing diff' do expect(evaluate(literal([1,2,3,[2],4]) - literal(2))).to eql([1,3,[2],4]) end it 'can compute diff with sub arrays' do expect(evaluate(literal([1,2,3,[2,3],4]) - literal([[2,3]]))).to eql([1,2,3,4]) end it 'computes difference by removing all matching instances' do expect(evaluate(literal([1,2,3,3,2,4,2,3]) - literal([2,3]))).to eql([1,4]) end it 'computes difference with a hash by converting it to an array' do expect(evaluate(literal([1,2,3,['a',1],['b',2]]) - literal({'a' => 1, 'b'=>2}))).to eql([1,2,3]) end it 'diffs hashes when given in an array' do expect(evaluate(literal([1,2,3,{'a'=>1,'b'=>2}]) - literal([{'a' => 1, 'b'=>2}]))).to eql([1,2,3]) end it 'raises and error when LHS of << is a hash' do expect { evaluate(literal({'a' => 1, 'b'=>2}) << literal(1)) }.to raise_error(/Operator '<<' is not applicable to a Hash/) end end context 'The evaluator when operating on a Hash' do it 'merges with another Hash using +' do expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal({'c' => 3}))).to eql({'a' => 1, 'b'=>2, 'c' => 3}) end it 'merges RHS on top of LHS ' do expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal({'c' => 3, 'b'=>3}))).to eql({'a' => 1, 'b'=>3, 'c' => 3}) end it 'merges a flat array of pairs converted to a hash' do expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal(['c', 3, 'b', 3]))).to eql({'a' => 1, 'b'=>3, 'c' => 3}) end it 'merges an array converted to a hash' do expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal([['c', 3], ['b', 3]]))).to eql({'a' => 1, 'b'=>3, 'c' => 3}) end it 'computes difference with another hash using the - operator' do expect(evaluate(literal({'a' => 1, 'b'=>2}) - literal({'b' => 3}))).to eql({'a' => 1 }) end it 'computes difference with an array by treating array as array of keys' do expect(evaluate(literal({'a' => 1, 'b'=>2,'c'=>3}) - literal(['b', 'c']))).to eql({'a' => 1 }) end it 'computes difference with a non array/hash by treating it as a key' do expect(evaluate(literal({'a' => 1, 'b'=>2,'c'=>3}) - literal('c'))).to eql({'a' => 1, 'b' => 2 }) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/runtime3_converter_spec.rb
spec/unit/pops/evaluator/runtime3_converter_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/types/type_factory' describe 'when converting to 3.x' do let(:converter) { Puppet::Pops::Evaluator::Runtime3Converter.instance } it "converts a resource type starting with Class without confusing it with exact match on 'class'" do t = Puppet::Pops::Types::TypeFactory.resource('classroom', 'kermit') converted = converter.catalog_type_to_split_type_title(t) expect(converted).to eql(['classroom', 'kermit']) end it "converts a resource type of exactly 'Class'" do t = Puppet::Pops::Types::TypeFactory.resource('class', 'kermit') converted = converter.catalog_type_to_split_type_title(t) expect(converted).to eql(['class', 'kermit']) end it "errors on attempts to convert an 'Iterator'" do expect { converter.convert(Puppet::Pops::Types::Iterable.on((1..3)), {}, nil) }.to raise_error(Puppet::Error, /Use of an Iterator is not supported here/) end it 'does not convert a SemVer instance to string' do v = SemanticPuppet::Version.parse('1.0.0') expect(converter.convert(v, {}, nil)).to equal(v) end it 'converts top level symbol :undef to the given undef value' do expect(converter.convert(:undef, {}, 'undef value')).to eql('undef value') end it 'converts top level nil value to the given undef value' do expect(converter.convert(nil, {}, 'undef value')).to eql('undef value') end it 'converts nested :undef in a hash to nil' do expect(converter.convert({'foo' => :undef}, {}, 'undef value')).to eql({'foo' => nil}) end it 'converts nested :undef in an array to nil' do expect(converter.convert(['boo', :undef], {}, 'undef value')).to eql(['boo', nil]) end it 'converts deeply nested :undef in to nil' do expect(converter.convert({'foo' => [[:undef]], 'bar' => { 'x' => :undef }}, {}, 'undef value')).to eql({'foo' => [[nil]], 'bar' => { 'x' => nil}}) end it 'does not converts nil to given undef value when nested in an array' do expect(converter.convert({'foo' => nil}, {}, 'undef value')).to eql({'foo' => nil}) end it 'does not convert top level symbols' do expect(converter.convert(:default, {}, 'undef value')).to eql(:default) expect(converter.convert(:whatever, {}, 'undef value')).to eql(:whatever) end it 'does not convert nested symbols' do expect(converter.convert([:default], {}, 'undef value')).to eql([:default]) expect(converter.convert([:whatever], {}, 'undef value')).to eql([:whatever]) end it 'does not convert a Regex instance to string' do v = /^[A-Z]$/ expect(converter.convert(v, {}, nil)).to equal(v) end it 'does not convert a Version instance to string' do v = SemanticPuppet::Version.parse('1.0.0') expect(converter.convert(v, {}, nil)).to equal(v) end it 'does not convert a VersionRange instance to string' do v = SemanticPuppet::VersionRange.parse('>=1.0.0') expect(converter.convert(v, {}, nil)).to equal(v) end it 'does not convert a Timespan instance to string' do v = Puppet::Pops::Time::Timespan.new(1234) expect(converter.convert(v, {}, nil)).to equal(v) end it 'does not convert a Timestamp instance to string' do v = Puppet::Pops::Time::Timestamp.now expect(converter.convert(v, {}, nil)).to equal(v) end it 'does not convert a Sensitive instance to string' do v = Puppet::Pops::Types::PSensitiveType::Sensitive.new("don't reveal this") expect(converter.convert(v, {}, nil)).to equal(v) end it 'does not convert a Binary instance to string' do v = Puppet::Pops::Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==') expect(converter.convert(v, {}, nil)).to equal(v) end context 'the Runtime3FunctionArgumentConverter' do let(:converter) { Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.instance } it 'converts a Regex instance to string' do c = converter.convert(/^[A-Z]$/, {}, nil) expect(c).to be_a(String) expect(c).to eql('/^[A-Z]$/') end it 'converts a Version instance to string' do c = converter.convert(SemanticPuppet::Version.parse('1.0.0'), {}, nil) expect(c).to be_a(String) expect(c).to eql('1.0.0') end it 'converts a VersionRange instance to string' do c = converter.convert(SemanticPuppet::VersionRange.parse('>=1.0.0'), {}, nil) expect(c).to be_a(String) expect(c).to eql('>=1.0.0') end it 'converts a Timespan instance to string' do c = converter.convert(Puppet::Pops::Time::Timespan.new(1234), {}, nil) expect(c).to be_a(String) expect(c).to eql('0-00:00:00.1234') end it 'converts a Timestamp instance to string' do c = converter.convert(Puppet::Pops::Time::Timestamp.parse('2016-09-15T12:24:47.193 UTC'), {}, nil) expect(c).to be_a(String) expect(c).to eql('2016-09-15T12:24:47.193000000 UTC') end it 'converts a Binary instance to string' do b64 = 'w5ZzdGVuIG1lZCByw7ZzdGVuCg==' c = converter.convert(Puppet::Pops::Types::PBinaryType::Binary.from_base64(b64), {}, nil) expect(c).to be_a(String) expect(c).to eql(b64) end it 'does not convert a Sensitive instance to string' do v = Puppet::Pops::Types::PSensitiveType::Sensitive.new("don't reveal this") expect(converter.convert(v, {}, nil)).to equal(v) end it 'errors if an Integer is too big' do too_big = 0x7fffffffffffffff + 1 expect do converter.convert(too_big, {}, nil) end.to raise_error(/Use of a Ruby Integer outside of Puppet Integer max range, got/) end it 'errors if an Integer is too small' do too_small = -0x8000000000000000-1 expect do converter.convert(too_small, {}, nil) end.to raise_error(/Use of a Ruby Integer outside of Puppet Integer min range, got/) end it 'errors if a BigDecimal is out of range for Float' do big_dec = BigDecimal("123456789123456789.1415") expect do converter.convert(big_dec, {}, nil) end.to raise_error(/Use of a Ruby BigDecimal value outside Puppet Float range, got/) end it 'BigDecimal values in Float range are converted' do big_dec = BigDecimal("3.1415") f = converter.convert(big_dec, {}, nil) expect(f.class).to be(Float) end it 'errors when Integer is out of range in a structure' do structure = {'key' => [{ 'key' => [0x7fffffffffffffff + 1]}]} expect do converter.convert(structure, {}, nil) end.to raise_error(/Use of a Ruby Integer outside of Puppet Integer max range, got/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/arithmetic_ops_spec.rb
spec/unit/pops/evaluator/arithmetic_ops_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do include EvaluatorRspecHelper context "When the evaluator performs arithmetic" do context "on Integers" do it "2 + 2 == 4" do; expect(evaluate(literal(2) + literal(2))).to eq(4) ; end it "7 - 3 == 4" do; expect(evaluate(literal(7) - literal(3))).to eq(4) ; end it "6 * 3 == 18" do; expect(evaluate(literal(6) * literal(3))).to eq(18); end it "6 / 3 == 2" do; expect(evaluate(literal(6) / literal(3))).to eq(2) ; end it "6 % 3 == 0" do; expect(evaluate(literal(6) % literal(3))).to eq(0) ; end it "10 % 3 == 1" do; expect(evaluate(literal(10) % literal(3))).to eq(1); end it "-(6/3) == -2" do; expect(evaluate(minus(literal(6) / literal(3)))).to eq(-2) ; end it "-6/3 == -2" do; expect(evaluate(minus(literal(6)) / literal(3))).to eq(-2) ; end it "8 >> 1 == 4" do; expect(evaluate(literal(8) >> literal(1))).to eq(4) ; end it "8 << 1 == 16" do; expect(evaluate(literal(8) << literal(1))).to eq(16); end it "8 >> -1 == 16" do; expect(evaluate(literal(8) >> literal(-1))).to eq(16) ; end it "8 << -1 == 4" do; expect(evaluate(literal(8) << literal(-1))).to eq(4); end end # 64 bit signed integer max and min MAX_INTEGER = 0x7fffffffffffffff MIN_INTEGER = -0x8000000000000000 context "on integer values that cause 64 bit overflow" do it "MAX + 1 => error" do expect{ evaluate(literal(MAX_INTEGER) + literal(1)) }.to raise_error(/resulted in a value outside of Puppet Integer max range/) end it "MAX - -1 => error" do expect{ evaluate(literal(MAX_INTEGER) - literal(-1)) }.to raise_error(/resulted in a value outside of Puppet Integer max range/) end it "MAX * 2 => error" do expect{ evaluate(literal(MAX_INTEGER) * literal(2)) }.to raise_error(/resulted in a value outside of Puppet Integer max range/) end it "(MAX+1)*2 / 2 => error" do expect{ evaluate(literal((MAX_INTEGER+1)*2) / literal(2)) }.to raise_error(/resulted in a value outside of Puppet Integer max range/) end it "MAX << 1 => error" do expect{ evaluate(literal(MAX_INTEGER) << literal(1)) }.to raise_error(/resulted in a value outside of Puppet Integer max range/) end it "((MAX+1)*2) << 1 => error" do expect{ evaluate(literal((MAX_INTEGER+1)*2) >> literal(1)) }.to raise_error(/resulted in a value outside of Puppet Integer max range/) end it "MIN - 1 => error" do expect{ evaluate(literal(MIN_INTEGER) - literal(1)) }.to raise_error(/resulted in a value outside of Puppet Integer min range/) end it "does not error on the border values" do expect(evaluate(literal(MAX_INTEGER) + literal(MIN_INTEGER))).to eq(MAX_INTEGER+MIN_INTEGER) end end context "on Floats" do it "2.2 + 2.2 == 4.4" do; expect(evaluate(literal(2.2) + literal(2.2))).to eq(4.4) ; end it "7.7 - 3.3 == 4.4" do; expect(evaluate(literal(7.7) - literal(3.3))).to eq(4.4) ; end it "6.1 * 3.1 == 18.91" do; expect(evaluate(literal(6.1) * literal(3.1))).to eq(18.91); end it "6.6 / 3.3 == 2.0" do; expect(evaluate(literal(6.6) / literal(3.3))).to eq(2.0) ; end it "-(6.0/3.0) == -2.0" do; expect(evaluate(minus(literal(6.0) / literal(3.0)))).to eq(-2.0); end it "-6.0/3.0 == -2.0" do; expect(evaluate(minus(literal(6.0)) / literal(3.0))).to eq(-2.0); end it "6.6 % 3.3 == 0.0" do; expect { evaluate(literal(6.6) % literal(3.3))}.to raise_error(Puppet::ParseError); end it "10.0 % 3.0 == 1.0" do; expect { evaluate(literal(10.0) % literal(3.0))}.to raise_error(Puppet::ParseError); end it "3.14 << 2 == error" do; expect { evaluate(literal(3.14) << literal(2))}.to raise_error(Puppet::ParseError); end it "3.14 >> 2 == error" do; expect { evaluate(literal(3.14) >> literal(2))}.to raise_error(Puppet::ParseError); end end context "on strings requiring boxing to Numeric" do before :each do Puppet[:strict] = :off end it "'2' + '2' == 4" do expect(evaluate(literal('2') + literal('2'))).to eq(4) end it "'2.2' + '2.2' == 4.4" do expect(evaluate(literal('2.2') + literal('2.2'))).to eq(4.4) end it "'0xF7' + '0x8' == 0xFF" do expect(evaluate(literal('0xF7') + literal('0x8'))).to eq(0xFF) end it "'0367' + '010' == 0xFF" do expect(evaluate(literal('0367') + literal('010'))).to eq(0xFF) end it "'0888' + '010' == error" do expect { evaluate(literal('0888') + literal('010'))}.to raise_error(Puppet::ParseError) end it "'0xWTF' + '010' == error" do expect { evaluate(literal('0xWTF') + literal('010'))}.to raise_error(Puppet::ParseError) end it "'0x12.3' + '010' == error" do expect { evaluate(literal('0x12.3') + literal('010'))}.to raise_error(Puppet::ParseError) end it "'012.3' + '010' == 20.3 (not error, floats can start with 0)" do expect(evaluate(literal('012.3') + literal('010'))).to eq(20.3) end it "raises an error when coercing string to numerical by default" do Puppet[:strict] = :error expect { evaluate(literal('2') + literal('2')) }.to raise_error(/Evaluation Error: The string '2' was automatically coerced to the numerical value 2/) end end context 'on binary values' do include PuppetSpec::Compiler require 'base64' encoded = Base64.encode64('Hello world').chomp it 'Binary + Binary' do code = 'notice(assert_type(Binary, Binary([72,101,108,108,111,32]) + Binary([119,111,114,108,100])))' expect(eval_and_collect_notices(code)).to eql([encoded]) end end context 'on timespans' do include PuppetSpec::Compiler it 'Timespan + Timespan = Timespan' do code = 'notice(assert_type(Timespan, Timespan({days => 3}) + Timespan({hours => 12})))' expect(eval_and_collect_notices(code)).to eql(['3-12:00:00.0']) end it 'Timespan - Timespan = Timespan' do code = 'notice(assert_type(Timespan, Timespan({days => 3}) - Timespan({hours => 12})))' expect(eval_and_collect_notices(code)).to eql(['2-12:00:00.0']) end it 'Timespan + -Timespan = Timespan' do code = 'notice(assert_type(Timespan, Timespan({days => 3}) + -Timespan({hours => 12})))' expect(eval_and_collect_notices(code)).to eql(['2-12:00:00.0']) end it 'Timespan - -Timespan = Timespan' do code = 'notice(assert_type(Timespan, Timespan({days => 3}) - -Timespan({hours => 12})))' expect(eval_and_collect_notices(code)).to eql(['3-12:00:00.0']) end it 'Timespan / Timespan = Float' do code = "notice(assert_type(Float, Timespan({days => 3}) / Timespan('0-12:00:00')))" expect(eval_and_collect_notices(code)).to eql(['6.0']) end it 'Timespan * Timespan is an error' do code = 'notice(Timespan({days => 3}) * Timespan({hours => 12}))' expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be multiplied by a Timespan/) end it 'Timespan + Numeric = Timespan (numeric treated as seconds)' do code = 'notice(assert_type(Timespan, Timespan({days => 3}) + 7300.0))' expect(eval_and_collect_notices(code)).to eql(['3-02:01:40.0']) end it 'Timespan - Numeric = Timespan (numeric treated as seconds)' do code = "notice(assert_type(Timespan, Timespan({days => 3}) - 7300.123))" expect(eval_and_collect_notices(code)).to eql(['2-21:58:19.877']) end it 'Timespan * Numeric = Timespan (numeric treated as seconds)' do code = "notice(strftime(assert_type(Timespan, Timespan({days => 3}) * 2), '%D'))" expect(eval_and_collect_notices(code)).to eql(['6']) end it 'Numeric + Timespan = Timespan (numeric treated as seconds)' do code = 'notice(assert_type(Timespan, 7300.0 + Timespan({days => 3})))' expect(eval_and_collect_notices(code)).to eql(['3-02:01:40.0']) end it 'Numeric - Timespan = Timespan (numeric treated as seconds)' do code = "notice(strftime(assert_type(Timespan, 300000 - Timespan({days => 3})), '%H:%M'))" expect(eval_and_collect_notices(code)).to eql(['11:20']) end it 'Numeric * Timespan = Timespan (numeric treated as seconds)' do code = "notice(strftime(assert_type(Timespan, 2 * Timespan({days => 3})), '%D'))" expect(eval_and_collect_notices(code)).to eql(['6']) end it 'Timespan + Timestamp = Timestamp' do code = "notice(assert_type(Timestamp, Timespan({days => 3}) + Timestamp('2016-08-27T16:44:49.999 UTC')))" expect(eval_and_collect_notices(code)).to eql(['2016-08-30T16:44:49.999000000 UTC']) end it 'Timespan - Timestamp is an error' do code = 'notice(Timespan({days => 3}) - Timestamp())' expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be subtracted from a Timespan/) end it 'Timespan * Timestamp is an error' do code = 'notice(Timespan({days => 3}) * Timestamp())' expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be multiplied by a Timestamp/) end it 'Timespan / Timestamp is an error' do code = 'notice(Timespan({days => 3}) / Timestamp())' expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timespan cannot be divided by a Timestamp/) end end context 'on timestamps' do include PuppetSpec::Compiler it 'Timestamp + Timestamp is an error' do code = 'notice(Timestamp() + Timestamp())' expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be added to a Timestamp/) end it 'Timestamp + Timespan = Timestamp' do code = "notice(assert_type(Timestamp, Timestamp('2016-10-10') + Timespan('0-12:00:00')))" expect(eval_and_collect_notices(code)).to eql(['2016-10-10T12:00:00.000000000 UTC']) end it 'Timestamp + Numeric = Timestamp' do code = "notice(assert_type(Timestamp, Timestamp('2016-10-10T12:00:00.000') + 3600.123))" expect(eval_and_collect_notices(code)).to eql(['2016-10-10T13:00:00.123000000 UTC']) end it 'Numeric + Timestamp = Timestamp' do code = "notice(assert_type(Timestamp, 3600.123 + Timestamp('2016-10-10T12:00:00.000')))" expect(eval_and_collect_notices(code)).to eql(['2016-10-10T13:00:00.123000000 UTC']) end it 'Timestamp - Timestamp = Timespan' do code = "notice(assert_type(Timespan, Timestamp('2016-10-10') - Timestamp('2015-10-10')))" expect(eval_and_collect_notices(code)).to eql(['366-00:00:00.0']) end it 'Timestamp - Timespan = Timestamp' do code = "notice(assert_type(Timestamp, Timestamp('2016-10-10') - Timespan('0-12:00:00')))" expect(eval_and_collect_notices(code)).to eql(['2016-10-09T12:00:00.000000000 UTC']) end it 'Timestamp - Numeric = Timestamp' do code = "notice(assert_type(Timestamp, Timestamp('2016-10-10') - 3600.123))" expect(eval_and_collect_notices(code)).to eql(['2016-10-09T22:59:59.877000000 UTC']) end it 'Numeric - Timestamp = Timestamp' do code = "notice(assert_type(Timestamp, 123 - Timestamp('2016-10-10')))" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '-' is not applicable.*when right side is a Timestamp/) end it 'Timestamp / Timestamp is an error' do code = "notice(Timestamp('2016-10-10') / Timestamp())" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable to a Timestamp/) end it 'Timestamp / Timespan is an error' do code = "notice(Timestamp('2016-10-10') / Timespan('0-12:00:00'))" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable to a Timestamp/) end it 'Timestamp / Numeric is an error' do code = "notice(Timestamp('2016-10-10') / 3600.123)" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable to a Timestamp/) end it 'Numeric / Timestamp is an error' do code = "notice(3600.123 / Timestamp('2016-10-10'))" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable.*when right side is a Timestamp/) end it 'Timestamp * Timestamp is an error' do code = "notice(Timestamp('2016-10-10') * Timestamp())" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable to a Timestamp/) end it 'Timestamp * Timespan is an error' do code = "notice(Timestamp('2016-10-10') * Timespan('0-12:00:00'))" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable to a Timestamp/) end it 'Timestamp * Numeric is an error' do code = "notice(Timestamp('2016-10-10') * 3600.123)" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable to a Timestamp/) end it 'Numeric * Timestamp is an error' do code = "notice(3600.123 * Timestamp('2016-10-10'))" expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable.*when right side is a Timestamp/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/evaluator/comparison_ops_spec.rb
spec/unit/pops/evaluator/comparison_ops_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do include EvaluatorRspecHelper context "When the evaluator performs comparisons" do context "of string values" do it "'a' == 'a' == true" do; expect(evaluate(literal('a').eq(literal('a')))).to eq(true) ; end it "'a' == 'b' == false" do; expect(evaluate(literal('a').eq(literal('b')))).to eq(false) ; end it "'a' != 'a' == false" do; expect(evaluate(literal('a').ne(literal('a')))).to eq(false) ; end it "'a' != 'b' == true" do; expect(evaluate(literal('a').ne(literal('b')))).to eq(true) ; end it "'a' < 'b' == true" do; expect(evaluate(literal('a') < literal('b'))).to eq(true) ; end it "'a' < 'a' == false" do; expect(evaluate(literal('a') < literal('a'))).to eq(false) ; end it "'b' < 'a' == false" do; expect(evaluate(literal('b') < literal('a'))).to eq(false) ; end it "'a' <= 'b' == true" do; expect(evaluate(literal('a') <= literal('b'))).to eq(true) ; end it "'a' <= 'a' == true" do; expect(evaluate(literal('a') <= literal('a'))).to eq(true) ; end it "'b' <= 'a' == false" do; expect(evaluate(literal('b') <= literal('a'))).to eq(false) ; end it "'a' > 'b' == false" do; expect(evaluate(literal('a') > literal('b'))).to eq(false) ; end it "'a' > 'a' == false" do; expect(evaluate(literal('a') > literal('a'))).to eq(false) ; end it "'b' > 'a' == true" do; expect(evaluate(literal('b') > literal('a'))).to eq(true) ; end it "'a' >= 'b' == false" do; expect(evaluate(literal('a') >= literal('b'))).to eq(false) ; end it "'a' >= 'a' == true" do; expect(evaluate(literal('a') >= literal('a'))).to eq(true) ; end it "'b' >= 'a' == true" do; expect(evaluate(literal('b') >= literal('a'))).to eq(true) ; end context "with mixed case" do it "'a' == 'A' == true" do; expect(evaluate(literal('a').eq(literal('A')))).to eq(true) ; end it "'a' != 'A' == false" do; expect(evaluate(literal('a').ne(literal('A')))).to eq(false) ; end it "'a' > 'A' == false" do; expect(evaluate(literal('a') > literal('A'))).to eq(false) ; end it "'a' >= 'A' == true" do; expect(evaluate(literal('a') >= literal('A'))).to eq(true) ; end it "'A' < 'a' == false" do; expect(evaluate(literal('A') < literal('a'))).to eq(false) ; end it "'A' <= 'a' == true" do; expect(evaluate(literal('A') <= literal('a'))).to eq(true) ; end end end context "of integer values" do it "1 == 1 == true" do; expect(evaluate(literal(1).eq(literal(1)))).to eq(true) ; end it "1 == 2 == false" do; expect(evaluate(literal(1).eq(literal(2)))).to eq(false) ; end it "1 != 1 == false" do; expect(evaluate(literal(1).ne(literal(1)))).to eq(false) ; end it "1 != 2 == true" do; expect(evaluate(literal(1).ne(literal(2)))).to eq(true) ; end it "1 < 2 == true" do; expect(evaluate(literal(1) < literal(2))).to eq(true) ; end it "1 < 1 == false" do; expect(evaluate(literal(1) < literal(1))).to eq(false) ; end it "2 < 1 == false" do; expect(evaluate(literal(2) < literal(1))).to eq(false) ; end it "1 <= 2 == true" do; expect(evaluate(literal(1) <= literal(2))).to eq(true) ; end it "1 <= 1 == true" do; expect(evaluate(literal(1) <= literal(1))).to eq(true) ; end it "2 <= 1 == false" do; expect(evaluate(literal(2) <= literal(1))).to eq(false) ; end it "1 > 2 == false" do; expect(evaluate(literal(1) > literal(2))).to eq(false) ; end it "1 > 1 == false" do; expect(evaluate(literal(1) > literal(1))).to eq(false) ; end it "2 > 1 == true" do; expect(evaluate(literal(2) > literal(1))).to eq(true) ; end it "1 >= 2 == false" do; expect(evaluate(literal(1) >= literal(2))).to eq(false) ; end it "1 >= 1 == true" do; expect(evaluate(literal(1) >= literal(1))).to eq(true) ; end it "2 >= 1 == true" do; expect(evaluate(literal(2) >= literal(1))).to eq(true) ; end end context "of mixed value types" do it "1 == 1.0 == true" do; expect(evaluate(literal(1).eq( literal(1.0)))).to eq(true) ; end it "1 < 1.1 == true" do; expect(evaluate(literal(1) < literal(1.1))).to eq(true) ; end it "1.0 == 1 == true" do; expect(evaluate(literal(1.0).eq( literal(1)))).to eq(true) ; end it "1.0 < 2 == true" do; expect(evaluate(literal(1.0) < literal(2))).to eq(true) ; end it "'1.0' < 'a' == true" do; expect(evaluate(literal('1.0') < literal('a'))).to eq(true) ; end it "'1.0' < '' == true" do; expect(evaluate(literal('1.0') < literal(''))).to eq(false) ; end it "'1.0' < ' ' == true" do; expect(evaluate(literal('1.0') < literal(' '))).to eq(false) ; end it "'a' > '1.0' == true" do; expect(evaluate(literal('a') > literal('1.0'))).to eq(true) ; end end context "of unsupported mixed value types" do it "'1' < 1.1 == true" do expect{ evaluate(literal('1') < literal(1.1))}.to raise_error(/String < Float/) end it "'1.0' < 1.1 == true" do expect{evaluate(literal('1.0') < literal(1.1))}.to raise_error(/String < Float/) end it "undef < 1.1 == true" do expect{evaluate(literal(nil) < literal(1.1))}.to raise_error(/Undef Value < Float/) end end context "of regular expressions" do it "/.*/ == /.*/ == true" do; expect(evaluate(literal(/.*/).eq(literal(/.*/)))).to eq(true) ; end it "/.*/ != /a.*/ == true" do; expect(evaluate(literal(/.*/).ne(literal(/a.*/)))).to eq(true) ; end end context "of booleans" do it "true == true == true" do; expect(evaluate(literal(true).eq(literal(true)))).to eq(true) ; end; it "false == false == true" do; expect(evaluate(literal(false).eq(literal(false)))).to eq(true) ; end; it "true == false != true" do; expect(evaluate(literal(true).eq(literal(false)))).to eq(false) ; end; it "false == '' == false" do; expect(evaluate(literal(false).eq(literal('')))).to eq(false) ; end; it "undef == '' == false" do; expect(evaluate(literal(:undef).eq(literal('')))).to eq(false) ; end; it "undef == undef == true" do; expect(evaluate(literal(:undef).eq(literal(:undef)))).to eq(true) ; end; it "nil == undef == true" do; expect(evaluate(literal(nil).eq(literal(:undef)))).to eq(true) ; end; end context "of collections" do it "[1,2,3] == [1,2,3] == true" do expect(evaluate(literal([1,2,3]).eq(literal([1,2,3])))).to eq(true) expect(evaluate(literal([1,2,3]).ne(literal([1,2,3])))).to eq(false) expect(evaluate(literal([1,2,4]).eq(literal([1,2,3])))).to eq(false) expect(evaluate(literal([1,2,4]).ne(literal([1,2,3])))).to eq(true) end it "{'a'=>1, 'b'=>2} == {'a'=>1, 'b'=>2} == true" do expect(evaluate(literal({'a'=>1, 'b'=>2}).eq(literal({'a'=>1, 'b'=>2})))).to eq(true) expect(evaluate(literal({'a'=>1, 'b'=>2}).ne(literal({'a'=>1, 'b'=>2})))).to eq(false) expect(evaluate(literal({'a'=>1, 'b'=>2}).eq(literal({'x'=>1, 'b'=>2})))).to eq(false) expect(evaluate(literal({'a'=>1, 'b'=>2}).ne(literal({'x'=>1, 'b'=>2})))).to eq(true) end end context "of non comparable types" do # TODO: Change the exception type it "false < true == error" do; expect { evaluate(literal(true) < literal(false))}.to raise_error(Puppet::ParseError); end it "false <= true == error" do; expect { evaluate(literal(true) <= literal(false))}.to raise_error(Puppet::ParseError); end it "false > true == error" do; expect { evaluate(literal(true) > literal(false))}.to raise_error(Puppet::ParseError); end it "false >= true == error" do; expect { evaluate(literal(true) >= literal(false))}.to raise_error(Puppet::ParseError); end it "/a/ < /b/ == error" do; expect { evaluate(literal(/a/) < literal(/b/))}.to raise_error(Puppet::ParseError); end it "/a/ <= /b/ == error" do; expect { evaluate(literal(/a/) <= literal(/b/))}.to raise_error(Puppet::ParseError); end it "/a/ > /b/ == error" do; expect { evaluate(literal(/a/) > literal(/b/))}.to raise_error(Puppet::ParseError); end it "/a/ >= /b/ == error" do; expect { evaluate(literal(/a/) >= literal(/b/))}.to raise_error(Puppet::ParseError); end it "[1,2,3] < [1,2,3] == error" do expect{ evaluate(literal([1,2,3]) < literal([1,2,3]))}.to raise_error(Puppet::ParseError) end it "[1,2,3] > [1,2,3] == error" do expect{ evaluate(literal([1,2,3]) > literal([1,2,3]))}.to raise_error(Puppet::ParseError) end it "[1,2,3] >= [1,2,3] == error" do expect{ evaluate(literal([1,2,3]) >= literal([1,2,3]))}.to raise_error(Puppet::ParseError) end it "[1,2,3] <= [1,2,3] == error" do expect{ evaluate(literal([1,2,3]) <= literal([1,2,3]))}.to raise_error(Puppet::ParseError) end it "{'a'=>1, 'b'=>2} < {'a'=>1, 'b'=>2} == error" do expect{ evaluate(literal({'a'=>1, 'b'=>2}) < literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError) end it "{'a'=>1, 'b'=>2} > {'a'=>1, 'b'=>2} == error" do expect{ evaluate(literal({'a'=>1, 'b'=>2}) > literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError) end it "{'a'=>1, 'b'=>2} <= {'a'=>1, 'b'=>2} == error" do expect{ evaluate(literal({'a'=>1, 'b'=>2}) <= literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError) end it "{'a'=>1, 'b'=>2} >= {'a'=>1, 'b'=>2} == error" do expect{ evaluate(literal({'a'=>1, 'b'=>2}) >= literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError) end end end context "When the evaluator performs Regular Expression matching" do it "'a' =~ /.*/ == true" do; expect(evaluate(literal('a') =~ literal(/.*/))).to eq(true) ; end it "'a' =~ '.*' == true" do; expect(evaluate(literal('a') =~ literal(".*"))).to eq(true) ; end it "'a' !~ /b.*/ == true" do; expect(evaluate(literal('a').mne(literal(/b.*/)))).to eq(true) ; end it "'a' !~ 'b.*' == true" do; expect(evaluate(literal('a').mne(literal("b.*")))).to eq(true) ; end it "'a' =~ Pattern['.*'] == true" do expect(evaluate(literal('a') =~ fqr('Pattern').access_at(literal(".*")))).to eq(true) end it "$a = Pattern['.*']; 'a' =~ $a == true" do expr = block(var('a').set(fqr('Pattern').access_at('.*')), literal('foo') =~ var('a')) expect(evaluate(expr)).to eq(true) end it 'should fail if LHS is not a string' do expect { evaluate(literal(666) =~ literal(/6/))}.to raise_error(Puppet::ParseError) end end context "When evaluator evaluates the 'in' operator" do it "should find elements in an array" do expect(evaluate(literal(1).in(literal([1,2,3])))).to eq(true) expect(evaluate(literal(4).in(literal([1,2,3])))).to eq(false) end it "should find keys in a hash" do expect(evaluate(literal('a').in(literal({'x'=>1, 'a'=>2, 'y'=> 3})))).to eq(true) expect(evaluate(literal('z').in(literal({'x'=>1, 'a'=>2, 'y'=> 3})))).to eq(false) end it "should find substrings in a string" do expect(evaluate(literal('ana').in(literal('bananas')))).to eq(true) expect(evaluate(literal('xxx').in(literal('bananas')))).to eq(false) end it "should find substrings in a string (regexp)" do expect(evaluate(literal(/ana/).in(literal('bananas')))).to eq(true) expect(evaluate(literal(/xxx/).in(literal('bananas')))).to eq(false) end it "should find substrings in a string (ignoring case)" do expect(evaluate(literal('ANA').in(literal('bananas')))).to eq(true) expect(evaluate(literal('ana').in(literal('BANANAS')))).to eq(true) expect(evaluate(literal('xxx').in(literal('BANANAS')))).to eq(false) end it "should find sublists in a list" do expect(evaluate(literal([2,3]).in(literal([1,[2,3],4])))).to eq(true) expect(evaluate(literal([2,4]).in(literal([1,[2,3],4])))).to eq(false) end it "should find sublists in a list (case insensitive)" do expect(evaluate(literal(['a','b']).in(literal(['A',['A','B'],'C'])))).to eq(true) expect(evaluate(literal(['x','y']).in(literal(['A',['A','B'],'C'])))).to eq(false) end it "should find keys in a hash" do expect(evaluate(literal('a').in(literal({'a' => 10, 'b' => 20})))).to eq(true) expect(evaluate(literal('x').in(literal({'a' => 10, 'b' => 20})))).to eq(false) end it "should find keys in a hash (case insensitive)" do expect(evaluate(literal('A').in(literal({'a' => 10, 'b' => 20})))).to eq(true) expect(evaluate(literal('X').in(literal({'a' => 10, 'b' => 20})))).to eq(false) end it "should find keys in a hash (regexp)" do expect(evaluate(literal(/xxx/).in(literal({'abcxxxabc' => 10, 'xyz' => 20})))).to eq(true) expect(evaluate(literal(/yyy/).in(literal({'abcxxxabc' => 10, 'xyz' => 20})))).to eq(false) end it "should find numbers as numbers" do expect(evaluate(literal(15).in(literal([1,0xf,2])))).to eq(true) end it "should not find numbers as strings" do expect(evaluate(literal(15).in(literal([1, '0xf',2])))).to eq(false) expect(evaluate(literal('15').in(literal([1, 0xf,2])))).to eq(false) end it "should not find numbers embedded in strings, nor digits in numbers" do expect(evaluate(literal(15).in(literal([1, '115', 2])))).to eq(false) expect(evaluate(literal(1).in(literal([11, 111, 2])))).to eq(false) expect(evaluate(literal('1').in(literal([11, 111, 2])))).to eq(false) end it 'should find an entry with compatible type in an Array' do expect(evaluate(fqr('Array').access_at(fqr('Integer')).in(literal(['a', [1,2,3], 'b'])))).to eq(true) expect(evaluate(fqr('Array').access_at(fqr('Integer')).in(literal(['a', [1,2,'not integer'], 'b'])))).to eq(false) end it 'should find an entry with compatible type in a Hash' do expect(evaluate(fqr('Integer').in(literal({1 => 'a', 'a' => 'b'})))).to eq(true) expect(evaluate(fqr('Integer').in(literal({'a' => 'a', 'b' => 'b'})))).to eq(false) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/time/timespan_spec.rb
spec/unit/pops/time/timespan_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Time describe 'Timespan' do include PuppetSpec::Compiler let! (:simple) { Timespan.from_fields(false, 1, 3, 10, 11) } let! (:all_fields_hash) { {'days' => 1, 'hours' => 7, 'minutes' => 10, 'seconds' => 11, 'milliseconds' => 123, 'microseconds' => 456, 'nanoseconds' => 789} } let! (:complex) { Timespan.from_fields_hash(all_fields_hash) } context 'can be created from a String' do it 'using default format' do expect(Timespan.parse('1-03:10:11')).to eql(simple) end it 'using explicit format' do expect(Timespan.parse('1-7:10:11.123456789', '%D-%H:%M:%S.%N')).to eql(complex) end it 'using leading minus and explicit format' do expect(Timespan.parse('-1-7:10:11.123456789', '%D-%H:%M:%S.%N')).to eql(-complex) end it 'using %H as the biggest quantity' do expect(Timespan.parse('27:10:11', '%H:%M:%S')).to eql(simple) end it 'using %M as the biggest quantity' do expect(Timespan.parse('1630:11', '%M:%S')).to eql(simple) end it 'using %S as the biggest quantity' do expect(Timespan.parse('97811', '%S')).to eql(simple) end it 'where biggest quantity is not frist' do expect(Timespan.parse('11:1630', '%S:%M')).to eql(simple) end it 'raises an error when using %L as the biggest quantity' do expect { Timespan.parse('123', '%L') }.to raise_error(ArgumentError, /denotes fractions and must be used together with a specifier of higher magnitude/) end it 'raises an error when using %N as the biggest quantity' do expect { Timespan.parse('123', '%N') }.to raise_error(ArgumentError, /denotes fractions and must be used together with a specifier of higher magnitude/) end it 'where %L is treated as fractions of a second' do expect(Timespan.parse('0.4', '%S.%L')).to eql(Timespan.from_fields(false, 0, 0, 0, 0, 400)) end it 'where %N is treated as fractions of a second' do expect(Timespan.parse('0.4', '%S.%N')).to eql(Timespan.from_fields(false, 0, 0, 0, 0, 400)) end end context 'when presented as a String' do it 'uses default format for #to_s' do expect(simple.to_s).to eql('1-03:10:11.0') end context 'using a format' do it 'produces a string containing all components' do expect(complex.format('%D-%H:%M:%S.%N')).to eql('1-07:10:11.123456789') end it 'produces a literal % for %%' do expect(complex.format('%D%%%H:%M:%S')).to eql('1%07:10:11') end it 'produces a leading dash for negative instance' do expect((-complex).format('%D-%H:%M:%S')).to eql('-1-07:10:11') end it 'produces a string without trailing zeros for %-N' do expect(Timespan.parse('2.345', '%S.%N').format('%-S.%-N')).to eql('2.345') end it 'produces a string with trailing zeros for %N' do expect(Timespan.parse('2.345', '%S.%N').format('%-S.%N')).to eql('2.345000000') end it 'produces a string with trailing zeros for %0N' do expect(Timespan.parse('2.345', '%S.%N').format('%-S.%0N')).to eql('2.345000000') end it 'produces a string with trailing spaces for %_N' do expect(Timespan.parse('2.345', '%S.%N').format('%-S.%_N')).to eql('2.345 ') end end end context 'when converted to a hash' do it 'produces a hash with all numeric keys' do hash = complex.to_hash expect(hash).to eql(all_fields_hash) end it 'produces a compact hash with seconds and nanoseconds for #to_hash(true)' do hash = complex.to_hash(true) expect(hash).to eql({'seconds' => 112211, 'nanoseconds' => 123456789}) end context 'from a negative value' do it 'produces a hash with all numeric keys and negative = true' do hash = (-complex).to_hash expect(hash).to eql(all_fields_hash.merge('negative' => true)) end it 'produces a compact hash with negative seconds and negative nanoseconds for #to_hash(true)' do hash = (-complex).to_hash(true) expect(hash).to eql({'seconds' => -112211, 'nanoseconds' => -123456789}) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/time/timestamp_spec.rb
spec/unit/pops/time/timestamp_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops module Time describe 'Timestamp' do it 'Does not loose microsecond precision when converted to/from String' do ts = Timestamp.new(1495789430910161286) expect(Timestamp.parse(ts.to_s)).to eql(ts) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_timespan_type_spec.rb
spec/unit/pops/types/p_timespan_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Timespan type' do it 'is normalized in a Variant' do t = TypeFactory.variant(TypeFactory.timespan('10:00:00', '15:00:00'), TypeFactory.timespan('14:00:00', '17:00:00')).normalize expect(t).to be_a(PTimespanType) expect(t).to eql(TypeFactory.timespan('10:00:00', '17:00:00')) end context 'when used in Puppet expressions' do include PuppetSpec::Compiler it 'is equal to itself only' do code = <<-CODE $t = Timespan notice(Timespan =~ Type[Timespan]) notice(Timespan == Timespan) notice(Timespan < Timespan) notice(Timespan > Timespan) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true false false)) end it 'does not consider an Integer to be an instance' do code = <<-CODE notice(assert_type(Timespan, 1234)) CODE expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timespan value, got Integer/) end it 'does not consider a Float to be an instance' do code = <<-CODE notice(assert_type(Timespan, 1.234)) CODE expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timespan value, got Float/) end context "when parameterized" do it 'is equal other types with the same parameterization' do code = <<-CODE notice(Timespan['01:00:00', '13:00:00'] == Timespan['01:00:00', '13:00:00']) notice(Timespan['01:00:00', '13:00:00'] != Timespan['01:12:20', '13:00:00']) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true)) end it 'using just one parameter is the same as using default for the second parameter' do code = <<-CODE notice(Timespan['01:00:00'] == Timespan['01:00:00', default]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true)) end it 'if the second parameter is default, it is unlimited' do code = <<-CODE notice(Timespan('12345-23:59:59') =~ Timespan['01:00:00', default]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true)) end it 'orders parameterized types based on range inclusion' do code = <<-CODE notice(Timespan['01:00:00', '13:00:00'] < Timespan['00:00:00', '14:00:00']) notice(Timespan['01:00:00', '13:00:00'] > Timespan['00:00:00', '14:00:00']) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false)) end it 'accepts integer values when specifying the range' do code = <<-CODE notice(Timespan(1) =~ Timespan[1, 2]) notice(Timespan(3) =~ Timespan[1]) notice(Timespan(0) =~ Timespan[default, 2]) notice(Timespan(0) =~ Timespan[1, 2]) notice(Timespan(3) =~ Timespan[1, 2]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true true false false)) end it 'accepts float values when specifying the range' do code = <<-CODE notice(Timespan(1.0) =~ Timespan[1.0, 2.0]) notice(Timespan(3.0) =~ Timespan[1.0]) notice(Timespan(0.0) =~ Timespan[default, 2.0]) notice(Timespan(0.0) =~ Timespan[1.0, 2.0]) notice(Timespan(3.0) =~ Timespan[1.0, 2.0]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true true false false)) end end context 'a Timespan instance' do it 'can be created from a string' do code = <<-CODE $o = Timespan('3-11:00') notice($o) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq(%w(3-11:00:00.0 Timespan['3-11:00:00.0'])) end it 'can be created from a string and format' do code = <<-CODE $o = Timespan('1d11h23m', '%Dd%Hh%Mm') notice($o) CODE expect(eval_and_collect_notices(code)).to eq(%w(1-11:23:00.0)) end it 'can be created from a hash with string and format' do code = <<-CODE $o = Timespan({string => '1d11h23m', format => '%Dd%Hh%Mm'}) notice($o) CODE expect(eval_and_collect_notices(code)).to eq(%w(1-11:23:00.0)) end it 'can be created from a string and array of formats' do code = <<-CODE $fmts = ['%Dd%Hh%Mm%Ss', '%Hh%Mm%Ss', '%Dd%Hh%Mm', '%Dd%Hh', '%Hh%Mm', '%Mm%Ss', '%Dd', '%Hh', '%Mm', '%Ss' ] notice(Timespan('1d11h23m13s', $fmts)) notice(Timespan('11h23m13s', $fmts)) notice(Timespan('1d11h23m', $fmts)) notice(Timespan('1d11h', $fmts)) notice(Timespan('11h23m', $fmts)) notice(Timespan('23m13s', $fmts)) notice(Timespan('1d', $fmts)) notice(Timespan('11h', $fmts)) notice(Timespan('23m', $fmts)) notice(Timespan('13s', $fmts)) CODE expect(eval_and_collect_notices(code)).to eq( %w(1-11:23:13.0 0-11:23:13.0 1-11:23:00.0 1-11:00:00.0 0-11:23:00.0 0-00:23:13.0 1-00:00:00.0 0-11:00:00.0 0-00:23:00.0 0-00:00:13.0)) end it 'it cannot be created using an empty formats array' do code = <<-CODE notice(Timespan('1d11h23m13s', [])) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /parameter 'format' variant 1 expects size to be at least 1, got 0/) end it 'can be created from a integer that represents seconds' do code = <<-CODE $o = Timespan(6800) notice(Integer($o) == 6800) notice($o == Timespan('01:53:20')) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true)) end it 'can be created from a float that represents seconds with fraction' do code = <<-CODE $o = Timespan(6800.123456789) notice(Float($o) == 6800.123456789) notice($o == Timespan('01:53:20.123456789', '%H:%M:%S.%N')) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true)) end it 'matches the appropriate parameterized type' do code = <<-CODE $o = Timespan('3-11:12:13') notice(assert_type(Timespan['3-00:00:00', '4-00:00:00'], $o)) CODE expect(eval_and_collect_notices(code)).to eq(['3-11:12:13.0']) end it 'does not match an inappropriate parameterized type' do code = <<-CODE $o = Timespan('1-03:04:05') notice(assert_type(Timespan['2-00:00:00', '3-00:00:00'], $o) |$e, $a| { 'nope' }) CODE expect(eval_and_collect_notices(code)).to eq(['nope']) end it 'can be compared to other instances' do code = <<-CODE $o1 = Timespan('00:00:01') $o2 = Timespan('00:00:02') $o3 = Timespan('00:00:02') notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o1 == $o3) notice($o1 != $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) notice($o2 == $o3) notice($o2 != $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false true false false true true true false)) end it 'can be compared to integer that represents seconds' do code = <<-CODE $o1 = Timespan('00:00:01') $o2 = Timespan('00:00:02') $o3 = 2 notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'integer that represents seconds can be compared to it' do code = <<-CODE $o1 = 1 $o2 = 2 $o3 = Timespan('00:00:02') notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'is equal to integer that represents seconds' do code = <<-CODE $o1 = Timespan('02', '%S') $o2 = 2 notice($o1 == $o2) notice($o1 != $o2) notice(Integer($o1) == $o2) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'integer that represents seconds is equal to it' do code = <<-CODE $o1 = 2 $o2 = Timespan('02', '%S') notice($o1 == $o2) notice($o1 != $o2) notice($o1 == Integer($o2)) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'can be compared to float that represents seconds with fraction' do code = <<-CODE $o1 = Timespan('01.123456789', '%S.%N') $o2 = Timespan('02.123456789', '%S.%N') $o3 = 2.123456789 notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'float that represents seconds with fraction can be compared to it' do code = <<-CODE $o1 = 1.123456789 $o2 = 2.123456789 $o3 = Timespan('02.123456789', '%S.%N') notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'is equal to float that represents seconds with fraction' do code = <<-CODE $o1 = Timespan('02.123456789', '%S.%N') $o2 = 2.123456789 notice($o1 == $o2) notice($o1 != $o2) notice(Float($o1) == $o2) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'float that represents seconds with fraction is equal to it' do code = <<-CODE $o1 = 2.123456789 $o2 = Timespan('02.123456789', '%S.%N') notice($o1 == $o2) notice($o1 != $o2) notice($o1 == Float($o2)) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'it cannot be compared to a Timestamp' do code = <<-CODE notice(Timespan(3) < Timestamp()) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Timespans are only comparable to Timespans, Integers, and Floats/) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_init_type_spec.rb
spec/unit/pops/types/p_init_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'The Init Type' do include PuppetSpec::Compiler include_context 'types_setup' context 'when used in Puppet expressions' do it 'an unparameterized type can be used' do code = <<-CODE notice(type(Init)) CODE expect(eval_and_collect_notices(code)).to eql(['Type[Init]']) end it 'a parameterized type can be used' do code = <<-CODE notice(type(Init[Integer])) CODE expect(eval_and_collect_notices(code)).to eql(['Type[Init[Integer]]']) end it 'a parameterized type can have additional arguments' do code = <<-CODE notice(type(Init[Integer, 16])) CODE expect(eval_and_collect_notices(code)).to eql(['Type[Init[Integer, 16]]']) end (all_types - abstract_types - internal_types).map { |tc| tc::DEFAULT.name }.each do |type_name| it "can be created on a #{type_name}" do code = <<-CODE notice(type(Init[#{type_name}])) CODE expect(eval_and_collect_notices(code)).to eql(["Type[Init[#{type_name}]]"]) end end (abstract_types - internal_types).map { |tc| tc::DEFAULT.name }.each do |type_name| it "cannot be created on a #{type_name}" do code = <<-CODE type(Init[#{type_name}]('x')) CODE expect { eval_and_collect_notices(code) }.to raise_error(/Creation of new instance of type '#{type_name}' is not supported/) end end it 'an Init[Integer, 16] can create an instance from a String' do code = <<-CODE notice(Init[Integer, 16]('100')) CODE expect(eval_and_collect_notices(code)).to eql(['256']) end it "an Init[String,'%x'] can create an instance from an Integer" do code = <<-CODE notice(Init[String,'%x'](128)) CODE expect(eval_and_collect_notices(code)).to eql(['80']) end it "an Init[String,23] raises an error because no available dispatcher exists" do code = <<-CODE notice(Init[String,23](128)) CODE expect { eval_and_collect_notices(code) }.to raise_error( /The type 'Init\[String, 23\]' does not represent a valid set of parameters for String\.new\(\)/) end it 'an Init[String] can create an instance from an Integer' do code = <<-CODE notice(Init[String](128)) CODE expect(eval_and_collect_notices(code)).to eql(['128']) end it 'an Init[String] can create an instance from an array with an Integer' do code = <<-CODE notice(Init[String]([128])) CODE expect(eval_and_collect_notices(code)).to eql(['128']) end it 'an Init[String] can create an instance from an array with an Integer and a format' do code = <<-CODE notice(Init[String]([128, '%x'])) CODE expect(eval_and_collect_notices(code)).to eql(['80']) end it 'an Init[String] can create an instance from an array with an array' do code = <<-CODE notice(Init[String]([[128, '%x']])) CODE expect(eval_and_collect_notices(code)).to eql(["[128, '%x']"]) end it 'an Init[Binary] can create an instance from a string' do code = <<-CODE notice(Init[Binary]('b25lIHR3byB0aHJlZQ==')) CODE expect(eval_and_collect_notices(code)).to eql(['b25lIHR3byB0aHJlZQ==']) end it 'an Init[String] can not create an instance from an Integer and a format unless given as an array argument' do code = <<-CODE notice(Init[String](128, '%x')) CODE expect { eval_and_collect_notices(code) }.to raise_error(/'new_Init' expects 1 argument, got 2/) end it 'the array [128] is an instance of Init[String]' do code = <<-CODE notice(assert_type(Init[String], [128])) CODE expect(eval_and_collect_notices(code)).to eql(['[128]']) end it 'the value 128 is an instance of Init[String]' do code = <<-CODE notice(assert_type(Init[String], 128)) CODE expect(eval_and_collect_notices(code)).to eql(['128']) end it "the array [128] is an instance of Init[String]" do code = <<-CODE notice(assert_type(Init[String], [128])) CODE expect(eval_and_collect_notices(code)).to eql(['[128]']) end it "the array [128, '%x'] is an instance of Init[String]" do code = <<-CODE notice(assert_type(Init[String], [128, '%x'])) CODE expect(eval_and_collect_notices(code)).to eql(['[128, %x]']) end it "the array [[128, '%x']] is an instance of Init[String]" do code = <<-CODE notice(assert_type(Init[String], [[128, '%x']])) CODE expect(eval_and_collect_notices(code)).to eql(['[[128, %x]]']) end it 'RichData is assignable to Init' do code = <<-CODE notice(Init > RichData) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'Runtime is not assignable to Init' do code = <<-CODE notice(Init > Runtime['ruby', 'Time']) CODE expect(eval_and_collect_notices(code)).to eql(['false']) end it 'Init is not assignable to RichData' do code = <<-CODE notice(Init < RichData) CODE expect(eval_and_collect_notices(code)).to eql(['false']) end it 'Init[T1] is assignable to Init[T2] when T1 is assignable to T2' do code = <<-CODE notice(Init[Integer] < Init[Numeric]) notice(Init[Tuple[Integer]] < Init[Array[Integer]]) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'true']) end it 'Init[T1] is not assignable to Init[T2] unless T1 is assignable to T2' do code = <<-CODE notice(Init[Integer] > Init[Numeric]) notice(Init[Tuple[Integer]] > Init[Array[Integer]]) CODE expect(eval_and_collect_notices(code)).to eql(['false', 'false']) end it 'T is assignable to Init[T]' do code = <<-CODE notice(Integer < Init[Integer]) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'T1 is assignable to Init[T2] if T2 can be created from instance of T1' do code = <<-CODE notice(Integer < Init[String]) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'a RichData value is an instance of Init' do code = <<-CODE notice( String(assert_type(Init, { 'a' => [ 1, 2, Sensitive(3) ], 2 => Timestamp('2014-12-01T13:15:00') }), { Any => { format => '%s', string_formats => { Any => '%s' }}})) CODE expect(eval_and_collect_notices(code)).to eql(['{a => [1, 2, Sensitive [value redacted]], 2 => 2014-12-01T13:15:00.000000000 UTC}']) end it 'an Init[Sensitive[String]] can create an instance from a String' do code = <<-CODE notice(Init[Sensitive[String]]('256')) CODE expect(eval_and_collect_notices(code)).to eql(['Sensitive [value redacted]']) end it 'an Init[Type] can create an instance from a String' do code = <<-CODE notice(Init[Type]('Integer[2,3]')) CODE expect(eval_and_collect_notices(code)).to eql(['Integer[2, 3]']) end it 'an Init[Type[Numeric]] can not create an unassignable type from a String' do code = <<-CODE notice(Init[Type[Numeric]]('String')) CODE expect { eval_and_collect_notices(code) }.to raise_error( /Converted value from Type\[Numeric\]\.new\(\) has wrong type, expects a Type\[Numeric\] value, got Type\[String\]/) end it 'an Init with a custom object type can create an instance from a Hash' do code = <<-CODE type MyType = Object[{ attributes => { granularity => String, price => String, category => Integer } }] notice(Init[MyType]({ granularity => 'fine', price => '$10', category => 23 })) CODE expect(eval_and_collect_notices(code)).to eql(["MyType({'granularity' => 'fine', 'price' => '$10', 'category' => 23})"]) end it 'an Init with a custom object type and additional parameters can create an instance from a value' do code = <<-CODE type MyType = Object[{ attributes => { granularity => String, price => String, category => Integer } }] notice(Init[MyType,'$5',20]('coarse')) CODE expect(eval_and_collect_notices(code)).to eql(["MyType({'granularity' => 'coarse', 'price' => '$5', 'category' => 20})"]) end it 'an Init with a custom object with one Array parameter, can be created from an Array' do code = <<-CODE type MyType = Object[{ attributes => { array => Array[String] } }] notice(Init[MyType](['a'])) CODE expect(eval_and_collect_notices(code)).to eql(["MyType({'array' => ['a']})"]) end it 'an Init type can be used recursively' do # Even if it doesn't make sense, it should not crash code = <<-CODE type One = Object[{ attributes => { init_one => Variant[Init[One],String] } }] notice(Init[One]('w')) CODE expect(eval_and_collect_notices(code)).to eql(["One({'init_one' => 'w'})"]) end context 'computes if x is an instance such that' do %w(true false True False TRUE FALSE tRuE FaLsE Yes No yes no YES NO YeS nO y n Y N).each do |str| it "string '#{str}' is an instance of Init[Boolean]" do expect(eval_and_collect_notices("notice('#{str}' =~ Init[Boolean])")).to eql(['true']) end end it 'arbitrary string is not an instance of Init[Boolean]' do expect(eval_and_collect_notices("notice('blue' =~ Init[Boolean])")).to eql(['false']) end it 'empty string is not an instance of Init[Boolean]' do expect(eval_and_collect_notices("notice('' =~ Init[Boolean])")).to eql(['false']) end it 'undef string is not an instance of Init[Boolean]' do expect(eval_and_collect_notices("notice(undef =~ Init[Boolean])")).to eql(['false']) end %w(0 1 0634 0x3b -0xba 0b1001 +0b1111 23.14 -2.3 2e-21 1.23e18 -0.23e18).each do |str| it "string '#{str}' is an instance of Init[Numeric]" do expect(eval_and_collect_notices("notice('#{str}' =~ Init[Numeric])")).to eql(['true']) end end it 'non numeric string is not an instance of Init[Numeric]' do expect(eval_and_collect_notices("notice('blue' =~ Init[Numeric])")).to eql(['false']) end it 'empty string is not an instance of Init[Numeric]' do expect(eval_and_collect_notices("notice('' =~ Init[Numeric])")).to eql(['false']) end it 'undef is not an instance of Init[Numeric]' do expect(eval_and_collect_notices("notice(undef =~ Init[Numeric])")).to eql(['false']) end %w(0 1 0634 0x3b -0xba 0b1001 +0b1111 23.14 -2.3 2e-21 1.23e18 -0.23e18).each do |str| it "string '#{str}' is an instance of Init[Float]" do expect(eval_and_collect_notices("notice('#{str}' =~ Init[Float])")).to eql(['true']) end end it 'non numeric string is not an instance of Init[Float]' do expect(eval_and_collect_notices("notice('blue' =~ Init[Float])")).to eql(['false']) end it 'empty string is not an instance of Init[Float]' do expect(eval_and_collect_notices("notice('' =~ Init[Float])")).to eql(['false']) end it 'undef is not an instance of Init[Float]' do expect(eval_and_collect_notices("notice(undef =~ Init[Float])")).to eql(['false']) end %w(0 1 0634 0x3b -0xba 0b1001 0b1111).each do |str| it "string '#{str}' is an instance of Init[Integer]" do expect(eval_and_collect_notices("notice('#{str}' =~ Init[Integer])")).to eql(['true']) end end %w(23.14 -2.3 2e-21 1.23e18 -0.23e18).each do |str| it "valid float string '#{str}' is not an instance of Init[Integer]" do expect(eval_and_collect_notices("notice('#{str}' =~ Init[Integer])")).to eql(['false']) end end it 'non numeric string is not an instance of Init[Integer]' do expect(eval_and_collect_notices("notice('blue' =~ Init[Integer])")).to eql(['false']) end it 'empty string is not an instance of Init[Integer]' do expect(eval_and_collect_notices("notice('' =~ Init[Integer])")).to eql(['false']) end it 'undef is not an instance of Init[Integer]' do expect(eval_and_collect_notices("notice(undef =~ Init[Integer])")).to eql(['false']) end %w(1.2.3 1.1.1-a3 1.2.3+b3 1.2.3-a3+b3).each do |str| it "string '#{str}' is an instance of Init[SemVer]" do expect(eval_and_collect_notices("notice('#{str}' =~ Init[SemVer])")).to eql(['true']) end end it 'non SemVer compliant string is not an instance of Init[SemVer]' do expect(eval_and_collect_notices("notice('blue' =~ Init[SemVer])")).to eql(['false']) end it 'empty string is not an instance of Init[SemVer]' do expect(eval_and_collect_notices("notice('' =~ Init[SemVer])")).to eql(['false']) end it 'undef is not an instance of Init[SemVer]' do expect(eval_and_collect_notices("notice(undef =~ Init[SemVer])")).to eql(['false']) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/string_converter_spec.rb
spec/unit/pops/types/string_converter_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'The string converter' do let(:converter) { Puppet::Pops::Types::StringConverter.singleton } let(:factory) { Puppet::Pops::Types::TypeFactory } let(:format) { Puppet::Pops::Types::StringConverter::Format } let(:binary) { Puppet::Pops::Types::PBinaryType::Binary } describe 'helper Format' do it 'parses a single character like "%d" as a format' do fmt = format.new("%d") expect(fmt.format()).to be(:d) expect(fmt.alt()).to be(false) expect(fmt.left()).to be(false) expect(fmt.width()).to be_nil expect(fmt.prec()).to be_nil expect(fmt.plus()).to eq(:ignore) end it 'alternative form can be given with "%#d"' do fmt = format.new("%#d") expect(fmt.format()).to be(:d) expect(fmt.alt()).to be(true) end it 'left adjust can be given with "%-d"' do fmt = format.new("%-d") expect(fmt.format()).to be(:d) expect(fmt.left()).to be(true) end it 'plus sign can be used to indicate how positive numbers are displayed' do fmt = format.new("%+d") expect(fmt.format()).to be(:d) expect(fmt.plus()).to eq(:plus) end it 'a space can be used to output " " instead of "+" for positive numbers' do fmt = format.new("% d") expect(fmt.format()).to be(:d) expect(fmt.plus()).to eq(:space) end it 'padding with zero can be specified with a "0" flag' do fmt = format.new("%0d") expect(fmt.format()).to be(:d) expect(fmt.zero_pad()).to be(true) end it 'width can be specified as an integer >= 1' do fmt = format.new("%1d") expect(fmt.format()).to be(:d) expect(fmt.width()).to be(1) fmt = format.new("%10d") expect(fmt.width()).to be(10) end it 'precision can be specified as an integer >= 0' do fmt = format.new("%.0d") expect(fmt.format()).to be(:d) expect(fmt.prec()).to be(0) fmt = format.new("%.10d") expect(fmt.prec()).to be(10) end it 'width and precision can both be specified' do fmt = format.new("%2.3d") expect(fmt.format()).to be(:d) expect(fmt.width()).to be(2) expect(fmt.prec()).to be(3) end [ '[', '{', '(', '<', '|', ].each do | delim | it "a container delimiter pair can be set with '#{delim}'" do fmt = format.new("%#{delim}d") expect(fmt.format()).to be(:d) expect(fmt.delimiters()).to eql(delim) end end it "Is an error to specify different delimiters at the same time" do expect do format.new("%[{d") end.to raise_error(/Only one of the delimiters/) end it "Is an error to have trailing characters after the format" do expect do format.new("%dv") end.to raise_error(/The format '%dv' is not a valid format/) end it "Is an error to specify the same flag more than once" do expect do format.new("%[[d") end.to raise_error(/The same flag can only be used once/) end end context 'when converting to string' do { 42 => "42", 3.14 => "3.140000", "hello world" => "hello world", "hello\tworld" => "hello\tworld", }.each do |from, to| it "the string value of #{from} is '#{to}'" do expect(converter.convert(from, :default)).to eq(to) end end it 'float point value decimal digits can be specified' do string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => '%.2f'} expect(converter.convert(3.14, string_formats)).to eq('3.14') end it 'when specifying format for one type, other formats are not affected' do string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => '%.2f'} expect(converter.convert('3.1415', string_formats)).to eq('3.1415') end context 'The %p format for string produces' do let!(:string_formats) { { Puppet::Pops::Types::PStringType::DEFAULT => '%p'} } it 'double quoted result for string that contains control characters' do expect(converter.convert("hello\tworld.\r\nSun is brigth today.", string_formats)).to eq('"hello\\tworld.\\r\\nSun is brigth today."') end it 'single quoted result for string that is plain ascii without \\, $ or control characters' do expect(converter.convert('hello world', string_formats)).to eq("'hello world'") end it 'double quoted result when using %#p if it would otherwise be single quoted' do expect(converter.convert('hello world', '%#p')).to eq('"hello world"') end it 'quoted 5-byte unicode chars' do expect(converter.convert("smile \u{1f603}.", string_formats)).to eq("'smile \u{1F603}.'") end it 'quoted 2-byte unicode chars' do expect(converter.convert("esc \u{1b}.", string_formats)).to eq('"esc \\u{1B}."') end it 'escape for $ in double quoted string' do # Use \n in string to force double quotes expect(converter.convert("escape the $ sign\n", string_formats)).to eq('"escape the \$ sign\n"') end it 'no escape for $ in single quoted string' do expect(converter.convert('don\'t escape the $ sign', string_formats)).to eq("'don\\'t escape the $ sign'") end it 'escape for double quote but not for single quote in double quoted string' do # Use \n in string to force double quotes expect(converter.convert("the ' single and \" double quote\n", string_formats)).to eq('"the \' single and \\" double quote\n"') end it 'escape for single quote but not for double quote in single quoted string' do expect(converter.convert('the \' single and " double quote', string_formats)).to eq("'the \\' single and \" double quote'") end it 'no escape for #' do expect(converter.convert('do not escape #{x}', string_formats)).to eq('\'do not escape #{x}\'') end it 'escape for last \\' do expect(converter.convert('escape the last \\', string_formats)).to eq("'escape the last \\'") end end { '%s' => 'hello::world', '%p' => "'hello::world'", '%c' => 'Hello::world', '%#c' => "'Hello::world'", '%u' => 'HELLO::WORLD', '%#u' => "'HELLO::WORLD'", }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => fmt} expect(converter.convert('hello::world', string_formats)).to eq(result) end end { '%c' => 'Hello::world', '%#c' => "'Hello::world'", '%d' => 'hello::world', '%#d' => "'hello::world'", }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => fmt} expect(converter.convert('HELLO::WORLD', string_formats)).to eq(result) end end { [nil, '%.1p'] => 'u', [nil, '%#.2p'] => '"u', [:default, '%.1p'] => 'd', [true, '%.2s'] => 'tr', [true, '%.2y'] => 'ye', }.each do |args, result | it "the format #{args[1]} produces #{result} for value #{args[0]}" do expect(converter.convert(*args)).to eq(result) end end { ' a b ' => 'a b', 'a b ' => 'a b', ' a b' => 'a b', }.each do |input, result | it "the input #{input} is trimmed to #{result} by using format '%t'" do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%t'} expect(converter.convert(input, string_formats)).to eq(result) end end { ' a b ' => "'a b'", 'a b ' => "'a b'", ' a b' => "'a b'", }.each do |input, result | it "the input #{input} is trimmed to #{result} by using format '%#t'" do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%#t'} expect(converter.convert(input, string_formats)).to eq(result) end end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => "%k"} converter.convert('wat', string_formats) end.to raise_error(/Illegal format 'k' specified for value of String type - expected one of the characters 'cCudspt'/) end it 'Width pads a string left with spaces to given width' do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%6s'} expect(converter.convert("abcd", string_formats)).to eq(' abcd') end it 'Width pads a string right with spaces to given width and - flag' do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%-6s'} expect(converter.convert("abcd", string_formats)).to eq('abcd ') end it 'Precision truncates the string if precision < length' do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%-6.2s'} expect(converter.convert("abcd", string_formats)).to eq('ab ') end { '%4.2s' => ' he', '%4.2p' => " 'h", '%4.2c' => ' He', '%#4.2c' => " 'H", '%4.2u' => ' HE', '%#4.2u' => " 'H", '%4.2d' => ' he', '%#4.2d' => " 'h" }.each do |fmt, result | it "width and precision can be combined with #{fmt}" do string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => fmt} expect(converter.convert('hello::world', string_formats)).to eq(result) end end end context 'when converting integer' do it 'the default string representation is decimal' do expect(converter.convert(42, :default)).to eq('42') end { '%s' => '18', '%4.1s' => ' 1', '%p' => '18', '%4.2p' => ' 18', '%4.1p' => ' 1', '%#s' => '"18"', '%#6.4s' => ' "18"', '%#p' => '18', '%#6.4p' => ' 18', '%d' => '18', '%4.1d' => ' 18', '%4.3d' => ' 018', '%x' => '12', '%4.3x' => ' 012', '%#x' => '0x12', '%#6.4x' => '0x0012', '%X' => '12', '%4.3X' => ' 012', '%#X' => '0X12', '%#6.4X' => '0X0012', '%o' => '22', '%4.2o' => ' 22', '%#o' => '022', '%b' => '10010', '%7.6b' => ' 010010', '%#b' => '0b10010', '%#9.6b' => ' 0b010010', '%#B' => '0B10010', '%#9.6B' => ' 0B010010', # Integer to float then a float format - fully tested for float '%e' => '1.800000e+01', '%E' => '1.800000E+01', '%f' => '18.000000', '%g' => '18', '%a' => '0x1.2p+4', '%A' => '0X1.2P+4', '%.1f' => '18.0', }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => fmt} expect(converter.convert(18, string_formats)).to eq(result) end end it 'the format %#6.4o produces 0022' do string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => '%#6.4o' } result = RUBY_PLATFORM == 'java' ? ' 00022' : ' 0022' expect(converter.convert(18, string_formats)).to eq(result) end it 'produces a unicode char string by using format %c' do string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => '%c'} expect(converter.convert(0x1F603, string_formats)).to eq("\u{1F603}") end it 'produces a quoted unicode char string by using format %#c' do string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => '%#c'} expect(converter.convert(0x1F603, string_formats)).to eq("\"\u{1F603}\"") end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => "%k"} converter.convert(18, string_formats) end.to raise_error(/Illegal format 'k' specified for value of Integer type - expected one of the characters 'dxXobBeEfgGaAspc'/) end end context 'when converting float' do it 'the default string representation is decimal' do expect(converter.convert(42.0, :default)).to eq('42.000000') end { '%s' => '18.0', '%#s' => '"18.0"', '%5s' => ' 18.0', '%#8s' => ' "18.0"', '%05.1s' => ' 1', '%p' => '18.0', '%7.2p' => ' 18', '%e' => '1.800000e+01', '%+e' => '+1.800000e+01', '% e' => ' 1.800000e+01', '%.2e' => '1.80e+01', '%10.2e' => ' 1.80e+01', '%-10.2e' => '1.80e+01 ', '%010.2e' => '001.80e+01', '%E' => '1.800000E+01', '%+E' => '+1.800000E+01', '% E' => ' 1.800000E+01', '%.2E' => '1.80E+01', '%10.2E' => ' 1.80E+01', '%-10.2E' => '1.80E+01 ', '%010.2E' => '001.80E+01', '%f' => '18.000000', '%+f' => '+18.000000', '% f' => ' 18.000000', '%.2f' => '18.00', '%10.2f' => ' 18.00', '%-10.2f' => '18.00 ', '%010.2f' => '0000018.00', '%g' => '18', '%5g' => ' 18', '%05g' => '00018', '%-5g' => '18 ', '%5.4g' => ' 18', # precision has no effect '%a' => '0x1.2p+4', '%.4a' => '0x1.2000p+4', '%10a' => ' 0x1.2p+4', '%010a' => '0x001.2p+4', '%-10a' => '0x1.2p+4 ', '%A' => '0X1.2P+4', '%.4A' => '0X1.2000P+4', '%10A' => ' 0X1.2P+4', '%-10A' => '0X1.2P+4 ', '%010A' => '0X001.2P+4', # integer formats fully tested for integer '%d' => '18', '%x' => '12', '%X' => '12', '%o' => '22', '%b' => '10010', '%#B' => '0B10010', }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => fmt} expect(converter.convert(18.0, string_formats)).to eq(result) end end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => "%k"} converter.convert(18.0, string_formats) end.to raise_error(/Illegal format 'k' specified for value of Float type - expected one of the characters 'dxXobBeEfgGaAsp'/) end end context 'when converting undef' do it 'the default string representation is empty string' do expect(converter.convert(nil, :default)).to eq('') end { "%u" => "undef", "%#u" => "undefined", "%s" => "", "%#s" => '""', "%p" => 'undef', "%#p" => '"undef"', "%n" => 'nil', "%#n" => 'null', "%v" => 'n/a', "%V" => 'N/A', "%d" => 'NaN', "%x" => 'NaN', "%o" => 'NaN', "%b" => 'NaN', "%B" => 'NaN', "%e" => 'NaN', "%E" => 'NaN', "%f" => 'NaN', "%g" => 'NaN', "%G" => 'NaN', "%a" => 'NaN', "%A" => 'NaN', }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PUndefType::DEFAULT => fmt} expect(converter.convert(nil, string_formats)).to eq(result) end end { "%7u" => " undef", "%-7u" => "undef ", "%#10u" => " undefined", "%#-10u" => "undefined ", "%7.2u" => " un", "%4s" => " ", "%#4s" => ' ""', "%7p" => ' undef', "%7.1p" => ' u', "%#8p" => ' "undef"', "%5n" => ' nil', "%.1n" => 'n', "%-5n" => 'nil ', "%#5n" => ' null', "%#-5n" => 'null ', "%5v" => ' n/a', "%5.2v" => ' n/', "%-5v" => 'n/a ', "%5V" => ' N/A', "%5.1V" => ' N', "%-5V" => 'N/A ', "%5d" => ' NaN', "%5.2d" => ' Na', "%-5d" => 'NaN ', "%5x" => ' NaN', "%5.2x" => ' Na', "%-5x" => 'NaN ', "%5o" => ' NaN', "%5.2o" => ' Na', "%-5o" => 'NaN ', "%5b" => ' NaN', "%5.2b" => ' Na', "%-5b" => 'NaN ', "%5B" => ' NaN', "%5.2B" => ' Na', "%-5B" => 'NaN ', "%5e" => ' NaN', "%5.2e" => ' Na', "%-5e" => 'NaN ', "%5E" => ' NaN', "%5.2E" => ' Na', "%-5E" => 'NaN ', "%5f" => ' NaN', "%5.2f" => ' Na', "%-5f" => 'NaN ', "%5g" => ' NaN', "%5.2g" => ' Na', "%-5g" => 'NaN ', "%5G" => ' NaN', "%5.2G" => ' Na', "%-5G" => 'NaN ', "%5a" => ' NaN', "%5.2a" => ' Na', "%-5a" => 'NaN ', "%5A" => ' NaN', "%5.2A" => ' Na', "%-5A" => 'NaN ', }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PUndefType::DEFAULT => fmt} expect(converter.convert(nil, string_formats)).to eq(result) end end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PUndefType::DEFAULT => "%k"} converter.convert(nil, string_formats) end.to raise_error(/Illegal format 'k' specified for value of Undef type - expected one of the characters 'nudxXobBeEfgGaAvVsp'/) end end context 'when converting default' do it 'the default string representation is unquoted "default"' do expect(converter.convert(:default, :default)).to eq('default') end { "%d" => 'default', "%D" => 'Default', "%#d" => '"default"', "%#D" => '"Default"', "%s" => 'default', "%p" => 'default', }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PDefaultType::DEFAULT => fmt} expect(converter.convert(:default, string_formats)).to eq(result) end end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PDefaultType::DEFAULT => "%k"} converter.convert(:default, string_formats) end.to raise_error(/Illegal format 'k' specified for value of Default type - expected one of the characters 'dDsp'/) end end context 'when converting boolean true' do it 'the default string representation is unquoted "true"' do expect(converter.convert(true, :default)).to eq('true') end { "%t" => 'true', "%#t" => 't', "%T" => 'True', "%#T" => 'T', "%s" => 'true', "%p" => 'true', "%d" => '1', "%x" => '1', "%#x" => '0x1', "%o" => '1', "%#o" => '01', "%b" => '1', "%#b" => '0b1', "%#B" => '0B1', "%e" => '1.000000e+00', "%f" => '1.000000', "%g" => '1', "%a" => '0x1p+0', "%A" => '0X1P+0', "%.1f" => '1.0', "%y" => 'yes', "%Y" => 'Yes', "%#y" => 'y', "%#Y" => 'Y', }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => fmt} expect(converter.convert(true, string_formats)).to eq(result) end end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => "%k"} converter.convert(true, string_formats) end.to raise_error(/Illegal format 'k' specified for value of Boolean type - expected one of the characters 'tTyYdxXobBeEfgGaAsp'/) end end context 'when converting boolean false' do it 'the default string representation is unquoted "false"' do expect(converter.convert(false, :default)).to eq('false') end { "%t" => 'false', "%#t" => 'f', "%T" => 'False', "%#T" => 'F', "%s" => 'false', "%p" => 'false', "%d" => '0', "%x" => '0', "%#x" => '0', "%o" => '0', "%#o" => '0', "%b" => '0', "%#b" => '0', "%#B" => '0', "%e" => '0.000000e+00', "%E" => '0.000000E+00', "%f" => '0.000000', "%g" => '0', "%a" => '0x0p+0', "%A" => '0X0P+0', "%.1f" => '0.0', "%y" => 'no', "%Y" => 'No', "%#y" => 'n', "%#Y" => 'N', }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => fmt} expect(converter.convert(false, string_formats)).to eq(result) end end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => "%k"} converter.convert(false, string_formats) end.to raise_error(/Illegal format 'k' specified for value of Boolean type - expected one of the characters 'tTyYdxXobBeEfgGaAsp'/) end end context 'when converting array' do it 'the default string representation is using [] delimiters, joins with ',' and uses %p for values' do expect(converter.convert(["hello", "world"], :default)).to eq("['hello', 'world']") end { "%s" => "[1, 'hello']", "%p" => "[1, 'hello']", "%a" => "[1, 'hello']", "%<a" => "<1, 'hello'>", "%[a" => "[1, 'hello']", "%(a" => "(1, 'hello')", "%{a" => "{1, 'hello'}", "% a" => "1, 'hello'", {'format' => '%(a', 'separator' => ' ' } => "(1 'hello')", {'format' => '%(a', 'separator' => '' } => "(1'hello')", {'format' => '%|a', 'separator' => ' ' } => "|1 'hello'|", {'format' => '%(a', 'separator' => ' ', 'string_formats' => {Puppet::Pops::Types::PIntegerType::DEFAULT => '%#x'} } => "(0x1 'hello')", }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => fmt} expect(converter.convert([1, "hello"], string_formats)).to eq(result) end end it "multiple rules selects most specific" do short_array_t = factory.array_of(factory.integer, factory.range(1,2)) long_array_t = factory.array_of(factory.integer, factory.range(3,100)) string_formats = { short_array_t => "%(a", long_array_t => "%[a", } expect(converter.convert([1, 2], string_formats)).to eq('(1, 2)') unless RUBY_PLATFORM == 'java' # PUP-8615 expect(converter.convert([1, 2, 3], string_formats)).to eq('[1, 2, 3]') end it 'indents elements in alternate mode' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#a', 'separator' =>", " } } # formatting matters here result = [ "[1, 2, 9, 9,", " [3, 4],", " [5,", " [6, 7]],", " 8, 9]" ].join("\n") formatted = converter.convert([1, 2, 9, 9, [3, 4], [5, [6, 7]], 8, 9], string_formats) expect(formatted).to eq(result) end it 'applies a short form format' do result = [ "[1,", " [2, 3],", " 4]" ].join("\n") expect(converter.convert([1, [2,3], 4], '%#a')).to eq(result) end it 'treats hashes as nested arrays wrt indentation' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#a', 'separator' =>", " } } # formatting matters here result = [ "[1, 2, 9, 9,", " {3 => 4, 5 => 6},", " [5,", " [6, 7]],", " 8, 9]" ].join("\n") formatted = converter.convert([1, 2, 9, 9, {3 => 4, 5 => 6}, [5, [6, 7]], 8, 9], string_formats) expect(formatted).to eq(result) end it 'indents and breaks when a sequence > given width, in alternate mode' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#3a', 'separator' =>", " } } # formatting matters here result = [ "[ 1,", " 2,", " 90,", # this sequence has length 4 (1,2,90) which is > 3 " [3, 4],", " [5,", " [6, 7]],", " 8,", " 9]", ].join("\n") formatted = converter.convert([1, 2, 90, [3, 4], [5, [6, 7]], 8, 9], string_formats) expect(formatted).to eq(result) end it 'indents and breaks when a sequence (placed last) > given width, in alternate mode' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#3a', 'separator' =>", " } } # formatting matters here result = [ "[ 1,", " 2,", " 9,", # this sequence has length 3 (1,2,9) which does not cause breaking on each " [3, 4],", " [5,", " [6, 7]],", " 8,", " 900]", # this sequence has length 4 (8, 900) which causes breaking on each ].join("\n") formatted = converter.convert([1, 2, 9, [3, 4], [5, [6, 7]], 8, 900], string_formats) expect(formatted).to eq(result) end it 'indents and breaks nested sequences when one is placed first' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#a', 'separator' =>", " } } # formatting matters here result = [ "[", " [", " [1, 2,", " [3, 4]]],", " [5,", " [6, 7]],", " 8, 900]", ].join("\n") formatted = converter.convert([[[1, 2, [3, 4]]], [5, [6, 7]], 8, 900], string_formats) expect(formatted).to eq(result) end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => "%k"} converter.convert([1,2], string_formats) end.to raise_error(/Illegal format 'k' specified for value of Array type - expected one of the characters 'asp'/) end end context 'when converting hash' do it 'the default string representation is using {} delimiters, joins with '=>' and uses %p for values' do expect(converter.convert({"hello" => "world"}, :default)).to eq("{'hello' => 'world'}") end { "%s" => "{1 => 'world'}", "%p" => "{1 => 'world'}", "%h" => "{1 => 'world'}", "%a" => "[[1, 'world']]", "%<h" => "<1 => 'world'>", "%[h" => "[1 => 'world']", "%(h" => "(1 => 'world')", "%{h" => "{1 => 'world'}", "% h" => "1 => 'world'", {'format' => '%(h', 'separator2' => ' ' } => "(1 'world')", {'format' => '%(h', 'separator2' => ' ', 'string_formats' => {Puppet::Pops::Types::PIntegerType::DEFAULT => '%#x'} } => "(0x1 'world')", }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => fmt} expect(converter.convert({1 => "world"}, string_formats)).to eq(result) end end { "%s" => "{1 => 'hello', 2 => 'world'}", {'format' => '%(h', 'separator2' => ' ' } => "(1 'hello', 2 'world')", {'format' => '%(h', 'separator' => '', 'separator2' => '' } => "(1'hello'2'world')", {'format' => '%(h', 'separator' => ' >> ', 'separator2' => ' <=> ', 'string_formats' => {Puppet::Pops::Types::PIntegerType::DEFAULT => '%#x'} } => "(0x1 <=> 'hello' >> 0x2 <=> 'world')", }.each do |fmt, result | it "the format #{fmt} produces #{result}" do string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => fmt} expect(converter.convert({1 => "hello", 2 => "world"}, string_formats)).to eq(result) end end it 'indents elements in alternative mode #' do string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => { 'format' => '%#h', } } # formatting matters here result = [ "{", " 1 => 'hello',", " 2 => {", " 3 => 'world'", " }", "}" ].join("\n") expect(converter.convert({1 => "hello", 2 => {3=> "world"}}, string_formats)).to eq(result) end it 'applies a short form format' do result = [ "{", " 1 => {", " 2 => 3", " },", " 4 => 5", "}"].join("\n") expect(converter.convert({1 => {2 => 3}, 4 => 5}, '%#h')).to eq(result) end context "containing an array" do it 'the hash and array renders without breaks and indentation by default' do result = "{1 => [1, 2, 3]}" formatted = converter.convert({ 1 => [1, 2, 3] }, :default) expect(formatted).to eq(result) end it 'the array renders with breaks if so specified' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#1a', 'separator' =>"," } } result = [ "{1 => [ 1,", " 2,", " 3]}" ].join("\n") formatted = converter.convert({ 1 => [1, 2, 3] }, string_formats) expect(formatted).to eq(result) end it 'both hash and array renders with breaks and indentation if so specified for both' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#1a', 'separator' =>", " }, Puppet::Pops::Types::PHashType::DEFAULT => { 'format' => '%#h', 'separator' =>"," } } result = [ "{", " 1 => [ 1,", " 2,", " 3]", "}" ].join("\n") formatted = converter.convert({ 1 => [1, 2, 3] }, string_formats) expect(formatted).to eq(result) end it 'hash, but not array is rendered with breaks and indentation if so specified only for the hash' do string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%a', 'separator' =>", " }, Puppet::Pops::Types::PHashType::DEFAULT => { 'format' => '%#h', 'separator' =>"," } } result = [ "{", " 1 => [1, 2, 3]", "}" ].join("\n") formatted = converter.convert({ 1 => [1, 2, 3] }, string_formats) expect(formatted).to eq(result) end end context 'that is subclassed' do let(:array) { ['a', 2] } let(:derived_array) do Class.new(Array) do def to_a self # Dead wrong! Should return a plain Array copy end end.new(array) end let(:derived_with_to_a) do Class.new(Array) do def to_a super end end.new(array) end let(:hash) { {'first' => 1, 'second' => 2} } let(:derived_hash) do Class.new(Hash)[hash] end let(:derived_with_to_hash) do Class.new(Hash) do def to_hash {}.merge(self) end end[hash] end it 'formats a derived array as a Runtime' do expect(converter.convert(array)).to eq('[\'a\', 2]') expect(converter.convert(derived_array)).to eq('["a", 2]') end it 'formats a derived array with #to_a retuning plain Array as an Array' do expect(converter.convert(derived_with_to_a)).to eq('[\'a\', 2]') end it 'formats a derived hash as a Runtime' do expect(converter.convert(hash)).to eq('{\'first\' => 1, \'second\' => 2}') expect(converter.convert(derived_hash)).to match(/{"first"\s*=>\s*1, "second"\s*=>\s*2}/) end it 'formats a derived hash with #to_hash retuning plain Hash as a Hash' do expect(converter.convert(derived_with_to_hash, '%p')).to eq('{\'first\' => 1, \'second\' => 2}') end end it 'errors when format is not recognized' do expect do string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => "%k"} converter.convert({1 => 2}, string_formats) end.to raise_error(/Illegal format 'k' specified for value of Hash type - expected one of the characters 'hasp'/) end end context 'when converting a runtime type' do [ :sym, (1..3), Time.now ].each do |value| it "the default string representation for #{value} is #to_s" do expect(converter.convert(value, :default)).to eq(value.to_s) end it "the '%q' string representation for #{value} is #inspect" do expect(converter.convert(value, '%q')).to eq(value.inspect) end it "the '%p' string representation for #{value} is quoted #to_s" do
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_object_type_spec.rb
spec/unit/pops/types/p_object_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'The Object Type' do include PuppetSpec::Compiler let(:parser) { TypeParser.singleton } let(:pp_parser) { Parser::EvaluatingParser.new } let(:env) { Puppet::Node::Environment.create(:testing, []) } let(:node) { Puppet::Node.new('testnode', :environment => env) } let(:loader) { Loaders.find_loader(nil) } let(:factory) { TypeFactory } before(:each) do Puppet.push_context(:loaders => Loaders.new(env)) end after(:each) do Puppet.pop_context() end def type_object_t(name, body_string) object = PObjectType.new(name, pp_parser.parse_string("{#{body_string}}").body) loader.set_entry(Loader::TypedName.new(:type, name), object) object end def parse_object(name, body_string) type_object_t(name, body_string) parser.parse(name, loader).resolve(loader) end context 'when dealing with attributes' do it 'raises an error when the attribute type is not a type' do obj = <<-OBJECT attributes => { a => 23 } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /attribute MyObject\[a\] has wrong type, expects a Type value, got Integer/) end it 'raises an error if the type is missing' do obj = <<-OBJECT attributes => { a => { kind => derived } } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /expects a value for key 'type'/) end it 'raises an error when value is of incompatible type' do obj = <<-OBJECT attributes => { a => { type => Integer, value => 'three' } } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /attribute MyObject\[a\] value has wrong type, expects an Integer value, got String/) end it 'raises an error if the kind is invalid' do obj = <<-OBJECT attributes => { a => { type => String, kind => derivd } } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /expects a match for Enum\['constant', 'derived', 'given_or_derived', 'reference'\], got 'derivd'/) end it 'raises an error if the name is __ptype' do obj = <<-OBJECT attributes => { __ptype => String } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, /The attribute '__ptype' is reserved and cannot be used/) end it 'raises an error if the name is __pvalue' do obj = <<-OBJECT attributes => { __pvalue => String } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, /The attribute '__pvalue' is reserved and cannot be used/) end it 'stores value in attribute' do tp = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer, value => 3 } } OBJECT attr = tp['a'] expect(attr).to be_a(PObjectType::PAttribute) expect(attr.value).to eql(3) end it 'attribute with defined value responds true to value?' do tp = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer, value => 3 } } OBJECT attr = tp['a'] expect(attr.value?).to be_truthy end it 'attribute value can be defined using heredoc?' do tp = parse_object('MyObject', <<-OBJECT.unindent) attributes => { a => { type => String, value => @(END) } The value is some multiline text |-END } OBJECT attr = tp['a'] expect(attr.value).to eql("The value is some\nmultiline text") end it 'attribute without defined value responds false to value?' do tp = parse_object('MyObject', <<-OBJECT) attributes => { a => Integer } OBJECT attr = tp['a'] expect(attr.value?).to be_falsey end it 'attribute without defined value but optional type responds true to value?' do tp = parse_object('MyObject', <<-OBJECT) attributes => { a => Optional[Integer] } OBJECT attr = tp['a'] expect(attr.value?).to be_truthy expect(attr.value).to be_nil end it 'raises an error when value is requested from an attribute that has no value' do tp = parse_object('MyObject', <<-OBJECT) attributes => { a => Integer } OBJECT expect { tp['a'].value }.to raise_error(Puppet::Error, 'attribute MyObject[a] has no value') end context 'that are constants' do context 'and declared under key "constants"' do it 'sets final => true' do tp = parse_object('MyObject', <<-OBJECT) constants => { a => 3 } OBJECT expect(tp['a'].final?).to be_truthy end it 'sets kind => constant' do tp = parse_object('MyObject', <<-OBJECT) constants => { a => 3 } OBJECT expect(tp['a'].constant?).to be_truthy end it 'infers generic type from value' do tp = parse_object('MyObject', <<-OBJECT) constants => { a => 3 } OBJECT expect(tp['a'].type.to_s).to eql('Integer') end it 'cannot have the same name as an attribute' do obj = <<-OBJECT constants => { a => 3 }, attributes => { a => Integer } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, 'attribute MyObject[a] is defined as both a constant and an attribute') end end context 'and declared under key "attributes"' do it 'sets final => true when declard in attributes' do tp = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer, kind => constant, value => 3 } } OBJECT expect(tp['a'].final?).to be_truthy end it 'raises an error when no value is declared' do obj = <<-OBJECT attributes => { a => { type => Integer, kind => constant } } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, "attribute MyObject[a] of kind 'constant' requires a value") end it 'raises an error when final => false' do obj = <<-OBJECT attributes => { a => { type => Integer, kind => constant, final => false } } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, "attribute MyObject[a] of kind 'constant' cannot be combined with final => false") end end end end context 'when dealing with functions' do it 'raises an error unless the function type is a Type[Callable]' do obj = <<-OBJECT functions => { a => String } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /function MyObject\[a\] has wrong type, expects a Type\[Callable\] value, got Type\[String\]/) end it 'raises an error when a function has the same name as an attribute' do obj = <<-OBJECT attributes => { a => Integer }, functions => { a => Callable } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, 'function MyObject[a] conflicts with attribute with the same name') end end context 'when dealing with overrides' do it 'can redefine inherited member to assignable type' do parent = <<-OBJECT attributes => { a => Integer } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { a => { type => Integer[0,10], override => true } } OBJECT parse_object('MyObject', parent) tp = parse_object('MyDerivedObject', obj) expect(tp['a'].type).to eql(PIntegerType.new(0,10)) end it 'can redefine inherited constant to assignable type' do parent = <<-OBJECT constants => { a => 23 } OBJECT obj = <<-OBJECT parent => MyObject, constants => { a => 46 } OBJECT tp = parse_object('MyObject', parent) td = parse_object('MyDerivedObject', obj) expect(tp['a'].value).to eql(23) expect(td['a'].value).to eql(46) end it 'raises an error when an attribute overrides a function' do parent = <<-OBJECT attributes => { a => Integer } OBJECT obj = <<-OBJECT parent => MyObject, functions => { a => { type => Callable, override => true } } OBJECT parse_object('MyObject', parent) expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError, 'function MyDerivedObject[a] attempts to override attribute MyObject[a]') end it 'raises an error when the a function overrides an attribute' do parent = <<-OBJECT functions => { a => Callable } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { a => { type => Integer, override => true } } OBJECT parse_object('MyObject', parent) expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError, 'attribute MyDerivedObject[a] attempts to override function MyObject[a]') end it 'raises an error on attempts to redefine inherited member to unassignable type' do parent = <<-OBJECT attributes => { a => Integer } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { a => { type => String, override => true } } OBJECT parse_object('MyObject', parent) expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError, 'attribute MyDerivedObject[a] attempts to override attribute MyObject[a] with a type that does not match') end it 'raises an error when an attribute overrides a final attribute' do parent = <<-OBJECT attributes => { a => { type => Integer, final => true } } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { a => { type => Integer, override => true } } OBJECT parse_object('MyObject', parent) expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError, 'attribute MyDerivedObject[a] attempts to override final attribute MyObject[a]') end it 'raises an error when an overriding attribute is not declared with override => true' do parent = <<-OBJECT attributes => { a => Integer } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { a => Integer } OBJECT parse_object('MyObject', parent) expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError, 'attribute MyDerivedObject[a] attempts to override attribute MyObject[a] without having override => true') end it 'raises an error when an attribute declared with override => true does not override' do parent = <<-OBJECT attributes => { a => Integer } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { b => { type => Integer, override => true } } OBJECT parse_object('MyObject', parent) expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError, "expected attribute MyDerivedObject[b] to override an inherited attribute, but no such attribute was found") end end context 'when dealing with equality' do it 'the attributes can be declared as an array of names' do obj = <<-OBJECT attributes => { a => Integer, b => Integer }, equality => [a,b] OBJECT tp = parse_object('MyObject', obj) expect(tp.equality).to eq(['a','b']) expect(tp.equality_attributes.keys).to eq(['a','b']) end it 'a single [<name>] can be declared as <name>' do obj = <<-OBJECT attributes => { a => Integer, b => Integer }, equality => a OBJECT tp = parse_object('MyObject', obj) expect(tp.equality).to eq(['a']) end it 'includes all non-constant attributes by default' do obj = <<-OBJECT attributes => { a => Integer, b => { type => Integer, kind => constant, value => 3 }, c => Integer } OBJECT tp = parse_object('MyObject', obj) expect(tp.equality).to be_nil expect(tp.equality_attributes.keys).to eq(['a','c']) end it 'equality_include_type is true by default' do obj = <<-OBJECT attributes => { a => Integer }, equality => a OBJECT expect(parse_object('MyObject', obj).equality_include_type?).to be_truthy end it 'will allow an empty list of attributes' do obj = <<-OBJECT attributes => { a => Integer, b => Integer }, equality => [] OBJECT tp = parse_object('MyObject', obj) expect(tp.equality).to be_empty expect(tp.equality_attributes).to be_empty end it 'will extend default equality in parent' do parent = <<-OBJECT attributes => { a => Integer, b => Integer } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { c => Integer, d => Integer } OBJECT parse_object('MyObject', parent) tp = parse_object('MyDerivedObject', obj) expect(tp.equality).to be_nil expect(tp.equality_attributes.keys).to eq(['a','b','c','d']) end it 'extends equality declared in parent' do parent = <<-OBJECT attributes => { a => Integer, b => Integer }, equality => a OBJECT obj = <<-OBJECT parent => MyObject, attributes => { c => Integer, d => Integer } OBJECT parse_object('MyObject', parent) tp = parse_object('MyDerivedObject', obj) expect(tp.equality).to be_nil expect(tp.equality_attributes.keys).to eq(['a','c','d']) end it 'parent defined attributes can be included in equality if not already included by a parent' do parent = <<-OBJECT attributes => { a => Integer, b => Integer }, equality => a OBJECT obj = <<-OBJECT parent => MyObject, attributes => { c => Integer, d => Integer }, equality => [b,c] OBJECT parse_object('MyObject', parent) tp = parse_object('MyDerivedObject', obj) expect(tp.equality).to eq(['b','c']) expect(tp.equality_attributes.keys).to eq(['a','b','c']) end it 'raises an error when attempting to extend default equality in parent' do parent = <<-OBJECT attributes => { a => Integer, b => Integer } OBJECT obj = <<-OBJECT parent => MyObject, attributes => { c => Integer, d => Integer }, equality => a OBJECT parse_object('MyObject', parent) expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError, "MyDerivedObject equality is referencing attribute MyObject[a] which is included in equality of MyObject") end it 'raises an error when equality references a constant attribute' do obj = <<-OBJECT attributes => { a => Integer, b => { type => Integer, kind => constant, value => 3 } }, equality => [a,b] OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, 'MyObject equality is referencing constant attribute MyObject[b]. Reference to constant is not allowed in equality') end it 'raises an error when equality references a function' do obj = <<-OBJECT attributes => { a => Integer, }, functions => { b => Callable }, equality => [a,b] OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, 'MyObject equality is referencing function MyObject[b]. Only attribute references are allowed') end it 'raises an error when equality references a non existent attributes' do obj = <<-OBJECT attributes => { a => Integer }, equality => [a,b] OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, "MyObject equality is referencing non existent attribute 'b'") end it 'raises an error when equality_include_type = false and attributes are provided' do obj = <<-OBJECT attributes => { a => Integer }, equality => a, equality_include_type => false OBJECT expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError, 'equality_include_type = false cannot be combined with non empty equality specification') end end it 'raises an error when initialization hash contains invalid keys' do obj = <<-OBJECT attribrutes => { a => Integer } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /object initializer has wrong type, unrecognized key 'attribrutes'/) end it 'raises an error when attribute contains invalid keys' do obj = <<-OBJECT attributes => { a => { type => Integer, knid => constant } } OBJECT expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /initializer for attribute MyObject\[a\] has wrong type, unrecognized key 'knid'/) end context 'when inheriting from a another Object type' do let(:parent) { <<-OBJECT } attributes => { a => Integer }, functions => { b => Callable } OBJECT let(:derived) { <<-OBJECT } parent => MyObject, attributes => { c => String, d => Boolean } OBJECT it 'includes the inherited type and its members' do parse_object('MyObject', parent) t = parse_object('MyDerivedObject', derived) members = t.members.values expect{ |b| members.each {|m| m.name.tap(&b) }}.to yield_successive_args('c', 'd') expect{ |b| members.each {|m| m.type.simple_name.tap(&b) }}.to yield_successive_args('String', 'Boolean') members = t.members(true).values expect{ |b| members.each {|m| m.name.tap(&b) }}.to yield_successive_args('a', 'b', 'c', 'd') expect{ |b| members.each {|m| m.type.simple_name.tap(&b) }}.to(yield_successive_args('Integer', 'Callable', 'String', 'Boolean')) end it 'is assignable to its inherited type' do p = parse_object('MyObject', parent) t = parse_object('MyDerivedObject', derived) expect(p).to be_assignable(t) end it 'does not consider inherited type to be assignable' do p = parse_object('MyObject', parent) d = parse_object('MyDerivedObject', derived) expect(d).not_to be_assignable(p) end it 'ruby access operator can retrieve parent member' do p = parse_object('MyObject', parent) d = parse_object('MyDerivedObject', derived) expect(d['b'].container).to equal(p) end context 'that in turn inherits another Object type' do let(:derived2) { <<-OBJECT } parent => MyDerivedObject, attributes => { e => String, f => Boolean } OBJECT it 'is assignable to all inherited types' do p = parse_object('MyObject', parent) d1 = parse_object('MyDerivedObject', derived) d2 = parse_object('MyDerivedObject2', derived2) expect(p).to be_assignable(d2) expect(d1).to be_assignable(d2) end it 'does not consider any of the inherited types to be assignable' do p = parse_object('MyObject', parent) d1 = parse_object('MyDerivedObject', derived) d2 = parse_object('MyDerivedObject2', derived2) expect(d2).not_to be_assignable(p) expect(d2).not_to be_assignable(d1) end end end context 'when producing an init_hash_type' do it 'produces a struct of all attributes that are not derived or constant' do t = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer }, b => { type => Integer, kind => given_or_derived }, c => { type => Integer, kind => derived }, d => { type => Integer, kind => constant, value => 4 } } OBJECT expect(t.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, 'b' => factory.integer })) end it 'produces a struct where optional entires are denoted with an optional key' do t = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer }, b => { type => Integer, value => 4 } } OBJECT expect(t.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, factory.optional('b') => factory.integer })) end it 'produces a struct that includes parameters from parent type' do t1 = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer } } OBJECT t2 = parse_object('MyDerivedObject', <<-OBJECT) parent => MyObject, attributes => { b => { type => Integer } } OBJECT expect(t1.init_hash_type).to eql(factory.struct({ 'a' => factory.integer })) expect(t2.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, 'b' => factory.integer })) end it 'produces a struct that reflects overrides made in derived type' do t1 = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer }, b => { type => Integer } } OBJECT t2 = parse_object('MyDerivedObject', <<-OBJECT) parent => MyObject, attributes => { b => { type => Integer, override => true, value => 5 } } OBJECT expect(t1.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, 'b' => factory.integer })) expect(t2.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, factory.optional('b') => factory.integer })) end end context 'with attributes and parameters of its own type' do it 'resolves an attribute type' do t = parse_object('MyObject', <<-OBJECT) attributes => { a => MyObject } OBJECT expect(t['a'].type).to equal(t) end it 'resolves a parameter type' do t = parse_object('MyObject', <<-OBJECT) functions => { a => Callable[MyObject] } OBJECT expect(t['a'].type).to eql(PCallableType.new(PTupleType.new([t]))) end end context 'when using the initialization hash' do it 'produced hash that contains features using short form (type instead of detailed hash when only type is declared)' do obj = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer } } OBJECT expect(obj.to_s).to eql("Object[{name => 'MyObject', attributes => {'a' => Integer}}]") end it 'produced hash that does not include default for equality_include_type' do obj = parse_object('MyObject', <<-OBJECT) attributes => { a => Integer }, equality_include_type => true OBJECT expect(obj.to_s).to eql("Object[{name => 'MyObject', attributes => {'a' => Integer}}]") end it 'constants are presented in a separate hash if they use a generic type' do obj = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer, value => 23, kind => constant }, }, OBJECT expect(obj.to_s).to eql("Object[{name => 'MyObject', constants => {'a' => 23}}]") end it 'constants are not presented in a separate hash unless they use a generic type' do obj = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer[0, 30], value => 23, kind => constant }, }, OBJECT expect(obj.to_s).to eql("Object[{name => 'MyObject', attributes => {'a' => {type => Integer[0, 30], kind => constant, value => 23}}}]") end it 'can create an equal copy from produced hash' do obj = parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Struct[{x => Integer, y => Integer}], value => {x => 4, y => 9}, kind => constant }, b => Integer }, functions => { x => Callable[MyObject,Integer] }, equality => [b] OBJECT obj2 = PObjectType.new(obj._pcore_init_hash) expect(obj).to eql(obj2) end end context 'when stringifying created instances' do it 'outputs a Puppet constructor using the initializer hash' do code = <<-CODE type Spec::MyObject = Object[{attributes => { a => Integer }}] type Spec::MySecondObject = Object[{parent => Spec::MyObject, attributes => { b => String }}] notice(Spec::MySecondObject(42, 'Meaning of life')) CODE expect(eval_and_collect_notices(code)).to eql(["Spec::MySecondObject({'a' => 42, 'b' => 'Meaning of life'})"]) end end context 'when used from Ruby' do it 'can create an instance without scope using positional arguments' do parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer } } OBJECT t = Puppet::Pops::Types::TypeParser.singleton.parse('MyObject', Puppet::Pops::Loaders.find_loader(nil)) instance = t.create(32) expect(instance.a).to eql(32) end it 'can create an instance without scope using initialization hash' do parse_object('MyObject', <<-OBJECT) attributes => { a => { type => Integer } } OBJECT t = Puppet::Pops::Types::TypeParser.singleton.parse('MyObject', Puppet::Pops::Loaders.find_loader(nil)) instance = t.from_hash('a' => 32) expect(instance.a).to eql(32) end end context 'when used in Puppet expressions' do it 'two anonymous empty objects are equal' do code = <<-CODE $x = Object[{}] $y = Object[{}] notice($x == $y) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'two objects where one object inherits another object are different' do code = <<-CODE type MyFirstObject = Object[{}] type MySecondObject = Object[{ parent => MyFirstObject }] notice(MyFirstObject == MySecondObject) CODE expect(eval_and_collect_notices(code)).to eql(['false']) end it 'two anonymous objects that inherits the same parent are equal' do code = <<-CODE type MyFirstObject = Object[{}] $x = Object[{ parent => MyFirstObject }] $y = Object[{ parent => MyFirstObject }] notice($x == $y) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'declared Object type is assignable to default Object type' do code = <<-CODE type MyObject = Object[{ attributes => { a => Integer }}] notice(MyObject < Object) notice(MyObject <= Object) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'true']) end it 'default Object type not is assignable to declared Object type' do code = <<-CODE type MyObject = Object[{ attributes => { a => Integer }}] notice(Object < MyObject) notice(Object <= MyObject) CODE expect(eval_and_collect_notices(code)).to eql(['false', 'false']) end it 'default Object type is assignable to itself' do code = <<-CODE notice(Object < Object) notice(Object <= Object) notice(Object > Object) notice(Object >= Object) CODE expect(eval_and_collect_notices(code)).to eql(['false', 'true', 'false', 'true']) end it 'an object type is an instance of an object type type' do code = <<-CODE type MyObject = Object[{ attributes => { a => Integer }}] notice(MyObject =~ Type[MyObject]) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'an object that inherits another object is an instance of the type of its parent' do code = <<-CODE type MyFirstObject = Object[{}] type MySecondObject = Object[{ parent => MyFirstObject }] notice(MySecondObject =~ Type[MyFirstObject]) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'a named object is not added to the loader unless a type <name> = <definition> is made' do code = <<-CODE $x = Object[{ name => 'MyFirstObject' }] notice($x == MyFirstObject) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Resource type not found: MyFirstObject/) end it 'a type alias on a named object overrides the name' do code = <<-CODE type MyObject = Object[{ name => 'MyFirstObject', attributes => { a => { type => Integer, final => true }}}] type MySecondObject = Object[{ parent => MyObject, attributes => { a => { type => Integer[10], override => true }}}] notice(MySecondObject =~ Type) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /attribute MySecondObject\[a\] attempts to override final attribute MyObject\[a\]/) end it 'a type cannot be created using an unresolved parent' do code = <<-CODE notice(Object[{ name => 'MyObject', parent => Type('NoneSuch'), attributes => { a => String}}].new('hello')) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /reference to unresolved type 'NoneSuch'/) end context 'type alias using bracket-less (implicit Object) form' do let(:logs) { [] } let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } let(:node) { Puppet::Node.new('example.com') } let(:compiler) { Puppet::Parser::Compiler.new(node) } def compile(code) Puppet[:code] = code Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) { compiler.compile } end it 'Object is implicit' do compile(<<-CODE) type MyObject = { name => 'MyFirstObject', attributes => { a => Integer}} notice(MyObject =~ Type) notice(MyObject(3)) CODE expect(warnings).to be_empty expect(notices).to eql(['true', "MyObject({'a' => 3})"]) end it 'Object can be specified' do compile(<<-CODE) type MyObject = Object { name => 'MyFirstObject', attributes => { a =>Integer }} notice(MyObject =~ Type) notice(MyObject(3)) CODE expect(warnings).to be_empty expect(notices).to eql(['true', "MyObject({'a' => 3})"]) end it 'parent can be specified before the hash' do compile(<<-CODE) type MyObject = { name => 'MyFirstObject', attributes => { a => String }} type MySecondObject = MyObject { attributes => { b => String }} notice(MySecondObject =~ Type) notice(MySecondObject < MyObject) notice(MyObject('hi')) notice(MySecondObject('hello', 'world')) CODE expect(warnings).to be_empty expect(notices).to eql(
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_uri_type_spec.rb
spec/unit/pops/types/p_uri_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'URI type' do context 'when used in Puppet expressions' do include PuppetSpec::Compiler it 'is equal to itself only' do expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true false false)) $t = URI notice(URI =~ Type[URI]) notice(URI == URI) notice(URI < URI) notice(URI > URI) CODE end context "when parameterized" do it 'is equal other types with the same parameterization' do code = <<-CODE notice(URI == URI[{}]) notice(URI['http://example.com'] == URI[scheme => http, host => 'example.com']) notice(URI['urn:a:b:c'] == URI[scheme => urn, opaque => 'a:b:c']) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true true)) end it 'is assignable from more qualified types' do expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true true)) notice(URI > URI['http://example.com']) notice(URI['http://example.com'] > URI['http://example.com/path']) notice(URI[scheme => Enum[http, https]] > URI['http://example.com']) CODE end it 'is not assignable unless scheme is assignable' do expect(eval_and_collect_notices(<<-CODE)).to eq(%w(false)) notice(URI[scheme => Enum[http, https]] > URI[scheme => 'ftp']) CODE end it 'presents parsable string form' do code = <<-CODE notice(URI['https://user:password@www.example.com:3000/some/path?x=y#frag']) CODE expect(eval_and_collect_notices(code)).to eq([ "URI[{'scheme' => 'https', 'userinfo' => 'user:password', 'host' => 'www.example.com', 'port' => '3000', 'path' => '/some/path', 'query' => 'x=y', 'fragment' => 'frag'}]", ]) end end context 'a URI instance' do it 'can be created from a string' do code = <<-CODE $o = URI('https://example.com/a/b') notice(String($o, '%p')) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq([ "URI('https://example.com/a/b')", "URI[{'scheme' => 'https', 'host' => 'example.com', 'path' => '/a/b'}]" ]) end it 'which is opaque, can be created from a string' do code = <<-CODE $o = URI('urn:a:b:c') notice(String($o, '%p')) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq([ "URI('urn:a:b:c')", "URI[{'scheme' => 'urn', 'opaque' => 'a:b:c'}]" ]) end it 'can be created from a hash' do code = <<-CODE $o = URI(scheme => 'https', host => 'example.com', path => '/a/b') notice(String($o, '%p')) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq([ "URI('https://example.com/a/b')", "URI[{'scheme' => 'https', 'host' => 'example.com', 'path' => '/a/b'}]" ]) end it 'which is opaque, can be created from a hash' do code = <<-CODE $o = URI(scheme => 'urn', opaque => 'a:b:c') notice(String($o, '%p')) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq([ "URI('urn:a:b:c')", "URI[{'scheme' => 'urn', 'opaque' => 'a:b:c'}]" ]) end it 'is an instance of its type' do code = <<-CODE $o = URI('https://example.com/a/b') notice($o =~ type($o)) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'is an instance of matching parameterized URI' do code = <<-CODE $o = URI('https://example.com/a/b') notice($o =~ URI[scheme => https, host => 'example.com']) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'is an instance of matching default URI' do code = <<-CODE $o = URI('https://example.com/a/b') notice($o =~ URI) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'path is not matched by opaque' do code = <<-CODE $o = URI('urn:a:b:c') notice($o =~ URI[path => 'a:b:c']) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'opaque is not matched by path' do code = <<-CODE $o = URI('https://example.com/a/b') notice($o =~ URI[opaque => '/a/b']) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'is not an instance unless parameters matches' do code = <<-CODE $o = URI('https://example.com/a/b') notice($o =~ URI[scheme => http]) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'individual parts of URI can be accessed using accessor methods' do code = <<-CODE $o = URI('https://bob:pw@example.com:8080/a/b?a=b#frag') notice($o.scheme) notice($o.userinfo) notice($o.host) notice($o.port) notice($o.path) notice($o.query) notice($o.fragment) CODE expect(eval_and_collect_notices(code)).to eq(['https', 'bob:pw', 'example.com', '8080', '/a/b', 'a=b', 'frag']) end it 'individual parts of opaque URI can be accessed using accessor methods' do code = <<-CODE $o = URI('urn:a:b:c') notice($o.scheme) notice($o.opaque) CODE expect(eval_and_collect_notices(code)).to eq(['urn', 'a:b:c']) end it 'An URI can be merged with a String using the + operator' do code = <<-CODE notice(String(URI('https://example.com') + '/a/b', '%p')) CODE expect(eval_and_collect_notices(code)).to eq(["URI('https://example.com/a/b')"]) end it 'An URI can be merged with another URI using the + operator' do code = <<-CODE notice(String(URI('https://example.com') + URI('/a/b'), '%p')) CODE expect(eval_and_collect_notices(code)).to eq(["URI('https://example.com/a/b')"]) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_sem_ver_type_spec.rb
spec/unit/pops/types/p_sem_ver_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Semantic Versions' do include PuppetSpec::Compiler context 'the SemVer type' do it 'is normalized in a Variant' do t = TypeFactory.variant(TypeFactory.sem_ver('>=1.0.0 <2.0.0'), TypeFactory.sem_ver('>=1.5.0 <4.0.0')).normalize expect(t).to be_a(PSemVerType) expect(t).to eql(TypeFactory.sem_ver('>=1.0.0 <4.0.0')) end context 'convert method' do it 'returns nil on a nil argument' do expect(PSemVerType.convert(nil)).to be_nil end it 'returns its argument when the argument is a version' do v = SemanticPuppet::Version.new(1,0,0) expect(PSemVerType.convert(v)).to equal(v) end it 'converts a valid version string argument to a version' do v = SemanticPuppet::Version.new(1,0,0) expect(PSemVerType.convert('1.0.0')).to eq(v) end it 'raises an error string that does not represent a valid version' do expect{PSemVerType.convert('1-3')}.to raise_error(ArgumentError) end end end context 'the SemVerRange type' do context 'convert method' do it 'returns nil on a nil argument' do expect(PSemVerRangeType.convert(nil)).to be_nil end it 'returns its argument when the argument is a version range' do vr = SemanticPuppet::VersionRange.parse('1.x') expect(PSemVerRangeType.convert(vr)).to equal(vr) end it 'converts a valid version string argument to a version range' do vr = SemanticPuppet::VersionRange.parse('1.x') expect(PSemVerRangeType.convert('1.x')).to eq(vr) end it 'raises an error string that does not represent a valid version range' do expect{PSemVerRangeType.convert('x3')}.to raise_error(ArgumentError) end end end context 'when used in Puppet expressions' do context 'the SemVer type' do it 'can have multiple range arguments' do code = <<-CODE $t = SemVer[SemVerRange('>=1.0.0 <2.0.0'), SemVerRange('>=3.0.0 <4.0.0')] notice(SemVer('1.2.3') =~ $t) notice(SemVer('2.3.4') =~ $t) notice(SemVer('3.4.5') =~ $t) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true']) end it 'can have multiple range arguments in string form' do code = <<-CODE $t = SemVer['>=1.0.0 <2.0.0', '>=3.0.0 <4.0.0'] notice(SemVer('1.2.3') =~ $t) notice(SemVer('2.3.4') =~ $t) notice(SemVer('3.4.5') =~ $t) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true']) end it 'range arguments are normalized' do code = <<-CODE notice(SemVer['>=1.0.0 <2.0.0', '>=1.5.0 <4.0.0'] == SemVer['>=1.0.0 <4.0.0']) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'is assignable to a type containing ranges with a merged range that is assignable but individual ranges are not' do code = <<-CODE $x = SemVer['>=1.0.0 <2.0.0', '>=1.5.0 <3.0.0'] $y = SemVer['>=1.2.0 <2.8.0'] notice($y < $x) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end end context 'the SemVerRange type' do it 'a range is an instance of the type' do code = <<-CODE notice(SemVerRange('3.0.0 - 4.0.0') =~ SemVerRange) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end end context 'a SemVer instance' do it 'can be created from a String' do code = <<-CODE $x = SemVer('1.2.3') notice(assert_type(SemVer, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['1.2.3']) end it 'can be compared to another instance for equality' do code = <<-CODE $x = SemVer('1.2.3') $y = SemVer('1.2.3') notice($x == $y) notice($x != $y) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'false']) end it 'can be compared to another instance created from arguments' do code = <<-CODE $x = SemVer('1.2.3-rc4+5') $y = SemVer(1, 2, 3, 'rc4', '5') notice($x == $y) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'can be compared to another instance created from a hash' do code = <<-CODE $x = SemVer('1.2.3-rc4+5') $y = SemVer(major => 1, minor => 2, patch => 3, prerelease => 'rc4', build => '5') notice($x == $y) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it 'can be compared to another instance for magnitude' do code = <<-CODE $x = SemVer('1.1.1') $y = SemVer('1.2.3') notice($x < $y) notice($x <= $y) notice($x > $y) notice($x >= $y) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'true', 'false', 'false']) end it 'can be matched against a version range' do code = <<-CODE $v = SemVer('1.1.1') notice($v =~ SemVerRange('>1.0.0')) notice($v =~ SemVerRange('>1.1.1')) notice($v =~ SemVerRange('>=1.1.1')) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true']) end it 'can be matched against a SemVerRange in case expression' do code = <<-CODE case SemVer('1.1.1') { SemVerRange('>1.1.1'): { notice('high') } SemVerRange('>1.0.0'): { notice('mid') } default: { notice('low') } } CODE expect(eval_and_collect_notices(code)).to eql(['mid']) end it 'can be matched against a SemVer in case expression' do code = <<-CODE case SemVer('1.1.1') { SemVer('1.1.0'): { notice('high') } SemVer('1.1.1'): { notice('mid') } default: { notice('low') } } CODE expect(eval_and_collect_notices(code)).to eql(['mid']) end it "can be matched against a versions in 'in' expression" do code = <<-CODE notice(SemVer('1.1.1') in [SemVer('1.0.0'), SemVer('1.1.1'), SemVer('2.3.4')]) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it "can be matched against a VersionRange using an 'in' expression" do code = <<-CODE notice(SemVer('1.1.1') in SemVerRange('>1.0.0')) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it "can be matched against multiple VersionRanges using an 'in' expression" do code = <<-CODE notice(SemVer('1.1.1') in [SemVerRange('>=1.0.0 <1.0.2'), SemVerRange('>=1.1.0 <1.1.2')]) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end end context 'a String representing a SemVer' do it 'can be matched against a version range' do code = <<-CODE $v = '1.1.1' notice($v =~ SemVerRange('>1.0.0')) notice($v =~ SemVerRange('>1.1.1')) notice($v =~ SemVerRange('>=1.1.1')) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true']) end it 'can be matched against a SemVerRange in case expression' do code = <<-CODE case '1.1.1' { SemVerRange('>1.1.1'): { notice('high') } SemVerRange('>1.0.0'): { notice('mid') } default: { notice('low') } } CODE expect(eval_and_collect_notices(code)).to eql(['mid']) end it 'can be matched against a SemVer in case expression' do code = <<-CODE case '1.1.1' { SemVer('1.1.0'): { notice('high') } SemVer('1.1.1'): { notice('mid') } default: { notice('low') } } CODE expect(eval_and_collect_notices(code)).to eql(['mid']) end it "can be matched against a VersionRange using an 'in' expression" do code = <<-CODE notice('1.1.1' in SemVerRange('>1.0.0')) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end it "can be matched against multiple VersionRanges using an 'in' expression" do code = <<-CODE notice('1.1.1' in [SemVerRange('>=1.0.0 <1.0.2'), SemVerRange('>=1.1.0 <1.1.2')]) CODE expect(eval_and_collect_notices(code)).to eql(['true']) end end context 'matching SemVer' do suitability = { [ '1.2.3', '1.2.2' ] => false, [ '>=1.2.3', '1.2.2' ] => false, [ '<=1.2.3', '1.2.2' ] => true, [ '1.2.3 - 1.2.4', '1.2.2' ] => false, [ '~1.2.3', '1.2.2' ] => false, [ '~1.2', '1.2.2' ] => true, [ '~1', '1.2.2' ] => true, [ '1.2.x', '1.2.2' ] => true, [ '1.x', '1.2.2' ] => true, [ '1.2.3-alpha', '1.2.3-alpha' ] => true, [ '>=1.2.3-alpha', '1.2.3-alpha' ] => true, [ '<=1.2.3-alpha', '1.2.3-alpha' ] => true, [ '<=1.2.3-alpha', '1.2.3-a' ] => true, [ '>1.2.3-alpha', '1.2.3-alpha' ] => false, [ '>1.2.3-a', '1.2.3-alpha' ] => true, [ '<1.2.3-alpha', '1.2.3-alpha' ] => false, [ '<1.2.3-alpha', '1.2.3-a' ] => true, [ '1.2.3-alpha - 1.2.4', '1.2.3-alpha' ] => true, [ '1.2.3 - 1.2.4-alpha', '1.2.4-alpha' ] => true, [ '1.2.3 - 1.2.4', '1.2.5-alpha' ] => false, [ '~1.2.3-alhpa', '1.2.3-alpha' ] => true, [ '~1.2.3-alpha', '1.3.0-alpha' ] => false, [ '1.2.3', '1.2.3' ] => true, [ '>=1.2.3', '1.2.3' ] => true, [ '<=1.2.3', '1.2.3' ] => true, [ '1.2.3 - 1.2.4', '1.2.3' ] => true, [ '~1.2.3', '1.2.3' ] => true, [ '~1.2', '1.2.3' ] => true, [ '~1', '1.2.3' ] => true, [ '1.2.x', '1.2.3' ] => true, [ '1.x', '1.2.3' ] => true, [ '1.2.3', '1.2.4' ] => false, [ '>=1.2.3', '1.2.4' ] => true, [ '<=1.2.3', '1.2.4' ] => false, [ '1.2.3 - 1.2.4', '1.2.4' ] => true, # [ '~1.2.3', '1.2.4' ] => true, Awaits fix for PUP-6242 [ '~1.2', '1.2.4' ] => true, [ '~1', '1.2.4' ] => true, [ '1.2.x', '1.2.4' ] => true, [ '1.x', '1.2.4' ] => true, } suitability.each do |arguments, expected| it "'#{arguments[1]}' against SemVerRange '#{arguments[0]}', yields #{expected}" do code = "notice(SemVer('#{arguments[1]}') =~ SemVerRange('#{arguments[0]}'))" expect(eval_and_collect_notices(code)).to eql([expected.to_s]) end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/types_spec.rb
spec/unit/pops/types/types_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Puppet Type System' do include PuppetSpec::Compiler let(:tf) { TypeFactory } context 'Integer type' do let!(:a) { tf.range(10, 20) } let!(:b) { tf.range(18, 28) } let!(:c) { tf.range( 2, 12) } let!(:d) { tf.range(12, 18) } let!(:e) { tf.range( 8, 22) } let!(:f) { tf.range( 8, 9) } let!(:g) { tf.range(21, 22) } let!(:h) { tf.range(30, 31) } let!(:i) { tf.float_range(1.0, 30.0) } let!(:j) { tf.float_range(1.0, 9.0) } context 'when testing if ranges intersect' do it 'detects an intersection when self is before its argument' do expect(a.intersect?(b)).to be_truthy end it 'detects an intersection when self is after its argument' do expect(a.intersect?(c)).to be_truthy end it 'detects an intersection when self covers its argument' do expect(a.intersect?(d)).to be_truthy end it 'detects an intersection when self equals its argument' do expect(a.intersect?(a)).to be_truthy end it 'detects an intersection when self is covered by its argument' do expect(a.intersect?(e)).to be_truthy end it 'does not consider an adjacent range to be intersecting' do [f, g].each {|x| expect(a.intersect?(x)).to be_falsey } end it 'does not consider an range that is apart to be intersecting' do expect(a.intersect?(h)).to be_falsey end it 'does not consider an overlapping float range to be intersecting' do expect(a.intersect?(i)).to be_falsey end end context 'when testing if ranges are adjacent' do it 'detects an adjacent type when self is after its argument' do expect(a.adjacent?(f)).to be_truthy end it 'detects an adjacent type when self is before its argument' do expect(a.adjacent?(g)).to be_truthy end it 'does not consider overlapping types to be adjacent' do [a, b, c, d, e].each { |x| expect(a.adjacent?(x)).to be_falsey } end it 'does not consider an range that is apart to be adjacent' do expect(a.adjacent?(h)).to be_falsey end it 'does not consider an adjacent float range to be adjancent' do expect(a.adjacent?(j)).to be_falsey end end context 'when merging ranges' do it 'will merge intersecting ranges' do expect(a.merge(b)).to eq(tf.range(10, 28)) end it 'will merge adjacent ranges' do expect(a.merge(g)).to eq(tf.range(10, 22)) end it 'will not merge ranges that are apart' do expect(a.merge(h)).to be_nil end it 'will not merge overlapping float ranges' do expect(a.merge(i)).to be_nil end it 'will not merge adjacent float ranges' do expect(a.merge(j)).to be_nil end end end context 'Float type' do let!(:a) { tf.float_range(10.0, 20.0) } let!(:b) { tf.float_range(18.0, 28.0) } let!(:c) { tf.float_range( 2.0, 12.0) } let!(:d) { tf.float_range(12.0, 18.0) } let!(:e) { tf.float_range( 8.0, 22.0) } let!(:f) { tf.float_range(30.0, 31.0) } let!(:g) { tf.range(1, 30) } context 'when testing if ranges intersect' do it 'detects an intersection when self is before its argument' do expect(a.intersect?(b)).to be_truthy end it 'detects an intersection when self is after its argument' do expect(a.intersect?(c)).to be_truthy end it 'detects an intersection when self covers its argument' do expect(a.intersect?(d)).to be_truthy end it 'detects an intersection when self equals its argument' do expect(a.intersect?(a)).to be_truthy end it 'detects an intersection when self is covered by its argument' do expect(a.intersect?(e)).to be_truthy end it 'does not consider an range that is apart to be intersecting' do expect(a.intersect?(f)).to be_falsey end it 'does not consider an overlapping integer range to be intersecting' do expect(a.intersect?(g)).to be_falsey end end context 'when merging ranges' do it 'will merge intersecting ranges' do expect(a.merge(b)).to eq(tf.float_range(10.0, 28.0)) end it 'will not merge ranges that are apart' do expect(a.merge(f)).to be_nil end it 'will not merge overlapping integer ranges' do expect(a.merge(g)).to be_nil end end end context 'Boolean type' do it 'parameterized type is assignable to base type' do code = <<-CODE notice(Boolean[true] < Boolean) notice(Boolean[false] < Boolean) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true']) end it 'boolean literals are instances of the base type' do code = <<-CODE notice(true =~ Boolean) notice(false =~ Boolean) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true']) end it 'boolean literals are instances of type parameterized with the same literal' do code = <<-CODE notice(true =~ Boolean[true]) notice(false =~ Boolean[false]) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true']) end it 'boolean literals are not instances of type parameterized with a different literal' do code = <<-CODE notice(true =~ Boolean[false]) notice(false =~ Boolean[true]) CODE expect(eval_and_collect_notices(code)).to eq(['false', 'false']) end end context 'Enum type' do it 'sorts its entries' do code = <<-CODE Enum[c,b,a].each |$e| { notice $e } CODE expect(eval_and_collect_notices(code)).to eq(['a', 'b', 'c']) end it 'makes entries unique' do code = <<-CODE Enum[a,b,c,b,a].each |$e| { notice $e } CODE expect(eval_and_collect_notices(code)).to eq(['a', 'b', 'c']) end it 'is case sensitive by default' do code = <<-CODE notice('A' =~ Enum[a,b]) notice('a' =~ Enum[a,b]) CODE expect(eval_and_collect_notices(code)).to eq(['false', 'true']) end it 'is case insensitive when last parameter argument is true' do code = <<-CODE notice('A' =~ Enum[a,b,true]) notice('a' =~ Enum[a,b,true]) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true']) end end context 'Regexp type' do it 'parameterized type is assignable to base type' do code = <<-CODE notice(Regexp[a] < Regexp) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'new function creates a new regexp' do code = <<-CODE $r = Regexp('abc') notice('abc' =~ $r) notice(type($r) =~ Type[Regexp]) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true']) end it 'special characters are escaped with second parameter to Regexp.new set to true' do code = <<-CODE $r = Regexp('.[]', true) notice('.[]' =~ $r) notice(String($r) == "\\.\\[\\]") CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true']) end end context 'Iterable type' do it 'can be parameterized with element type' do code = <<-CODE function foo(Iterable[String] $x) { $x.each |$e| { notice $e } } foo([bar, baz, cake]) CODE expect(eval_and_collect_notices(code)).to eq(['bar', 'baz', 'cake']) end end context 'Iterator type' do let!(:iterint) { tf.iterator(tf.integer) } context 'when testing instance?' do it 'will consider an iterable on an integer is an instance of Iterator[Integer]' do expect(iterint.instance?(Iterable.on(3))).to be_truthy end it 'will consider an iterable on string to be an instance of Iterator[Integer]' do expect(iterint.instance?(Iterable.on('string'))).to be_falsey end end context 'when testing assignable?' do it 'will consider an iterator with an assignable type as assignable' do expect(tf.iterator(tf.numeric).assignable?(iterint)).to be_truthy end it 'will not consider an iterator with a non assignable type as assignable' do expect(tf.iterator(tf.string).assignable?(iterint)).to be_falsey end end context 'when asked for an iterable type' do it 'the default iterator type returns the default iterable type' do expect(PIteratorType::DEFAULT.iterable_type).to be(PIterableType::DEFAULT) end it 'a typed iterator type returns the an equally typed iterable type' do expect(iterint.iterable_type).to eq(tf.iterable(tf.integer)) end end it 'can be parameterized with an element type' do code = <<-CODE function foo(Iterator[String] $x) { $x.each |$e| { notice $e } } foo([bar, baz, cake].reverse_each) CODE expect(eval_and_collect_notices(code)).to eq(['cake', 'baz', 'bar']) end end context 'Collection type' do it 'can be parameterized with a range' do code = <<-CODE notice(Collection[5, default] == Collection[5]) notice(Collection[5, 5] > Tuple[Integer, 0, 10]) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'false']) end end context 'Struct type' do context 'can be used as key in hash' do it 'compacts optional in optional in optional to just optional' do key1 = tf.struct({'foo' => tf.string}) key2 = tf.struct({'foo' => tf.string}) expect({key1 => 'hi'}[key2]).to eq('hi') end end end context 'Optional type' do let!(:overlapping_ints) { tf.variant(tf.range(10, 20), tf.range(18, 28)) } let!(:optoptopt) { tf.optional(tf.optional(tf.optional(overlapping_ints))) } let!(:optnu) { tf.optional(tf.not_undef(overlapping_ints)) } context 'when normalizing' do it 'compacts optional in optional in optional to just optional' do expect(optoptopt.normalize).to eq(tf.optional(tf.range(10, 28))) end end it 'compacts NotUndef in Optional to just Optional' do expect(optnu.normalize).to eq(tf.optional(tf.range(10, 28))) end end context 'NotUndef type' do let!(:nununu) { tf.not_undef(tf.not_undef(tf.not_undef(tf.any))) } let!(:nuopt) { tf.not_undef(tf.optional(tf.any)) } let!(:nuoptint) { tf.not_undef(tf.optional(tf.integer)) } context 'when normalizing' do it 'compacts NotUndef in NotUndef in NotUndef to just NotUndef' do expect(nununu.normalize).to eq(tf.not_undef(tf.any)) end it 'compacts Optional in NotUndef to just NotUndef' do expect(nuopt.normalize).to eq(tf.not_undef(tf.any)) end it 'compacts NotUndef[Optional[Integer]] in NotUndef to just Integer' do expect(nuoptint.normalize).to eq(tf.integer) end end end context 'Variant type' do let!(:overlapping_ints) { tf.variant(tf.range(10, 20), tf.range(18, 28)) } let!(:adjacent_ints) { tf.variant(tf.range(10, 20), tf.range(8, 9)) } let!(:mix_ints) { tf.variant(overlapping_ints, adjacent_ints) } let!(:overlapping_floats) { tf.variant(tf.float_range(10.0, 20.0), tf.float_range(18.0, 28.0)) } let!(:enums) { tf.variant(tf.enum('a', 'b'), tf.enum('b', 'c')) } let!(:enums_s_is) { tf.variant(tf.enum('a', 'b'), tf.enum('b', 'c', true)) } let!(:enums_is_is) { tf.variant(tf.enum('A', 'b', true), tf.enum('B', 'c', true)) } let!(:patterns) { tf.variant(tf.pattern('a', 'b'), tf.pattern('b', 'c')) } let!(:with_undef) { tf.variant(tf.undef, tf.range(1,10)) } let!(:all_optional) { tf.variant(tf.optional(tf.range(1,10)), tf.optional(tf.range(11,20))) } let!(:groups) { tf.variant(mix_ints, overlapping_floats, enums, patterns, with_undef, all_optional) } context 'when normalizing contained types that' do it 'are overlapping ints, the result is a range' do expect(overlapping_ints.normalize).to eq(tf.range(10, 28)) end it 'are adjacent ints, the result is a range' do expect(adjacent_ints.normalize).to eq(tf.range(8, 20)) end it 'are mixed variants with adjacent and overlapping ints, the result is a range' do expect(mix_ints.normalize).to eq(tf.range(8, 28)) end it 'are overlapping floats, the result is a float range' do expect(overlapping_floats.normalize).to eq(tf.float_range(10.0, 28.0)) end it 'are enums, the result is an enum' do expect(enums.normalize).to eq(tf.enum('a', 'b', 'c')) end it 'are case sensitive versus case insensitive enums, does not merge the enums' do expect(enums_s_is.normalize).to eq(enums_s_is) end it 'are case insensitive enums, result is case insensitive and unique irrespective of case' do expect(enums_is_is.normalize).to eq(tf.enum('a', 'b', 'c', true)) end it 'are patterns, the result is a pattern' do expect(patterns.normalize).to eq(tf.pattern('a', 'b', 'c')) end it 'contains an Undef, the result is Optional' do expect(with_undef.normalize).to eq(tf.optional(tf.range(1,10))) end it 'are all Optional, the result is an Optional with normalized type' do expect(all_optional.normalize).to eq(tf.optional(tf.range(1,20))) end it 'can be normalized in groups, the result is a Variant containing the resulting normalizations' do expect(groups.normalize).to eq(tf.optional( tf.variant( tf.range(1, 28), tf.float_range(10.0, 28.0), tf.enum('a', 'b', 'c'), tf.pattern('a', 'b', 'c')))) end end context 'when generalizing' do it 'will generalize and compact contained types' do expect(tf.variant(tf.string(tf.range(3,3)), tf.string(tf.range(5,5))).generalize).to eq(tf.variant(tf.string)) end end end context 'Runtime type' do it 'can be created with a runtime and a runtime type name' do expect(tf.runtime('ruby', 'Hash').to_s).to eq("Runtime[ruby, 'Hash']") end it 'can be created with a runtime and, puppet name pattern, and runtime replacement' do expect(tf.runtime('ruby', [/^MyPackage::(.*)$/, 'MyModule::\1']).to_s).to eq("Runtime[ruby, [/^MyPackage::(.*)$/, 'MyModule::\\1']]") end it 'will map a Puppet name to a runtime type' do t = tf.runtime('ruby', [/^MyPackage::(.*)$/, 'MyModule::\1']) expect(t.from_puppet_name('MyPackage::MyType').to_s).to eq("Runtime[ruby, 'MyModule::MyType']") end it 'with parameters is assignable to the default Runtime type' do code = <<-CODE notice(Runtime[ruby, 'Symbol'] < Runtime) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'with parameters is not assignable from the default Runtime type' do code = <<-CODE notice(Runtime < Runtime[ruby, 'Symbol']) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'default is assignable to itself' do code = <<-CODE notice(Runtime < Runtime) notice(Runtime <= Runtime) CODE expect(eval_and_collect_notices(code)).to eq(['false', 'true']) end end context 'Type aliases' do it 'will resolve nested objects using self recursion' do code = <<-CODE type Tree = Hash[String,Variant[String,Tree]] notice({a => {b => {c => d}}} =~ Tree) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'will find mismatches using self recursion' do code = <<-CODE type Tree = Hash[String,Variant[String,Tree]] notice({a => {b => {c => 1}}} =~ Tree) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'will not allow an alias chain to only contain aliases' do code = <<-CODE type Foo = Bar type Fee = Foo type Bar = Fee notice(0 =~ Bar) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Type alias 'Bar' cannot be resolved to a real type/) end it 'will not allow an alias chain that contains nothing but aliases and variants' do code = <<-CODE type Foo = Bar type Fee = Foo type Bar = Variant[Fee,Foo] notice(0 =~ Bar) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Type alias 'Bar' cannot be resolved to a real type/) end it 'will not allow an alias to directly reference itself' do code = <<-CODE type Foo = Foo notice(0 =~ Foo) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Type alias 'Foo' cannot be resolved to a real type/) end it 'will allow an alias to directly reference itself in a variant with other types' do code = <<-CODE type Foo = Variant[Foo,String] notice(a =~ Foo) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'will allow an alias where a variant references an alias with a variant that references itself' do code = <<-CODE type X = Variant[Y, Integer] type Y = Variant[X, String] notice(X >= X) notice(X >= Y) notice(Y >= X) CODE expect(eval_and_collect_notices(code)).to eq(['true','true','true']) end it 'will detect a mismatch in an alias that directly references itself in a variant with other types' do code = <<-CODE type Foo = Variant[Foo,String] notice(3 =~ Foo) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'will normalize a Variant containing a self reference so that the self reference is removed' do code = <<-CODE type Foo = Variant[Foo,String,Integer] assert_type(Foo, /x/) CODE expect { eval_and_collect_notices(code) }.to raise_error(/expects a Foo = Variant\[String, Integer\] value, got Regexp/) end it 'will handle a scalar correctly in combinations of nested aliased variants' do code = <<-CODE type Bar = Variant[Foo,Integer] type Foo = Variant[Bar,String] notice(a =~ Foo) notice(1 =~ Foo) notice(/x/ =~ Foo) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false']) end it 'will handle a non scalar correctly in combinations of nested aliased array with nested variants' do code = <<-CODE type Bar = Variant[Foo,Integer] type Foo = Array[Variant[Bar,String]] notice([a] =~ Foo) notice([1] =~ Foo) notice([/x/] =~ Foo) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false']) end it 'will handle a non scalar correctly in combinations of nested aliased variants with array' do code = <<-CODE type Bar = Variant[Foo,Array[Integer]] type Foo = Variant[Bar,Array[String]] notice([a] =~ Foo) notice([1] =~ Foo) notice([/x/] =~ Foo) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false']) end it 'will not allow dynamic constructs in type definition' do code = <<-CODE type Foo = Enum[$facts[os][family]] notice(Foo) CODE expect{ eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /The expression <\$facts\[os\]\[family\]> is not a valid type specification/) end end context 'Type mappings' do it 'can register a singe type mapping' do source = <<-CODE type MyModule::ImplementationRegistry = Object[{}] type Runtime[ruby, 'Puppet::Pops::Types::ImplementationRegistry'] = MyModule::ImplementationRegistry notice(true) CODE collect_notices(source) do |compiler| compiler.compile do |catalog| type = Loaders.implementation_registry.type_for_module(ImplementationRegistry) expect(type).to be_a(PObjectType) expect(type.name).to eql('MyModule::ImplementationRegistry') catalog end end end it 'can register a regexp based mapping' do source = <<-CODE type MyModule::TypeMismatchDescriber = Object[{}] type Runtime[ruby, [/^Puppet::Pops::Types::(\\w+)$/, 'MyModule::\\1']] = [/^MyModule::(\\w+)$/, 'Puppet::Pops::Types::\\1'] notice(true) CODE collect_notices(source) do |compiler| compiler.compile do |catalog| type = Loaders.implementation_registry.type_for_module(TypeMismatchDescriber) expect(type).to be_a(PObjectType) expect(type.name).to eql('MyModule::TypeMismatchDescriber') catalog end end end it 'a type mapping affects type inference' do source = <<-CODE type MyModule::ImplementationRegistry = Object[{}] type Runtime[ruby, 'Puppet::Pops::Types::ImplementationRegistry'] = MyModule::ImplementationRegistry notice(true) CODE collect_notices(source) do |compiler| compiler.compile do |catalog| type = TypeCalculator.singleton.infer(Loaders.implementation_registry) expect(type).to be_a(PObjectType) expect(type.name).to eql('MyModule::ImplementationRegistry') catalog end end end end context 'When attempting to redefine a built in type' do it 'such as Integer, an error is raised' do code = <<-CODE type Integer = String notice 'hello' =~ Integer CODE expect{ eval_and_collect_notices(code) }.to raise_error(/Attempt to redefine entity 'http:\/\/puppet\.com\/2016\.1\/runtime\/type\/integer'. Originally set by Puppet-Type-System\/Static-Loader/) end end context 'instantiation via new_function is supported by' do let(:loader) { Loader::BaseLoader.new(nil, "types_unit_test_loader") } it 'Integer' do func_class = tf.integer.new_function expect(func_class).to be_a(Class) expect(func_class.superclass).to be(Puppet::Functions::Function) end it 'Optional[Integer]' do func_class = tf.optional(tf.integer).new_function expect(func_class).to be_a(Class) expect(func_class.superclass).to be(Puppet::Functions::Function) end it 'Regexp' do func_class = tf.regexp.new_function expect(func_class).to be_a(Class) expect(func_class.superclass).to be(Puppet::Functions::Function) end end context 'instantiation via new_function is not supported by' do let(:loader) { Loader::BaseLoader.new(nil, "types_unit_test_loader") } it 'Any, Scalar, Collection' do [tf.any, tf.scalar, tf.collection ].each do |t| expect { t.new_function }.to raise_error(ArgumentError, /Creation of new instance of type '#{t.to_s}' is not supported/) end end end context 'instantiation via ruby create function' do before(:each) do Puppet.push_context(:loaders => Loaders.new(Puppet::Node::Environment.create(:testing, []))) do end end after(:each) do Puppet.pop_context() end it 'is supported by Integer' do int = tf.integer.create('32') expect(int).to eq(32) end it 'is supported by Regexp' do rx = tf.regexp.create('[a-z]+') expect(rx).to eq(/[a-z]+/) end it 'is supported by Optional[Integer]' do int = tf.optional(tf.integer).create('32') expect(int).to eq(32) end it 'is not supported by Any, Scalar, Collection' do [tf.any, tf.scalar, tf.collection ].each do |t| expect { t.create }.to raise_error(ArgumentError, /Creation of new instance of type '#{t.to_s}' is not supported/) end end end context 'creation of parameterized type via ruby create function on class' do before(:each) do Puppet.push_context(:loaders => Loaders.new(Puppet::Node::Environment.create(:testing, []))) do end end after(:each) do Puppet.pop_context() end it 'is supported by Integer' do int_type = tf.integer.class.create(0, 32) expect(int_type).to eq(tf.range(0, 32)) end it 'is supported by Regexp' do rx_type = tf.regexp.class.create('[a-z]+') expect(rx_type).to eq(tf.regexp(/[a-z]+/)) end end context 'backward compatibility' do it 'PTypeType can be accessed from PType' do # should appoint the exact same instance expect(PType).to equal(PTypeType) end it 'PClassType can be accessed from PHostClassType' do # should appoint the exact same instance expect(PHostClassType).to equal(PClassType) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_type_set_type_spec.rb
spec/unit/pops/types/p_type_set_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'The TypeSet Type' do include PuppetSpec::Compiler let(:parser) { TypeParser.singleton } let(:pp_parser) { Parser::EvaluatingParser.new } let(:env) { Puppet::Node::Environment.create('test', []) } let(:loaders) { Loaders.new(env) } let(:loader) { loaders.find_loader(nil) } def type_set_t(name, body_string, name_authority) init_literal_hash = pp_parser.parse_string("{#{body_string}}").body typeset = PTypeSetType.new(name, init_literal_hash, name_authority) loader.set_entry(Loader::TypedName.new(:type, name, name_authority), typeset) typeset end # Creates and parses an alias type declaration of a TypeSet, e.g. # ``` # type <name> = TypeSet[{<body_string>}] # ``` # The declaration implies the name authority {Pcore::RUNTIME_NAME_AUTHORITY} # # @param name [String] the name of the type set # @param body [String] the body (initialization hash) of the type-set # @return [PTypeSetType] the created type set def parse_type_set(name, body, name_authority = Pcore::RUNTIME_NAME_AUTHORITY) type_set_t(name, body, name_authority) parser.parse(name, loader) end context 'when validating the initialization hash' do context 'it will allow that it' do it 'has no types and no references' do ts = <<-OBJECT version => '1.0.0', pcore_version => '1.0.0', OBJECT expect { parse_type_set('MySet', ts) }.not_to raise_error end it 'has only references' do parse_type_set('FirstSet', <<-OBJECT) version => '1.0.0', pcore_version => '1.0.0', types => { Car => Object[{}] } OBJECT expect { parse_type_set('SecondSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', references => { First => { name => 'FirstSet', version_range => '1.x' } } OBJECT end it 'has multiple references to equally named TypeSets using different name authorities' do parse_type_set('FirstSet', <<-OBJECT, 'http://example.com/ns1') version => '1.0.0', pcore_version => '1.0.0', types => { Car => Object[{}] } OBJECT parse_type_set('FirstSet', <<-OBJECT, 'http://example.com/ns2') version => '1.0.0', pcore_version => '1.0.0', types => { Car => Object[{}] } OBJECT expect { parse_type_set('SecondSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', references => { First_1 => { name_authority => 'http://example.com/ns1', name => 'FirstSet', version_range => '1.x' }, First_2 => { name => 'FirstSet', name_authority => 'http://example.com/ns2', version_range => '1.x' } } OBJECT end end context 'it raises an error when' do it 'pcore_version is missing' do ts = <<-OBJECT version => '1.0.0', OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /expects a value for key 'pcore_version'/) end it 'the version is an invalid semantic version' do ts = <<-OBJECT version => '1.x', pcore_version => '1.0.0', OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(SemanticPuppet::Version::ValidationFailure) end it 'the pcore_version is an invalid semantic version' do ts = <<-OBJECT version => '1.0.0', pcore_version => '1.x', OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(SemanticPuppet::Version::ValidationFailure) end it 'the pcore_version is outside of the range of that is parsable by this runtime' do ts = <<-OBJECT version => '1.0.0', pcore_version => '2.0.0', OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError, /The pcore version for TypeSet 'MySet' is not understood by this runtime. Expected range 1\.x, got 2\.0\.0/) end it 'the name authority is an invalid URI' do ts = <<-OBJECT version => '1.0.0', pcore_version => '1.0.0', name_authority => 'not a valid URI' OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'name_authority' expects a match for Pattern\[.*\], got 'not a valid URI'/m) end context 'the types map' do it 'is empty' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', types => {} OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'types' expects size to be at least 1, got 0/) end it 'is not a map' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', types => [] OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(Puppet::Error, /entry 'types' expects a Hash value, got Array/) end it 'contains values that are not types' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', types => { Car => 'brum' } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(Puppet::Error, /The expression <'brum'> is not a valid type specification/) end it 'contains keys that are not SimpleNames' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', types => { car => Integer } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /key of entry 'car' expects a match for Pattern\[\/\\A\[A-Z\]\\w\*\\z\/\], got 'car'/) end end context 'the references hash' do it 'is empty' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => {} OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'references' expects size to be at least 1, got 0/) end it 'is not a hash' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => [] OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'references' expects a Hash value, got Array/) end it 'contains something other than reference initialization maps' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => {Ref => 2} OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'references' entry 'Ref' expects a Struct value, got Integer/) end it 'contains several initialization that refers to the same TypeSet' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => { A => { name => 'Vehicle::Cars', version_range => '1.x' }, V => { name => 'Vehicle::Cars', version_range => '1.x' }, } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError, /references TypeSet 'http:\/\/puppet\.com\/2016\.1\/runtime\/Vehicle::Cars' more than once using overlapping version ranges/) end it 'contains an initialization maps with an alias that collides with a type name' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', types => { Car => Object[{}] }, references => { Car => { name => 'Vehicle::Car', version_range => '1.x' } } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError, /references a TypeSet using alias 'Car'. The alias collides with the name of a declared type/) end context 'contains an initialization map that' do it 'has no version range' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => { Ref => { name => 'X' } } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'references' entry 'Ref' expects a value for key 'version_range'/) end it 'has no name' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => { Ref => { version_range => '1.x' } } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'references' entry 'Ref' expects a value for key 'name'/) end it 'has a name that is not a QRef' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => { Ref => { name => 'cars', version_range => '1.x' } } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'references' entry 'Ref' entry 'name' expects a match for Pattern\[\/\\A\[A-Z\]\\w\*\(\?:::\[A-Z\]\\w\*\)\*\\z\/\], got 'cars'/) end it 'has a version_range that is not a valid SemVer range' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => { Ref => { name => 'Cars', version_range => 'N' } } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError, /Unparsable version range: "N"/) end it 'has an alias that is not a SimpleName' do ts = <<-OBJECT pcore_version => '1.0.0', version => '1.0.0', references => { 'cars' => { name => 'X', version_range => '1.x' } } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, /entry 'references' key of entry 'cars' expects a match for Pattern\[\/\\A\[A-Z\]\\w\*\\z\/\], got 'cars'/) end end end end end context 'when declaring types' do it 'can declare a type Alias' do expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', types => { PositiveInt => Integer[0, default] } OBJECT end it 'can declare an Object type using Object[{}]' do expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', types => { Complex => Object[{}] } OBJECT end it 'can declare an Object type that references other types in the same set' do expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', types => { Real => Float, Complex => Object[{ attributes => { real => Real, imaginary => Real } }] } OBJECT end it 'can declare an alias that references itself' do expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', types => { Tree => Hash[String,Variant[String,Tree]] } OBJECT end it 'can declare a type that references types in another type set' do parse_type_set('Vehicles', <<-OBJECT) version => '1.0.0', pcore_version => '1.0.0', types => { Car => Object[{}], Bicycle => Object[{}] } OBJECT expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', types => { Transports => Variant[Vecs::Car,Vecs::Bicycle] }, references => { Vecs => { name => 'Vehicles', version_range => '1.x' } } OBJECT end it 'can declare a type that references types in a type set referenced by another type set' do parse_type_set('Vehicles', <<-OBJECT) version => '1.0.0', pcore_version => '1.0.0', types => { Car => Object[{}], Bicycle => Object[{}] } OBJECT parse_type_set('Transports', <<-OBJECT) version => '1.0.0', pcore_version => '1.0.0', types => { Transports => Variant[Vecs::Car,Vecs::Bicycle] }, references => { Vecs => { name => 'Vehicles', version_range => '1.x' } } OBJECT expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error version => '1.0.0', pcore_version => '1.0.0', types => { MotorPowered => Variant[T::Vecs::Car], Pedaled => Variant[T::Vecs::Bicycle], All => T::Transports }, references => { T => { name => 'Transports', version_range => '1.x' } } OBJECT end context 'allows bracket-less form' do let(:logs) { [] } let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } let(:node) { Puppet::Node.new('example.com') } let(:compiler) { Puppet::Parser::Compiler.new(node) } def compile(code) Puppet[:code] = code Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) { compiler.compile } end it 'on the TypeSet declaration itself' do compile(<<-PUPPET) type TS = TypeSet { pcore_version => '1.0.0' } notice(TS =~ Type[TypeSet]) PUPPET expect(warnings).to be_empty expect(notices).to eql(['true']) end it 'without prefix on declared types (implies Object)' do compile(<<-PUPPET) type TS = TypeSet { pcore_version => '1.0.0', types => { MyObject => { attributes => { a => Integer} } } } notice(TS =~ Type[TypeSet]) notice(TS::MyObject =~ Type) notice(TS::MyObject(3)) PUPPET expect(warnings).to be_empty expect(notices).to eql(['true', 'true', "TS::MyObject({'a' => 3})"]) end it "prefixed with QREF 'Object' on declared types" do compile(<<-PUPPET) type TS = TypeSet { pcore_version => '1.0.0', types => { MyObject => Object { attributes => { a => Integer} } } } notice(TS =~ Type[TypeSet]) notice(TS::MyObject =~ Type) notice(TS::MyObject(3)) PUPPET expect(warnings).to be_empty expect(notices).to eql(['true', 'true', "TS::MyObject({'a' => 3})"]) end it 'prefixed with QREF to declare parent on declared types' do compile(<<-PUPPET) type TS = TypeSet { pcore_version => '1.0.0', types => { MyObject => { attributes => { a => String }}, MySecondObject => MyObject { attributes => { b => String }} } } notice(TS =~ Type[TypeSet]) notice(TS::MySecondObject =~ Type) notice(TS::MySecondObject < TS::MyObject) notice(TS::MyObject('hi')) notice(TS::MySecondObject('hello', 'world')) PUPPET expect(warnings).to be_empty expect(notices).to eql( ['true', 'true', 'true', "TS::MyObject({'a' => 'hi'})", "TS::MySecondObject({'a' => 'hello', 'b' => 'world'})"]) end it 'and warns when parent is specified both before and inside the hash if strict == warning' do Puppet[:strict] = 'warning' compile(<<-PUPPET) type TS = TypeSet { pcore_version => '1.0.0', types => { MyObject => { attributes => { a => String }}, MySecondObject => MyObject { parent => MyObject, attributes => { b => String }} } } notice(TS =~ Type[TypeSet]) PUPPET expect(warnings).to eql(["The key 'parent' is declared more than once"]) expect(notices).to eql(['true']) end it 'and errors when parent is specified both before and inside the hash if strict == error' do Puppet[:strict] = 'error' expect{ compile(<<-PUPPET) }.to raise_error(/The key 'parent' is declared more than once/) type TS = TypeSet { pcore_version => '1.0.0', types => { MyObject => { attributes => { a => String }}, MySecondObject => MyObject { parent => MyObject, attributes => { b => String }} } } notice(TS =~ Type[TypeSet]) PUPPET end end end it '#name_for method reports the name of deeply nested type correctly' do tv = parse_type_set('Vehicles', <<-OBJECT) version => '1.0.0', pcore_version => '1.0.0', types => { Car => Object[{}] } OBJECT parse_type_set('Transports', <<-OBJECT) version => '1.0.0', pcore_version => '1.0.0', references => { Vecs => { name => 'Vehicles', version_range => '1.x' } } OBJECT ts = parse_type_set('TheSet', <<-OBJECT) version => '1.0.0', pcore_version => '1.0.0', references => { T => { name => 'Transports', version_range => '1.x' } } OBJECT expect(ts.name_for(tv['Car'], nil)).to eql('T::Vecs::Car') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/type_parser_spec.rb
spec/unit/pops/types/type_parser_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops module Types describe TypeParser do extend RSpec::Matchers::DSL let(:parser) { TypeParser.singleton } let(:types) { TypeFactory } it "rejects a puppet expression" do expect { parser.parse("1 + 1") }.to raise_error(Puppet::ParseError, /The expression <1 \+ 1> is not a valid type specification/) end it "rejects a empty type specification" do expect { parser.parse("") }.to raise_error(Puppet::ParseError, /The expression <> is not a valid type specification/) end it "rejects an invalid type simple type" do expect { parser.parse("notAType") }.to raise_error(Puppet::ParseError, /The expression <notAType> is not a valid type specification/) end it "rejects an unknown parameterized type" do expect { parser.parse("notAType[Integer]") }.to raise_error(Puppet::ParseError, /The expression <notAType\[Integer\]> is not a valid type specification/) end it "rejects an unknown type parameter" do expect { parser.parse("Array[notAType]") }.to raise_error(Puppet::ParseError, /The expression <Array\[notAType\]> is not a valid type specification/) end it "rejects an unknown type parameter in a variant" do expect { parser.parse("Variant[Integer,'not a type']") }.to raise_error(Puppet::ParseError, /The expression <Variant\[Integer,'not a type'\]> is not a valid type specification/) end [ 'Any', 'Data', 'CatalogEntry', 'Scalar', 'Undef', 'Numeric', 'Default' ].each do |name| it "does not support parameterizing unparameterized type <#{name}>" do expect { parser.parse("#{name}[Integer]") }.to raise_unparameterized_error_for(name) end end it "parses a simple, unparameterized type into the type object" do expect(the_type_parsed_from(types.any)).to be_the_type(types.any) expect(the_type_parsed_from(types.integer)).to be_the_type(types.integer) expect(the_type_parsed_from(types.float)).to be_the_type(types.float) expect(the_type_parsed_from(types.string)).to be_the_type(types.string) expect(the_type_parsed_from(types.boolean)).to be_the_type(types.boolean) expect(the_type_parsed_from(types.pattern)).to be_the_type(types.pattern) expect(the_type_parsed_from(types.data)).to be_the_type(types.data) expect(the_type_parsed_from(types.catalog_entry)).to be_the_type(types.catalog_entry) expect(the_type_parsed_from(types.collection)).to be_the_type(types.collection) expect(the_type_parsed_from(types.tuple)).to be_the_type(types.tuple) expect(the_type_parsed_from(types.struct)).to be_the_type(types.struct) expect(the_type_parsed_from(types.optional)).to be_the_type(types.optional) expect(the_type_parsed_from(types.default)).to be_the_type(types.default) end it "interprets an unparameterized Array as an Array of Any" do expect(parser.parse("Array")).to be_the_type(types.array_of_any) end it "interprets an unparameterized Hash as a Hash of Any, Any" do expect(parser.parse("Hash")).to be_the_type(types.hash_of_any) end it "interprets a parameterized Array[0, 0] as an empty hash with no key and value type" do expect(parser.parse("Array[0, 0]")).to be_the_type(types.array_of(types.default, types.range(0, 0))) end it "interprets a parameterized Hash[0, 0] as an empty hash with no key and value type" do expect(parser.parse("Hash[0, 0]")).to be_the_type(types.hash_of(types.default, types.default, types.range(0, 0))) end it "interprets a parameterized Hash[t] as a Hash of Scalar to t" do expect(parser.parse("Hash[Scalar, Integer]")).to be_the_type(types.hash_of(types.integer)) end it 'interprets an Boolean with a true parameter to represent boolean true' do expect(parser.parse('Boolean[true]')).to be_the_type(types.boolean(true)) end it 'interprets an Boolean with a false parameter to represent boolean false' do expect(parser.parse('Boolean[false]')).to be_the_type(types.boolean(false)) end it 'does not accept non-boolean parameters' do expect{parser.parse('Boolean["false"]')}.to raise_error(/Boolean parameter must be true or false/) end it 'interprets an Integer with one parameter to have unbounded upper range' do expect(parser.parse('Integer[0]')).to eq(parser.parse('Integer[0,default]')) end it 'interprets a Float with one parameter to have unbounded upper range' do expect(parser.parse('Float[0]')).to eq(parser.parse('Float[0,default]')) end it "parses a parameterized type into the type object" do parameterized_array = types.array_of(types.integer) parameterized_hash = types.hash_of(types.integer, types.boolean) expect(the_type_parsed_from(parameterized_array)).to be_the_type(parameterized_array) expect(the_type_parsed_from(parameterized_hash)).to be_the_type(parameterized_hash) end it "parses a size constrained collection using capped range" do parameterized_array = types.array_of(types.integer, types.range(1,2)) parameterized_hash = types.hash_of(types.integer, types.boolean, types.range(1,2)) expect(the_type_parsed_from(parameterized_array)).to be_the_type(parameterized_array) expect(the_type_parsed_from(parameterized_hash)).to be_the_type(parameterized_hash) end it "parses a size constrained collection with open range" do parameterized_array = types.array_of(types.integer, types.range(1, :default)) parameterized_hash = types.hash_of(types.integer, types.boolean, types.range(1, :default)) expect(the_type_parsed_from(parameterized_array)).to be_the_type(parameterized_array) expect(the_type_parsed_from(parameterized_hash)).to be_the_type(parameterized_hash) end it "parses optional type" do opt_t = types.optional(Integer) expect(the_type_parsed_from(opt_t)).to be_the_type(opt_t) end it "parses timespan type" do timespan_t = types.timespan expect(the_type_parsed_from(timespan_t)).to be_the_type(timespan_t) end it "parses timestamp type" do timestamp_t = types.timestamp expect(the_type_parsed_from(timestamp_t)).to be_the_type(timestamp_t) end it "parses tuple type" do tuple_t = types.tuple([Integer, String]) expect(the_type_parsed_from(tuple_t)).to be_the_type(tuple_t) end it "parses tuple type with occurrence constraint" do tuple_t = types.tuple([Integer, String], types.range(2, 5)) expect(the_type_parsed_from(tuple_t)).to be_the_type(tuple_t) end it "parses struct type" do struct_t = types.struct({'a'=>Integer, 'b'=>String}) expect(the_type_parsed_from(struct_t)).to be_the_type(struct_t) end describe "handles parsing of patterns and regexp" do { 'Pattern[/([a-z]+)([1-9]+)/]' => [:pattern, [/([a-z]+)([1-9]+)/]], 'Pattern["([a-z]+)([1-9]+)"]' => [:pattern, [/([a-z]+)([1-9]+)/]], 'Regexp[/([a-z]+)([1-9]+)/]' => [:regexp, [/([a-z]+)([1-9]+)/]], 'Pattern[/x9/, /([a-z]+)([1-9]+)/]' => [:pattern, [/x9/, /([a-z]+)([1-9]+)/]], }.each do |source, type| it "such that the source '#{source}' yields the type #{type.to_s}" do expect(parser.parse(source)).to be_the_type(TypeFactory.send(type[0], *type[1])) end end end it "rejects an collection spec with the wrong number of parameters" do expect { parser.parse("Array[Integer, 1,2,3]") }.to raise_the_parameter_error("Array", "1 to 3", 4) expect { parser.parse("Hash[Integer, Integer, 1,2,3]") }.to raise_the_parameter_error("Hash", "2 to 4", 5) end context 'with scope context and loader' do let!(:scope) { {} } let(:loader) { double } before :each do expect(Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(loader) end it 'interprets anything that is not found by the loader to be a type reference' do expect(loader).to receive(:load).with(:type, 'nonesuch').and_return(nil) expect(parser.parse('Nonesuch', scope)).to be_the_type(types.type_reference('Nonesuch')) end it 'interprets anything that is found by the loader to be what the loader found' do expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File')) expect(parser.parse('File', scope)).to be_the_type(types.resource('File')) end it "parses a resource type with title" do expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File')) expect(parser.parse("File['/tmp/foo']", scope)).to be_the_type(types.resource('file', '/tmp/foo')) end it "parses a resource type using 'Resource[type]' form" do expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File')) expect(parser.parse("Resource[File]", scope)).to be_the_type(types.resource('file')) end it "parses a resource type with title using 'Resource[type, title]'" do expect(loader).to receive(:load).with(:type, 'file').and_return(nil) expect(parser.parse("Resource[File, '/tmp/foo']", scope)).to be_the_type(types.resource('file', '/tmp/foo')) end it "parses a resource type with title using 'Resource[Type[title]]'" do expect(loader).to receive(:load).with(:type, 'nonesuch').and_return(nil) expect(parser.parse("Resource[Nonesuch['fife']]", scope)).to be_the_type(types.resource('nonesuch', 'fife')) end end context 'with loader context' do let(:environment) { Puppet::Node::Environment.create(:testing, []) } let(:loader) { Puppet::Pops::Loader::BaseLoader.new(nil, "type_parser_unit_test_loader", environment) } it 'interprets anything that is not found by the loader to be a type reference' do expect(loader).to receive(:load).with(:type, 'nonesuch').and_return(nil) expect(parser.parse('Nonesuch', loader)).to be_the_type(types.type_reference('Nonesuch')) end it 'interprets anything that is found by the loader to be what the loader found' do expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File')) expect(parser.parse('File', loader)).to be_the_type(types.resource('file')) end it "parses a resource type with title" do expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File')) expect(parser.parse("File['/tmp/foo']", loader)).to be_the_type(types.resource('file', '/tmp/foo')) end it "parses a resource type using 'Resource[type]' form" do expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File')) expect(parser.parse("Resource[File]", loader)).to be_the_type(types.resource('file')) end it "parses a resource type with title using 'Resource[type, title]'" do expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File')) expect(parser.parse("Resource[File, '/tmp/foo']", loader)).to be_the_type(types.resource('file', '/tmp/foo')) end end context 'without a scope' do it "interprets anything that is not a built in type to be a type reference" do expect(parser.parse('TestType')).to eq(types.type_reference('TestType')) end it "interprets anything that is not a built in type with parameterers to be type reference with parameters" do expect(parser.parse("TestType['/tmp/foo']")).to eq(types.type_reference("TestType['/tmp/foo']")) end end it "parses a host class type" do expect(parser.parse("Class")).to be_the_type(types.host_class()) end it "parses a parameterized host class type" do expect(parser.parse("Class[foo::bar]")).to be_the_type(types.host_class('foo::bar')) end it 'parses an integer range' do expect(parser.parse("Integer[1,2]")).to be_the_type(types.range(1,2)) end it 'parses a negative integer range' do expect(parser.parse("Integer[-3,-1]")).to be_the_type(types.range(-3,-1)) end it 'parses a float range' do expect(parser.parse("Float[1.0,2.0]")).to be_the_type(types.float_range(1.0,2.0)) end it 'parses a collection size range' do expect(parser.parse("Collection[1,2]")).to be_the_type(types.collection(types.range(1,2))) end it 'parses a timespan type' do expect(parser.parse("Timespan")).to be_the_type(types.timespan) end it 'parses a timespan type with a lower bound' do expect(parser.parse("Timespan[{hours => 3}]")).to be_the_type(types.timespan({'hours' => 3})) end it 'parses a timespan type with an upper bound' do expect(parser.parse("Timespan[default, {hours => 9}]")).to be_the_type(types.timespan(nil, {'hours' => 9})) end it 'parses a timespan type with both lower and upper bounds' do expect(parser.parse("Timespan[{hours => 3}, {hours => 9}]")).to be_the_type(types.timespan({'hours' => 3}, {'hours' => 9})) end it 'parses a timestamp type' do expect(parser.parse("Timestamp")).to be_the_type(types.timestamp) end it 'parses a timestamp type with a lower bound' do expect(parser.parse("Timestamp['2014-12-12T13:14:15 CET']")).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET')) end it 'parses a timestamp type with an upper bound' do expect(parser.parse("Timestamp[default, '2014-12-12T13:14:15 CET']")).to be_the_type(types.timestamp(nil, '2014-12-12T13:14:15 CET')) end it 'parses a timestamp type with both lower and upper bounds' do expect(parser.parse("Timestamp['2014-12-12T13:14:15 CET', '2016-08-23T17:50:00 CET']")).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET', '2016-08-23T17:50:00 CET')) end it 'parses a type type' do expect(parser.parse("Type[Integer]")).to be_the_type(types.type_type(types.integer)) end it 'parses a ruby type' do expect(parser.parse("Runtime[ruby, 'Integer']")).to be_the_type(types.ruby_type('Integer')) end it 'parses a callable type' do t = parser.parse("Callable") expect(t).to be_the_type(types.all_callables()) expect(t.return_type).to be_nil end it 'parses a parameterized callable type' do t = parser.parse("Callable[String, Integer]") expect(t).to be_the_type(types.callable(String, Integer)) expect(t.return_type).to be_nil end it 'parses a parameterized callable type with min/max' do t = parser.parse("Callable[String, Integer, 1, default]") expect(t).to be_the_type(types.callable(String, Integer, 1, :default)) expect(t.return_type).to be_nil end it 'parses a parameterized callable type with block' do t = parser.parse("Callable[String, Callable[Boolean]]") expect(t).to be_the_type(types.callable(String, types.callable(true))) expect(t.return_type).to be_nil end it 'parses a callable with no parameters and return type' do expect(parser.parse("Callable[[],Float]")).to be_the_type(types.callable([],Float)) end it 'parses a parameterized callable type with return type' do expect(parser.parse("Callable[[String, Integer],Float]")).to be_the_type(types.callable([String, Integer],Float)) end it 'parses a parameterized callable type with min/max and return type' do expect(parser.parse("Callable[[String, Integer, 1, default],Float]")).to be_the_type(types.callable([String, Integer, 1, :default], Float)) end it 'parses a parameterized callable type with block and return type' do expect(parser.parse("Callable[[String, Callable[Boolean]],Float]")).to be_the_type(types.callable([String, types.callable(true)], Float)) end it 'parses a parameterized callable type with 0 min/max' do t = parser.parse("Callable[0,0]") expect(t).to be_the_type(types.callable(0,0)) expect(t.param_types.types).to be_empty expect(t.return_type).to be_nil end it 'parses a parameterized callable type with 0 min/max and return_type' do t = parser.parse("Callable[[0,0],Float]") expect(t).to be_the_type(types.callable([0,0],Float)) expect(t.param_types.types).to be_empty expect(t.return_type).to be_the_type(types.float) end it 'parses a parameterized callable type with >0 min/max' do t = parser.parse("Callable[0,1]") expect(t).to be_the_type(types.callable(0,1)) # Contains a Unit type to indicate "called with what you accept" expect(t.param_types.types[0]).to be_the_type(PUnitType.new()) expect(t.return_type).to be_nil end it 'parses a parameterized callable type with >0 min/max and a return type' do t = parser.parse("Callable[[0,1],Float]") expect(t).to be_the_type(types.callable([0,1], Float)) # Contains a Unit type to indicate "called with what you accept" expect(t.param_types.types[0]).to be_the_type(PUnitType.new()) expect(t.return_type).to be_the_type(types.float) end it 'parses all known literals' do t = parser.parse('Nonesuch[{a=>undef,b=>true,c=>false,d=>default,e=>"string",f=>0,g=>1.0,h=>[1,2,3]}]') expect(t).to be_a(PTypeReferenceType) expect(t.type_string).to eql('Nonesuch[{a=>undef,b=>true,c=>false,d=>default,e=>"string",f=>0,g=>1.0,h=>[1,2,3]}]') end it 'parses a parameterized Enum using identifiers' do t = parser.parse('Enum[a, b]') expect(t).to be_a(PEnumType) expect(t.to_s).to eql("Enum['a', 'b']") end it 'parses a parameterized Enum using strings' do t = parser.parse("Enum['a', 'b']") expect(t).to be_a(PEnumType) expect(t.to_s).to eql("Enum['a', 'b']") end it 'rejects a parameterized Enum using type refs' do expect { parser.parse('Enum[A, B]') }.to raise_error(/Enum parameters must be identifiers or strings/) end it 'rejects a parameterized Enum using integers' do expect { parser.parse('Enum[1, 2]') }.to raise_error(/Enum parameters must be identifiers or strings/) end matcher :be_the_type do |type| calc = TypeCalculator.new match do |actual| calc.assignable?(actual, type) && calc.assignable?(type, actual) end failure_message do |actual| "expected #{calc.string(type)}, but was #{calc.string(actual)}" end end def raise_the_parameter_error(type, required, given) raise_error(Puppet::ParseError, /#{type} requires #{required}, #{given} provided/) end def raise_type_error_for(type_name) raise_error(Puppet::ParseError, /Unknown type <#{type_name}>/) end def raise_unparameterized_error_for(type_name) raise_error(Puppet::ParseError, /Not a parameterized type <#{type_name}>/) end def the_type_parsed_from(type) parser.parse(the_type_spec_for(type)) end def the_type_spec_for(type) TypeFormatter.string(type) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/type_mismatch_describer_spec.rb
spec/unit/pops/types/type_mismatch_describer_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' require 'puppet_spec/files' require 'puppet/loaders' module Puppet::Pops module Types describe 'the type mismatch describer' do include PuppetSpec::Compiler, PuppetSpec::Files context 'with deferred functions' do let(:env_name) { 'spec' } let(:code_dir) { Puppet[:environmentpath] } let(:env_dir) { File.join(code_dir, env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_code_dir, env_name, 'modules')]) } let(:node) { Puppet::Node.new('fooname', environment: env) } let(:populated_code_dir) do dir_contained_in(code_dir, env_name => env_content) PuppetSpec::Files.record_tmp(env_dir) code_dir end let(:env_content) { { 'lib' => { 'puppet' => { 'functions' => { 'string_return.rb' => <<-RUBY.unindent, Puppet::Functions.create_function(:string_return) do dispatch :string_return do param 'String', :arg1 return_type 'String' end def string_return(arg1) arg1 end end RUBY 'variant_return.rb' => <<-RUBY.unindent, Puppet::Functions.create_function(:variant_return) do dispatch :variant_return do param 'String', :arg1 return_type 'Variant[Integer,Float]' end def variant_return(arg1) arg1 end end RUBY 'no_return.rb' => <<-RUBY.unindent, Puppet::Functions.create_function(:no_return) do dispatch :no_return do param 'String', :arg1 end def variant_return(arg1) arg1 end end RUBY } } } } } before(:each) do Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env)) end after(:each) do Puppet.pop_context end it 'will compile when the parameter type matches the function return_type' do code = <<-CODE $d = Deferred("string_return", ['/a/non/existing/path']) class testclass(String $classparam) { } class { 'testclass': classparam => $d } CODE expect { eval_and_collect_notices(code, node) }.to_not raise_error end it "will compile when a Variant parameter's types matches the return type" do code = <<-CODE $d = Deferred("string_return", ['/a/non/existing/path']) class testclass(Variant[String, Float] $classparam) { } class { 'testclass': classparam => $d } CODE expect { eval_and_collect_notices(code, node) }.to_not raise_error end it "will compile with a union of a Variant parameters' types and Variant return types" do code = <<-CODE $d = Deferred("variant_return", ['/a/non/existing/path']) class testclass(Variant[Any,Float] $classparam) { } class { 'testclass': classparam => $d } CODE expect { eval_and_collect_notices(code, node) }.to_not raise_error end it 'will warn when there is no defined return_type for the function definition' do code = <<-CODE $d = Deferred("no_return", ['/a/non/existing/path']) class testclass(Variant[String,Boolean] $classparam) { } class { 'testclass': classparam => $d } CODE expect(Puppet).to receive(:warn_once).with(anything, anything, /.+function no_return has no return_type/).at_least(:once) expect { eval_and_collect_notices(code, node) }.to_not raise_error end it 'will report a mismatch between a deferred function return type and class parameter value' do code = <<-CODE $d = Deferred("string_return", ['/a/non/existing/path']) class testclass(Integer $classparam) { } class { 'testclass': classparam => $d } CODE expect { eval_and_collect_notices(code, node) }.to raise_error(Puppet::Error, /.+'classparam' expects an Integer value, got String/) end it 'will report an argument error when no matching arity is found' do code = <<-CODE $d = Deferred("string_return", ['/a/non/existing/path', 'second-invalid-arg']) class testclass(Integer $classparam) { } class { 'testclass': classparam => $d } CODE expect { eval_and_collect_notices(code,node) }.to raise_error(Puppet::Error, /.+ No matching arity found for string_return/) end it 'will error with no matching Variant class parameters and return_type' do code = <<-CODE $d = Deferred("string_return", ['/a/non/existing/path']) class testclass(Variant[Integer,Float] $classparam) { } class { 'testclass': classparam => $d } CODE expect { eval_and_collect_notices(code,node) }.to raise_error(Puppet::Error, /.+'classparam' expects a value of type Integer or Float, got String/) end # This test exposes a shortcoming in the #message function for Puppet::Pops::Type::TypeMismatch # where the `actual` is not introspected for the list of Variant types, so the error message # shows that the list of expected types does not match Variant, instead of a list of actual types. it 'will error with no matching Variant class parameters and Variant return_type' do code = <<-CODE $d = Deferred("variant_return", ['/a/non/existing/path']) class testclass(Variant[String,Boolean] $classparam) { } class { 'testclass': classparam => $d } CODE expect { eval_and_collect_notices(code, node) }.to raise_error(Puppet::Error, /.+'classparam' expects a value of type String or Boolean, got Variant/) end end it 'will report a mismatch between a hash and a struct with details' do code = <<-CODE function f(Hash[String,String] $h) { $h['a'] } f({'a' => 'a', 'b' => 23}) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /'f' parameter 'h' entry 'b' expects a String value, got Integer/) end it 'will report a mismatch between a array and tuple with details' do code = <<-CODE function f(Array[String] $h) { $h[0] } f(['a', 23]) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /'f' parameter 'h' index 1 expects a String value, got Integer/) end it 'will not report details for a mismatch between an array and a struct' do code = <<-CODE function f(Array[String] $h) { $h[0] } f({'a' => 'a string', 'b' => 23}) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects an Array value, got Struct/) end it 'will not report details for a mismatch between a hash and a tuple' do code = <<-CODE function f(Hash[String,String] $h) { $h['a'] } f(['a', 23]) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects a Hash value, got Tuple/) end it 'will report an array size mismatch' do code = <<-CODE function f(Array[String,1,default] $h) { $h[0] } f([]) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects size to be at least 1, got 0/) end it 'will report a hash size mismatch' do code = <<-CODE function f(Hash[String,String,1,default] $h) { $h['a'] } f({}) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects size to be at least 1, got 0/) end it 'will include the aliased type when reporting a mismatch that involves an alias' do code = <<-CODE type UnprivilegedPort = Integer[1024,65537] function check_port(UnprivilegedPort $port) {} check_port(34) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /parameter 'port' expects an UnprivilegedPort = Integer\[1024, 65537\] value, got Integer\[34, 34\]/) end it 'will include the aliased type when reporting a mismatch that involves an alias nested in another type' do code = <<-CODE type UnprivilegedPort = Integer[1024,65537] type PortMap = Hash[UnprivilegedPort,String] function check_port(PortMap $ports) {} check_port({ 34 => 'some service'}) CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'ports' expects a PortMap = Hash\[UnprivilegedPort = Integer\[1024, 65537\], String\] value, got Hash\[Integer\[34, 34\], String\]/)) end it 'will not include the aliased type more than once when reporting a mismatch that involves an alias that is self recursive' do code = <<-CODE type Tree = Hash[String,Tree] function check_tree(Tree $tree) {} check_tree({ 'x' => {'y' => {32 => 'n'}}}) CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'tree' entry 'x' entry 'y' expects a Tree = Hash\[String, Tree\] value, got Hash\[Integer\[32, 32\], String\]/)) end it 'will use type normalization' do code = <<-CODE type EVariants = Variant[Enum[a,b],Enum[b,c],Enum[c,d]] function check_enums(EVariants $evars) {} check_enums('n') CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'evars' expects a match for EVariants = Enum\['a', 'b', 'c', 'd'\], got 'n'/)) end it "will not generalize a string that doesn't match an enum in a function call" do code = <<-CODE function check_enums(Enum[a,b] $arg) {} check_enums('c') CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'arg' expects a match for Enum\['a', 'b'\], got 'c'/)) end it "will not disclose a Sensitive that doesn't match an enum in a function call" do code = <<-CODE function check_enums(Enum[a,b] $arg) {} check_enums(Sensitive('c')) CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'arg' expects a match for Enum\['a', 'b'\], got Sensitive/)) end it "reports errors on the first failing parameter when that parameter is not the first in order" do code = <<-CODE type Abc = Enum['a', 'b', 'c'] type Cde = Enum['c', 'd', 'e'] function two_params(Abc $a, Cde $b) {} two_params('a', 'x') CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'b' expects a match for Cde = Enum\['c', 'd', 'e'\], got 'x'/)) end it "will not generalize a string that doesn't match an enum in a define call" do code = <<-CODE define check_enums(Enum[a,b] $arg) {} check_enums { x: arg => 'c' } CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'arg' expects a match for Enum\['a', 'b'\], got 'c'/)) end it "will include Undef when describing a mismatch against a Variant where one of the types is Undef" do code = <<-CODE define check(Variant[Undef,String,Integer,Hash,Array] $arg) {} check{ x: arg => 2.4 } CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'arg' expects a value of type Undef, String, Integer, Hash, or Array/)) end it "will not disclose a Sensitive that doesn't match an enum in a define call" do code = <<-CODE define check_enums(Enum[a,b] $arg) {} check_enums { x: arg => Sensitive('c') } CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /parameter 'arg' expects a match for Enum\['a', 'b'\], got Sensitive/)) end it "will report the parameter of Type[<type alias>] using the alias name" do code = <<-CODE type Custom = String[1] Custom.each |$x| { notice($x) } CODE expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /expects an Iterable value, got Type\[Custom\]/)) end context 'when reporting a mismatch between' do let(:parser) { TypeParser.singleton } let(:subject) { TypeMismatchDescriber.singleton } context 'hash and struct' do it 'reports a size mismatch when hash has unlimited size' do expected = parser.parse('Struct[{a=>Integer,b=>Integer}]') actual = parser.parse('Hash[String,Integer]') expect(subject.describe_mismatch('', expected, actual)).to eq('expects size to be 2, got unlimited') end it 'reports a size mismatch when hash has specified but incorrect size' do expected = parser.parse('Struct[{a=>Integer,b=>Integer}]') actual = parser.parse('Hash[String,Integer,1,1]') expect(subject.describe_mismatch('', expected, actual)).to eq('expects size to be 2, got 1') end it 'reports a full type mismatch when size is correct but hash value type is incorrect' do expected = parser.parse('Struct[{a=>Integer,b=>String}]') actual = parser.parse('Hash[String,Integer,2,2]') expect(subject.describe_mismatch('', expected, actual)).to eq("expects a Struct[{'a' => Integer, 'b' => String}] value, got Hash[String, Integer]") end end it 'reports a missing parameter as "has no parameter"' do t = parser.parse('Struct[{a=>String}]') expect { subject.validate_parameters('v', t, {'a'=>'a','b'=>'b'}, false) }.to raise_error(Puppet::Error, "v: has no parameter named 'b'") end it 'reports a missing value as "expects a value"' do t = parser.parse('Struct[{a=>String,b=>String}]') expect { subject.validate_parameters('v', t, {'a'=>'a'}, false) }.to raise_error(Puppet::Error, "v: expects a value for parameter 'b'") end it 'reports a missing block as "expects a block"' do callable = parser.parse('Callable[String,String,Callable]') args_tuple = parser.parse('Tuple[String,String]') dispatch = Functions::Dispatch.new(callable, 'foo', ['a','b'], false, 'block') expect(subject.describe_signatures('function', [dispatch], args_tuple)).to eq("'function' expects a block") end it 'reports an unexpected block as "does not expect a block"' do callable = parser.parse('Callable[String,String]') args_tuple = parser.parse('Tuple[String,String,Callable]') dispatch = Functions::Dispatch.new(callable, 'foo', ['a','b']) expect(subject.describe_signatures('function', [dispatch], args_tuple)).to eq("'function' does not expect a block") end it 'reports a block return type mismatch' do callable = parser.parse('Callable[[0,0,Callable[ [0,0],String]],Undef]') args_tuple = parser.parse('Tuple[Callable[[0,0],Integer]]') dispatch = Functions::Dispatch.new(callable, 'foo', [], false, 'block') expect(subject.describe_signatures('function', [dispatch], args_tuple)).to eq("'function' block return expects a String value, got Integer") end end it "reports struct mismatch correctly when hash doesn't contain required keys" do code = <<-PUPPET type Test::Options = Struct[{ var => String }] class test(String $var, Test::Options $opts) {} class { 'test': var => 'hello', opts => {} } PUPPET expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error, /Class\[Test\]: parameter 'opts' expects size to be 1, got 0/)) end it "treats Optional as Optional[Any]" do code = <<-PUPPET class test(Optional $var=undef) {} class { 'test': var => 'hello' } PUPPET expect { eval_and_collect_notices(code) }.not_to raise_error end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_timestamp_type_spec.rb
spec/unit/pops/types/p_timestamp_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Timestamp type' do it 'is normalized in a Variant' do t = TypeFactory.variant(TypeFactory.timestamp('2015-03-01', '2016-01-01'), TypeFactory.timestamp('2015-11-03', '2016-12-24')).normalize expect(t).to be_a(PTimestampType) expect(t).to eql(TypeFactory.timestamp('2015-03-01', '2016-12-24')) end it 'DateTime#_strptime creates hash with :leftover field' do expect(DateTime._strptime('2015-05-04 and bogus', '%F')).to include(:leftover) expect(DateTime._strptime('2015-05-04T10:34:11.003 UTC and bogus', '%FT%T.%N %Z')).to include(:leftover) end context 'when used in Puppet expressions' do include PuppetSpec::Compiler it 'is equal to itself only' do code = <<-CODE $t = Timestamp notice(Timestamp =~ Type[Timestamp]) notice(Timestamp == Timestamp) notice(Timestamp < Timestamp) notice(Timestamp > Timestamp) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true false false)) end it 'does not consider an Integer to be an instance' do code = <<-CODE notice(assert_type(Timestamp, 1234)) CODE expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timestamp value, got Integer/) end it 'does not consider a Float to be an instance' do code = <<-CODE notice(assert_type(Timestamp, 1.234)) CODE expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timestamp value, got Float/) end context "when parameterized" do it 'is equal other types with the same parameterization' do code = <<-CODE notice(Timestamp['2015-03-01', '2016-01-01'] == Timestamp['2015-03-01', '2016-01-01']) notice(Timestamp['2015-03-01', '2016-01-01'] != Timestamp['2015-11-03', '2016-12-24']) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true)) end it 'using just one parameter is the same as using default for the second parameter' do code = <<-CODE notice(Timestamp['2015-03-01'] == Timestamp['2015-03-01', default]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true)) end it 'if the second parameter is default, it is unlimited' do code = <<-CODE notice(Timestamp('5553-12-31') =~ Timestamp['2015-03-01', default]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true)) end it 'orders parameterized types based on range inclusion' do code = <<-CODE notice(Timestamp['2015-03-01', '2015-09-30'] < Timestamp['2015-02-01', '2015-10-30']) notice(Timestamp['2015-03-01', '2015-09-30'] > Timestamp['2015-02-01', '2015-10-30']) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false)) end it 'accepts integer values when specifying the range' do code = <<-CODE notice(Timestamp(1) =~ Timestamp[1, 2]) notice(Timestamp(3) =~ Timestamp[1]) notice(Timestamp(0) =~ Timestamp[default, 2]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true true)) end it 'accepts float values when specifying the range' do code = <<-CODE notice(Timestamp(1.0) =~ Timestamp[1.0, 2.0]) notice(Timestamp(3.0) =~ Timestamp[1.0]) notice(Timestamp(0.0) =~ Timestamp[default, 2.0]) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true true)) end end context 'a Timestamp instance' do it 'can be created from a string with just a date' do code = <<-CODE $o = Timestamp('2015-03-01') notice($o) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq(['2015-03-01T00:00:00.000000000 UTC', "Timestamp['2015-03-01T00:00:00.000000000 UTC']"]) end it 'can be created from a string and time separated by "T"' do code = <<-CODE notice(Timestamp('2015-03-01T11:12:13')) CODE expect(eval_and_collect_notices(code)).to eq(['2015-03-01T11:12:13.000000000 UTC']) end it 'can be created from a string and time separated by space' do code = <<-CODE notice(Timestamp('2015-03-01 11:12:13')) CODE expect(eval_and_collect_notices(code)).to eq(['2015-03-01T11:12:13.000000000 UTC']) end it 'should error when none of the default formats can parse the string' do code = <<-CODE notice(Timestamp('2015#03#01 11:12:13')) CODE expect { eval_and_collect_notices(code) }.to raise_error(/Unable to parse/) end it 'should error when only part of the string is parsed' do code = <<-CODE notice(Timestamp('2015-03-01T11:12:13 bogus after')) CODE expect { eval_and_collect_notices(code) }.to raise_error(/Unable to parse/) end it 'can be created from a string and format' do code = <<-CODE $o = Timestamp('Sunday, 28 August, 2016', '%A, %d %B, %Y') notice($o) CODE expect(eval_and_collect_notices(code)).to eq(['2016-08-28T00:00:00.000000000 UTC']) end it 'can be created from a string, format, and a timezone' do code = <<-CODE $o = Timestamp('Sunday, 28 August, 2016', '%A, %d %B, %Y', 'EST') notice($o) CODE expect(eval_and_collect_notices(code)).to eq(['2016-08-28T05:00:00.000000000 UTC']) end it 'can be not be created from a string, format with timezone designator, and a timezone' do code = <<-CODE $o = Timestamp('Sunday, 28 August, 2016 UTC', '%A, %d %B, %Y %z', 'EST') notice($o) CODE expect { eval_and_collect_notices(code) }.to raise_error( /Using a Timezone designator in format specification is mutually exclusive to providing an explicit timezone argument/) end it 'can be created from a hash with string and format' do code = <<-CODE $o = Timestamp({ string => 'Sunday, 28 August, 2016', format => '%A, %d %B, %Y' }) notice($o) CODE expect(eval_and_collect_notices(code)).to eq(['2016-08-28T00:00:00.000000000 UTC']) end it 'can be created from a hash with string, format, and a timezone' do code = <<-CODE $o = Timestamp({ string => 'Sunday, 28 August, 2016', format => '%A, %d %B, %Y', timezone => 'EST' }) notice($o) CODE expect(eval_and_collect_notices(code)).to eq(['2016-08-28T05:00:00.000000000 UTC']) end it 'can be created from a string and array of formats' do code = <<-CODE $fmts = [ '%A, %d %B, %Y at %r', '%b %d, %Y, %l:%M %P', '%y-%m-%d %H:%M:%S %z' ] notice(Timestamp('Sunday, 28 August, 2016 at 12:15:00 PM', $fmts)) notice(Timestamp('Jul 24, 2016, 1:20 am', $fmts)) notice(Timestamp('16-06-21 18:23:15 UTC', $fmts)) CODE expect(eval_and_collect_notices(code)).to eq( ['2016-08-28T12:15:00.000000000 UTC', '2016-07-24T01:20:00.000000000 UTC', '2016-06-21T18:23:15.000000000 UTC']) end it 'it cannot be created using an empty formats array' do code = <<-CODE notice(Timestamp('2015-03-01T11:12:13', [])) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /parameter 'format' variant 1 expects size to be at least 1, got 0/) end it 'can be created from a string, array of formats, and a timezone' do code = <<-CODE $fmts = [ '%A, %d %B, %Y at %r', '%b %d, %Y, %l:%M %P', '%y-%m-%d %H:%M:%S' ] notice(Timestamp('Sunday, 28 August, 2016 at 12:15:00 PM', $fmts, 'CET')) notice(Timestamp('Jul 24, 2016, 1:20 am', $fmts, 'CET')) notice(Timestamp('16-06-21 18:23:15', $fmts, 'CET')) CODE expect(eval_and_collect_notices(code)).to eq( ['2016-08-28T11:15:00.000000000 UTC', '2016-07-24T00:20:00.000000000 UTC', '2016-06-21T17:23:15.000000000 UTC']) end it 'can be created from a integer that represents seconds since epoch' do code = <<-CODE $o = Timestamp(1433116800) notice(Integer($o) == 1433116800) notice($o == Timestamp('2015-06-01T00:00:00 UTC')) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true)) end it 'can be created from a float that represents seconds with fraction since epoch' do code = <<-CODE $o = Timestamp(1433116800.123456) notice(Float($o) == 1433116800.123456) notice($o == Timestamp('2015-06-01T00:00:00.123456 UTC')) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true)) end it 'matches the appropriate parameterized type' do code = <<-CODE $o = Timestamp('2015-05-01') notice(assert_type(Timestamp['2015-03-01', '2015-09-30'], $o)) CODE expect(eval_and_collect_notices(code)).to eq(['2015-05-01T00:00:00.000000000 UTC']) end it 'does not match an inappropriate parameterized type' do code = <<-CODE $o = Timestamp('2015-05-01') notice(assert_type(Timestamp['2016-03-01', '2016-09-30'], $o) |$e, $a| { 'nope' }) CODE expect(eval_and_collect_notices(code)).to eq(['nope']) end it 'can be compared to other instances' do code = <<-CODE $o1 = Timestamp('2015-05-01') $o2 = Timestamp('2015-06-01') $o3 = Timestamp('2015-06-01') notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o1 == $o3) notice($o1 != $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) notice($o2 == $o3) notice($o2 != $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false true false false true true true false)) end it 'can be compared to integer that represents seconds since epoch' do code = <<-CODE $o1 = Timestamp('2015-05-01') $o2 = Timestamp('2015-06-01') $o3 = 1433116800 notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'integer that represents seconds since epoch can be compared to it' do code = <<-CODE $o1 = 1430438400 $o2 = 1433116800 $o3 = Timestamp('2015-06-01') notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'is equal to integer that represents seconds since epoch' do code = <<-CODE $o1 = Timestamp('2015-06-01T00:00:00 UTC') $o2 = 1433116800 notice($o1 == $o2) notice($o1 != $o2) notice(Integer($o1) == $o2) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'integer that represents seconds is equal to it' do code = <<-CODE $o1 = 1433116800 $o2 = Timestamp('2015-06-01T00:00:00 UTC') notice($o1 == $o2) notice($o1 != $o2) notice($o1 == Integer($o2)) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'can be compared to float that represents seconds with fraction since epoch' do code = <<-CODE $o1 = Timestamp('2015-05-01T00:00:00.123456789 UTC') $o2 = Timestamp('2015-06-01T00:00:00.123456789 UTC') $o3 = 1433116800.123456789 notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'float that represents seconds with fraction since epoch can be compared to it' do code = <<-CODE $o1 = 1430438400.123456789 $o2 = 1433116800.123456789 $o3 = Timestamp('2015-06-01T00:00:00.123456789 UTC') notice($o1 > $o3) notice($o1 >= $o3) notice($o1 < $o3) notice($o1 <= $o3) notice($o2 > $o3) notice($o2 < $o3) notice($o2 >= $o3) notice($o2 <= $o3) CODE expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true)) end it 'is equal to float that represents seconds with fraction since epoch' do code = <<-CODE $o1 = Timestamp('2015-06-01T00:00:00.123456789 UTC') $o2 = 1433116800.123456789 notice($o1 == $o2) notice($o1 != $o2) notice(Float($o1) == $o2) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'float that represents seconds with fraction is equal to it' do code = <<-CODE $o1 = 1433116800.123456789 $o2 = Timestamp('2015-06-01T00:00:00.123456789 UTC') notice($o1 == $o2) notice($o1 != $o2) notice($o1 == Float($o2)) CODE expect(eval_and_collect_notices(code)).to eq(%w(true false true)) end it 'it cannot be compared to a Timespan' do code = <<-CODE notice(Timestamp() > Timespan(3)) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Timestamps are only comparable to Timestamps, Integers, and Floats/) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/iterable_spec.rb
spec/unit/pops/types/iterable_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops::Types describe 'The iterable support' do [ 0, 5, (3..10), %w(a b c), {'a'=>2}, 'hello', PIntegerType.new(1, 4), PEnumType.new(%w(yes no)) ].each do |obj| it "should consider instances of #{obj.class.name} to be Iterable" do expect(PIterableType::DEFAULT.instance?(obj)).to eq(true) end it "should yield an Iterable instance when Iterable.on is called with a #{obj.class.name}" do expect(Iterable.on(obj)).to be_a(Iterable) end end { -1 => 'a negative Integer', 5.times => 'an Enumerable', PIntegerType.new(nil, nil) => 'an unbounded Integer type' }.each_pair do |obj, desc| it "does not consider #{desc} to be Iterable" do expect(PIterableType::DEFAULT.instance?(obj)).to eq(false) end it "does not yield an Iterable when Iterable.on is called with #{desc}" do expect(Iterable.on(obj)).to be_nil end end context 'when testing assignability' do iterable_types = [ PIntegerType::DEFAULT, PStringType::DEFAULT, PIterableType::DEFAULT, PIteratorType::DEFAULT, PCollectionType::DEFAULT, PArrayType::DEFAULT, PHashType::DEFAULT, PTupleType::DEFAULT, PStructType::DEFAULT, PUnitType::DEFAULT ] iterable_types << PTypeType.new(PIntegerType.new(0, 10)) iterable_types << PTypeType.new(PEnumType.new(%w(yes no))) iterable_types << PRuntimeType.new(:ruby, 'Puppet::Pops::Types::Iterator') iterable_types << PVariantType.new(iterable_types.clone) not_iterable_types = [ PAnyType::DEFAULT, PBooleanType::DEFAULT, PCallableType::DEFAULT, PCatalogEntryType::DEFAULT, PDefaultType::DEFAULT, PFloatType::DEFAULT, PClassType::DEFAULT, PNotUndefType::DEFAULT, PNumericType::DEFAULT, POptionalType::DEFAULT, PPatternType::DEFAULT, PRegexpType::DEFAULT, PResourceType::DEFAULT, PRuntimeType::DEFAULT, PScalarType::DEFAULT, PScalarDataType::DEFAULT, PTypeType::DEFAULT, PUndefType::DEFAULT ] not_iterable_types << PTypeType.new(PIntegerType::DEFAULT) not_iterable_types << PVariantType.new([iterable_types[0], not_iterable_types[0]]) iterable_types.each do |type| it "should consider #{type} to be assignable to Iterable type" do expect(PIterableType::DEFAULT.assignable?(type)).to eq(true) end end not_iterable_types.each do |type| it "should not consider #{type} to be assignable to Iterable type" do expect(PIterableType::DEFAULT.assignable?(type)).to eq(false) end end it "should consider Type[Integer[0,5]] to be assignable to Iterable[Integer[0,5]]" do expect(PIterableType.new(PIntegerType.new(0,5)).assignable?(PTypeType.new(PIntegerType.new(0,5)))).to eq(true) end it "should consider Type[Enum[yes,no]] to be assignable to Iterable[Enum[yes,no]]" do expect(PIterableType.new(PEnumType.new(%w(yes no))).assignable?(PTypeType.new(PEnumType.new(%w(yes no))))).to eq(true) end it "should not consider Type[Enum[ok,fail]] to be assignable to Iterable[Enum[yes,no]]" do expect(PIterableType.new(PEnumType.new(%w(ok fail))).assignable?(PTypeType.new(PEnumType.new(%w(yes no))))).to eq(false) end it "should not consider Type[String] to be assignable to Iterable[String]" do expect(PIterableType.new(PStringType::DEFAULT).assignable?(PTypeType.new(PStringType::DEFAULT))).to eq(false) end end it 'does not wrap an Iterable in another Iterable' do x = Iterable.on(5) expect(Iterable.on(x)).to equal(x) end it 'produces a "times" iterable on integer' do expect{ |b| Iterable.on(3).each(&b) }.to yield_successive_args(0,1,2) end it 'produces an iterable with element type Integer[0,X-1] for an iterable on an integer X' do expect(Iterable.on(3).element_type).to eq(PIntegerType.new(0,2)) end it 'produces a step iterable on an integer' do expect{ |b| Iterable.on(8).step(3, &b) }.to yield_successive_args(0, 3, 6) end it 'produces a reverse iterable on an integer' do expect{ |b| Iterable.on(5).reverse_each(&b) }.to yield_successive_args(4,3,2,1,0) end it 'produces an iterable on a integer range' do expect{ |b| Iterable.on(2..7).each(&b) }.to yield_successive_args(2,3,4,5,6,7) end it 'produces an iterable with element type Integer[X,Y] for an iterable on an integer range (X..Y)' do expect(Iterable.on(2..7).element_type).to eq(PIntegerType.new(2,7)) end it 'produces an iterable on a character range' do expect{ |b| Iterable.on('a'..'f').each(&b) }.to yield_successive_args('a', 'b', 'c', 'd', 'e', 'f') end it 'produces a step iterable on a range' do expect{ |b| Iterable.on(1..5).step(2, &b) }.to yield_successive_args(1,3,5) end it 'produces a reverse iterable on a range' do expect{ |b| Iterable.on(2..7).reverse_each(&b) }.to yield_successive_args(7,6,5,4,3,2) end it 'produces an iterable with element type String with a size constraint for an iterable on a character range' do expect(Iterable.on('a'..'fe').element_type).to eq(PStringType.new(PIntegerType.new(1,2))) end it 'produces an iterable on a bounded Integer type' do expect{ |b| Iterable.on(PIntegerType.new(2,7)).each(&b) }.to yield_successive_args(2,3,4,5,6,7) end it 'produces an iterable with element type Integer[X,Y] for an iterable on Integer[X,Y]' do expect(Iterable.on(PIntegerType.new(2,7)).element_type).to eq(PIntegerType.new(2,7)) end it 'produces an iterable on String' do expect{ |b| Iterable.on('eat this').each(&b) }.to yield_successive_args('e', 'a', 't', ' ', 't', 'h', 'i', 's') end it 'produces an iterable with element type String[1,1] for an iterable created on a String' do expect(Iterable.on('eat this').element_type).to eq(PStringType.new(PIntegerType.new(1,1))) end it 'produces an iterable on Array' do expect{ |b| Iterable.on([1,5,9]).each(&b) }.to yield_successive_args(1,5,9) end it 'produces an iterable with element type inferred from the array elements for an iterable on Array' do expect(Iterable.on([1,5,5,9,9,9]).element_type).to eq(PVariantType.new([PIntegerType.new(1,1), PIntegerType.new(5,5), PIntegerType.new(9,9)])) end it 'can chain reverse_each after step on Iterable' do expect{ |b| Iterable.on(6).step(2).reverse_each(&b) }.to yield_successive_args(4,2,0) end it 'can chain reverse_each after step on Integer range' do expect{ |b| Iterable.on(PIntegerType.new(0, 5)).step(2).reverse_each(&b) }.to yield_successive_args(4,2,0) end it 'can chain step after reverse_each on Iterable' do expect{ |b| Iterable.on(6).reverse_each.step(2, &b) }.to yield_successive_args(5,3,1) end it 'can chain step after reverse_each on Integer range' do expect{ |b| Iterable.on(PIntegerType.new(0, 5)).reverse_each.step(2, &b) }.to yield_successive_args(5,3,1) end it 'will produce the same result for each as for reverse_each.reverse_each' do x1 = Iterable.on(5) x2 = Iterable.on(5) expect(x1.reduce([]) { |a,i| a << i; a}).to eq(x2.reverse_each.reverse_each.reduce([]) { |a,i| a << i; a}) end it 'can chain many nested step/reverse_each calls' do # x = Iterable.on(18).step(3) (0, 3, 6, 9, 12, 15) # x = x.reverse_each (15, 12, 9, 6, 3, 0) # x = x.step(2) (15, 9, 3) # x = x.reverse_each(3, 9, 15) expect{ |b| Iterable.on(18).step(3).reverse_each.step(2).reverse_each(&b) }.to yield_successive_args(3, 9, 15) end it 'can chain many nested step/reverse_each calls on Array iterable' do expect{ |b| Iterable.on(18.times.to_a).step(3).reverse_each.step(2).reverse_each(&b) }.to yield_successive_args(3, 9, 15) end it 'produces an steppable iterable for Array' do expect{ |b| Iterable.on(%w(a b c d e f g h i)).step(3, &b) }.to yield_successive_args('a', 'd', 'g') end it 'produces an reverse steppable iterable for Array' do expect{ |b| Iterable.on(%w(a b c d e f g h i)).reverse_each.step(3, &b) }.to yield_successive_args('i', 'f', 'c') end it 'responds false when a bounded Iterable is passed to Iterable.unbounded?' do expect(Iterable.unbounded?(Iterable.on(%w(a b c d e f g h i)))).to eq(false) end it 'can create an Array from a bounded Iterable' do expect(Iterable.on(%w(a b c d e f g h i)).to_a).to eq(%w(a b c d e f g h i)) end class TestUnboundedIterator include Enumerable include Iterable def step(step_size) if block_given? begin current = 0 loop do yield(@current) current = current + step_size end rescue StopIteration end end self end end it 'responds true when an unbounded Iterable is passed to Iterable.unbounded?' do ubi = TestUnboundedIterator.new expect(Iterable.unbounded?(Iterable.on(ubi))).to eq(true) end it 'can not create an Array from an unbounded Iterable' do ubi = TestUnboundedIterator.new expect{ Iterable.on(ubi).to_a }.to raise_error(Puppet::Error, /Attempt to create an Array from an unbounded Iterable/) end it 'will produce the string Iterator[T] on to_s on an iterator instance with element type T' do expect(Iterable.on(18).to_s).to eq('Iterator[Integer]-Value') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/type_calculator_spec.rb
spec/unit/pops/types/type_calculator_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops module Types describe 'The type calculator' do let(:calculator) { TypeCalculator.new } def range_t(from, to) PIntegerType.new(from, to) end def pattern_t(*patterns) TypeFactory.pattern(*patterns) end def regexp_t(pattern) TypeFactory.regexp(pattern) end def string_t(string = nil) TypeFactory.string(string) end def constrained_string_t(size_type) TypeFactory.string(size_type) end def callable_t(*params) TypeFactory.callable(*params) end def all_callables_t TypeFactory.all_callables end def enum_t(*strings) TypeFactory.enum(*strings) end def variant_t(*types) TypeFactory.variant(*types) end def empty_variant_t() t = TypeFactory.variant() # assert this to ensure we did get an empty variant (or tests may pass when not being empty) raise 'typefactory did not return empty variant' unless t.types.empty? t end def type_alias_t(name, type_string) type_expr = Parser::EvaluatingParser.new.parse_string(type_string) TypeFactory.type_alias(name, type_expr) end def type_reference_t(type_string) TypeFactory.type_reference(type_string) end def integer_t TypeFactory.integer end def array_t(t, s = nil) TypeFactory.array_of(t, s) end def empty_array_t array_t(unit_t, range_t(0,0)) end def hash_t(k,v,s = nil) TypeFactory.hash_of(v, k, s) end def data_t TypeFactory.data end def factory TypeFactory end def collection_t(size_type = nil) TypeFactory.collection(size_type) end def tuple_t(*types) TypeFactory.tuple(types) end def constrained_tuple_t(size_type, *types) TypeFactory.tuple(types, size_type) end def struct_t(type_hash) TypeFactory.struct(type_hash) end def any_t TypeFactory.any end def optional_t(t) TypeFactory.optional(t) end def type_t(t) TypeFactory.type_type(t) end def not_undef_t(t = nil) TypeFactory.not_undef(t) end def undef_t TypeFactory.undef end def unit_t # Cannot be created via factory, the type is private to the type system PUnitType::DEFAULT end def runtime_t(t, c) TypeFactory.runtime(t, c) end def object_t(hash) TypeFactory.object(hash) end def iterable_t(t = nil) TypeFactory.iterable(t) end def types Types end context 'when inferring ruby' do it 'integer translates to PIntegerType' do expect(calculator.infer(1).class).to eq(PIntegerType) end it 'large integer translates to PIntegerType' do expect(calculator.infer(2**33).class).to eq(PIntegerType) end it 'float translates to PFloatType' do expect(calculator.infer(1.3).class).to eq(PFloatType) end it 'string translates to PStringType' do expect(calculator.infer('foo').class).to eq(PStringType) end it 'inferred string type knows the string value' do t = calculator.infer('foo') expect(t.class).to eq(PStringType) expect(t.value).to eq('foo') end it 'boolean true translates to PBooleanType::TRUE' do expect(calculator.infer(true)).to eq(PBooleanType::TRUE) end it 'boolean false translates to PBooleanType::FALSE' do expect(calculator.infer(false)).to eq(PBooleanType::FALSE) end it 'regexp translates to PRegexpType' do expect(calculator.infer(/^a regular expression$/).class).to eq(PRegexpType) end it 'iterable translates to PIteratorType' do expect(calculator.infer(Iterable.on(1))).to be_a(PIteratorType) end it 'nil translates to PUndefType' do expect(calculator.infer(nil).class).to eq(PUndefType) end it ':undef translates to PUndefType' do expect(calculator.infer(:undef).class).to eq(PUndefType) end it 'an instance of class Foo translates to PRuntimeType[ruby, Foo]' do ::Foo = Class.new begin t = calculator.infer(::Foo.new) expect(t.class).to eq(PRuntimeType) expect(t.runtime).to eq(:ruby) expect(t.runtime_type_name).to eq('Foo') ensure Object.send(:remove_const, :Foo) end end it 'Class Foo translates to PTypeType[PRuntimeType[ruby, Foo]]' do ::Foo = Class.new begin t = calculator.infer(::Foo) expect(t.class).to eq(PTypeType) tt = t.type expect(tt.class).to eq(PRuntimeType) expect(tt.runtime).to eq(:ruby) expect(tt.runtime_type_name).to eq('Foo') ensure Object.send(:remove_const, :Foo) end end it 'Module FooModule translates to PTypeType[PRuntimeType[ruby, FooModule]]' do ::FooModule = Module.new begin t = calculator.infer(::FooModule) expect(t.class).to eq(PTypeType) tt = t.type expect(tt.class).to eq(PRuntimeType) expect(tt.runtime).to eq(:ruby) expect(tt.runtime_type_name).to eq('FooModule') ensure Object.send(:remove_const, :FooModule) end end context 'sensitive' do it 'translates to PSensitiveType' do expect(calculator.infer(PSensitiveType::Sensitive.new("hunter2")).class).to eq(PSensitiveType) end end context 'binary' do it 'translates to PBinaryType' do expect(calculator.infer(PBinaryType::Binary.from_binary_string("binary")).class).to eq(PBinaryType) end end context 'version' do it 'translates to PVersionType' do expect(calculator.infer(SemanticPuppet::Version.new(1,0,0)).class).to eq(PSemVerType) end it 'range translates to PVersionRangeType' do expect(calculator.infer(SemanticPuppet::VersionRange.parse('1.x')).class).to eq(PSemVerRangeType) end it 'translates to a limited PVersionType by infer_set' do v = SemanticPuppet::Version.new(1,0,0) t = calculator.infer_set(v) expect(t.class).to eq(PSemVerType) expect(t.ranges.size).to eq(1) expect(t.ranges[0].begin).to eq(v) expect(t.ranges[0].end).to eq(v) end end context 'timespan' do it 'translates to PTimespanType' do expect(calculator.infer(Time::Timespan.from_fields_hash('days' => 2))).to be_a(PTimespanType) end it 'translates to a limited PTimespanType by infer_set' do ts = Time::Timespan.from_fields_hash('days' => 2) t = calculator.infer_set(ts) expect(t.class).to eq(PTimespanType) expect(t.from).to be(ts) expect(t.to).to be(ts) end end context 'timestamp' do it 'translates to PTimespanType' do expect(calculator.infer(Time::Timestamp.now)).to be_a(PTimestampType) end it 'translates to a limited PTimespanType by infer_set' do ts = Time::Timestamp.now t = calculator.infer_set(ts) expect(t.class).to eq(PTimestampType) expect(t.from).to be(ts) expect(t.to).to be(ts) end end context 'array' do let(:derived) do Class.new(Array).new([1,2]) end let(:derived_object) do Class.new(Array) do include PuppetObject def self._pcore_type @type ||= TypeFactory.object('name' => 'DerivedObjectArray') end end.new([1,2]) end it 'translates to PArrayType' do expect(calculator.infer([1,2]).class).to eq(PArrayType) end it 'translates derived Array to PRuntimeType' do expect(calculator.infer(derived).class).to eq(PRuntimeType) end it 'translates derived Puppet Object Array to PObjectType' do expect(calculator.infer(derived_object).class).to eq(PObjectType) end it 'Instance of derived Array class is not instance of Array type' do expect(PArrayType::DEFAULT).not_to be_instance(derived) end it 'Instance of derived Array class is instance of Runtime type' do expect(runtime_t('ruby', nil)).to be_instance(derived) end it 'Instance of derived Puppet Object Array class is not instance of Array type' do expect(PArrayType::DEFAULT).not_to be_instance(derived_object) end it 'Instance of derived Puppet Object Array class is instance of Object type' do expect(object_t('name' => 'DerivedObjectArray')).to be_instance(derived_object) end it 'with integer values translates to PArrayType[PIntegerType]' do expect(calculator.infer([1,2]).element_type.class).to eq(PIntegerType) end it 'with 32 and 64 bit integer values translates to PArrayType[PIntegerType]' do expect(calculator.infer([1,2**33]).element_type.class).to eq(PIntegerType) end it 'Range of integer values are computed' do t = calculator.infer([-3,0,42]).element_type expect(t.class).to eq(PIntegerType) expect(t.from).to eq(-3) expect(t.to).to eq(42) end it 'Compound string values are converted to enums' do t = calculator.infer(['a','b', 'c']).element_type expect(t.class).to eq(PEnumType) expect(t.values).to eq(['a', 'b', 'c']) end it 'with integer and float values translates to PArrayType[PNumericType]' do expect(calculator.infer([1,2.0]).element_type.class).to eq(PNumericType) end it 'with integer and string values translates to PArrayType[PScalarDataType]' do expect(calculator.infer([1,'two']).element_type.class).to eq(PScalarDataType) end it 'with float and string values translates to PArrayType[PScalarDataType]' do expect(calculator.infer([1.0,'two']).element_type.class).to eq(PScalarDataType) end it 'with integer, float, and string values translates to PArrayType[PScalarDataType]' do expect(calculator.infer([1, 2.0,'two']).element_type.class).to eq(PScalarDataType) end it 'with integer and regexp values translates to PArrayType[PScalarType]' do expect(calculator.infer([1, /two/]).element_type.class).to eq(PScalarType) end it 'with string and regexp values translates to PArrayType[PScalarType]' do expect(calculator.infer(['one', /two/]).element_type.class).to eq(PScalarType) end it 'with string and symbol values translates to PArrayType[PAnyType]' do expect(calculator.infer(['one', :two]).element_type.class).to eq(PAnyType) end it 'with integer and nil values translates to PArrayType[PIntegerType]' do expect(calculator.infer([1, nil]).element_type.class).to eq(PIntegerType) end it 'with integer value, and array of string values, translates to Array[Data]' do expect(calculator.infer([1, ['two']]).element_type.name).to eq('Data') end it 'with integer value, and hash of string => string values, translates to Array[Data]' do expect(calculator.infer([1, {'two' => 'three'} ]).element_type.name).to eq('Data') end it 'with integer value, and hash of integer => string values, translates to Array[RichData]' do expect(calculator.infer([1, {2 => 'three'} ]).element_type.name).to eq('RichData') end it 'with integer, regexp, and binary values translates to Array[RichData]' do expect(calculator.infer([1, /two/, PBinaryType::Binary.from_string('three')]).element_type.name).to eq('RichData') end it 'with arrays of string values translates to PArrayType[PArrayType[PStringType]]' do et = calculator.infer([['first', 'array'], ['second','array']]) expect(et.class).to eq(PArrayType) et = et.element_type expect(et.class).to eq(PArrayType) et = et.element_type expect(et.class).to eq(PEnumType) end it 'with array of string values and array of integers translates to PArrayType[PArrayType[PScalarDataType]]' do et = calculator.infer([['first', 'array'], [1,2]]) expect(et.class).to eq(PArrayType) et = et.element_type expect(et.class).to eq(PArrayType) et = et.element_type expect(et.class).to eq(PScalarDataType) end it 'with hashes of string values translates to PArrayType[PHashType[PEnumType]]' do et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 'first', :second => 'second' }]) expect(et.class).to eq(PArrayType) et = et.element_type expect(et.class).to eq(PHashType) et = et.value_type expect(et.class).to eq(PEnumType) end it 'with hash of string values and hash of integers translates to PArrayType[PHashType[PScalarDataType]]' do et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 1, :second => 2 }]) expect(et.class).to eq(PArrayType) et = et.element_type expect(et.class).to eq(PHashType) et = et.value_type expect(et.class).to eq(PScalarDataType) end end context 'hash' do let(:derived) do Class.new(Hash)[:first => 1, :second => 2] end let(:derived_object) do Class.new(Hash) do include PuppetObject def self._pcore_type @type ||= TypeFactory.object('name' => 'DerivedObjectHash') end end[:first => 1, :second => 2] end it 'translates to PHashType' do expect(calculator.infer({:first => 1, :second => 2}).class).to eq(PHashType) end it 'translates derived Hash to PRuntimeType' do expect(calculator.infer(derived).class).to eq(PRuntimeType) end it 'translates derived Puppet Object Hash to PObjectType' do expect(calculator.infer(derived_object).class).to eq(PObjectType) end it 'Instance of derived Hash class is not instance of Hash type' do expect(PHashType::DEFAULT).not_to be_instance(derived) end it 'Instance of derived Hash class is instance of Runtime type' do expect(runtime_t('ruby', nil)).to be_instance(derived) end it 'Instance of derived Puppet Object Hash class is not instance of Hash type' do expect(PHashType::DEFAULT).not_to be_instance(derived_object) end it 'Instance of derived Puppet Object Hash class is instance of Object type' do expect(object_t('name' => 'DerivedObjectHash')).to be_instance(derived_object) end it 'with symbolic keys translates to PHashType[PRuntimeType[ruby, Symbol], value]' do k = calculator.infer({:first => 1, :second => 2}).key_type expect(k.class).to eq(PRuntimeType) expect(k.runtime).to eq(:ruby) expect(k.runtime_type_name).to eq('Symbol') end it 'with string keys translates to PHashType[PEnumType, value]' do expect(calculator.infer({'first' => 1, 'second' => 2}).key_type.class).to eq(PEnumType) end it 'with integer values translates to PHashType[key, PIntegerType]' do expect(calculator.infer({:first => 1, :second => 2}).value_type.class).to eq(PIntegerType) end it 'when empty infers a type that answers true to is_the_empty_hash?' do expect(calculator.infer({}).is_the_empty_hash?).to eq(true) expect(calculator.infer_set({}).is_the_empty_hash?).to eq(true) end it 'when empty is assignable to any PHashType' do expect(calculator.assignable?(hash_t(string_t, string_t), calculator.infer({}))).to eq(true) end it 'when empty is not assignable to a PHashType with from size > 0' do expect(calculator.assignable?(hash_t(string_t,string_t,range_t(1, 1)), calculator.infer({}))).to eq(false) end context 'using infer_set' do it "with 'first' and 'second' keys translates to PStructType[{first=>value,second=>value}]" do t = calculator.infer_set({'first' => 1, 'second' => 2}) expect(t.class).to eq(PStructType) expect(t.elements.size).to eq(2) expect(t.elements.map { |e| e.name }.sort).to eq(['first', 'second']) end it 'with string keys and string and array values translates to PStructType[{key1=>PStringType,key2=>PTupleType}]' do t = calculator.infer_set({ 'mode' => 'read', 'path' => ['foo', 'fee' ] }) expect(t.class).to eq(PStructType) expect(t.elements.size).to eq(2) els = t.elements.map { |e| e.value_type }.sort {|a,b| a.to_s <=> b.to_s } expect(els[0].class).to eq(PStringType) expect(els[1].class).to eq(PTupleType) end it 'with mixed string and non-string keys translates to PHashType' do t = calculator.infer_set({ 1 => 'first', 'second' => 'second' }) expect(t.class).to eq(PHashType) end it 'with empty string keys translates to PHashType' do t = calculator.infer_set({ '' => 'first', 'second' => 'second' }) expect(t.class).to eq(PHashType) end end end it 'infers an instance of an anonymous class to Runtime[ruby]' do cls = Class.new do attr_reader :name def initialize(name) @name = name end end t = calculator.infer(cls.new('test')) expect(t.class).to eql(PRuntimeType) expect(t.runtime).to eql(:ruby) expect(t.name_or_pattern).to eql(nil) end end context 'patterns' do it 'constructs a PPatternType' do t = pattern_t('a(b)c') expect(t.class).to eq(PPatternType) expect(t.patterns.size).to eq(1) expect(t.patterns[0].class).to eq(PRegexpType) expect(t.patterns[0].pattern).to eq('a(b)c') expect(t.patterns[0].regexp.match('abc')[1]).to eq('b') end it 'constructs a PEnumType with multiple strings' do t = enum_t('a', 'b', 'c', 'abc') expect(t.values).to eq(['a', 'b', 'c', 'abc'].sort) end end # Deal with cases not covered by computing common type context 'when computing common type' do it 'computes given resource type commonality' do r1 = PResourceType.new('File', nil) r2 = PResourceType.new('File', nil) expect(calculator.common_type(r1, r2).to_s).to eq('File') r2 = PResourceType.new('File', '/tmp/foo') expect(calculator.common_type(r1, r2).to_s).to eq('File') r1 = PResourceType.new('File', '/tmp/foo') expect(calculator.common_type(r1, r2).to_s).to eq("File['/tmp/foo']") r1 = PResourceType.new('File', '/tmp/bar') expect(calculator.common_type(r1, r2).to_s).to eq('File') r2 = PResourceType.new('Package', 'apache') expect(calculator.common_type(r1, r2).to_s).to eq('Resource') end it 'computes given hostclass type commonality' do r1 = PClassType.new('foo') r2 = PClassType.new('foo') expect(calculator.common_type(r1, r2).to_s).to eq('Class[foo]') r2 = PClassType.new('bar') expect(calculator.common_type(r1, r2).to_s).to eq('Class') r2 = PClassType.new(nil) expect(calculator.common_type(r1, r2).to_s).to eq('Class') r1 = PClassType.new(nil) expect(calculator.common_type(r1, r2).to_s).to eq('Class') end context 'of strings' do it 'computes commonality' do t1 = string_t('abc') t2 = string_t('xyz') common_t = calculator.common_type(t1,t2) expect(common_t.class).to eq(PEnumType) expect(common_t.values).to eq(['abc', 'xyz']) end it 'computes common size_type' do t1 = constrained_string_t(range_t(3,6)) t2 = constrained_string_t(range_t(2,4)) common_t = calculator.common_type(t1,t2) expect(common_t.class).to eq(PStringType) expect(common_t.size_type).to eq(range_t(2,6)) end it 'computes common size_type to be undef when one of the types has no size_type' do t1 = string_t t2 = constrained_string_t(range_t(2,4)) common_t = calculator.common_type(t1,t2) expect(common_t.class).to eq(PStringType) expect(common_t.size_type).to be_nil end it 'computes values to be empty if the one has empty values' do t1 = string_t('apa') t2 = constrained_string_t(range_t(2,4)) common_t = calculator.common_type(t1,t2) expect(common_t.class).to eq(PStringType) expect(common_t.value).to be_nil end end it 'computes pattern commonality' do t1 = pattern_t('abc') t2 = pattern_t('xyz') common_t = calculator.common_type(t1,t2) expect(common_t.class).to eq(PPatternType) expect(common_t.patterns.map { |pr| pr.pattern }).to eq(['abc', 'xyz']) expect(common_t.to_s).to eq('Pattern[/abc/, /xyz/]') end it 'computes enum commonality to value set sum' do t1 = enum_t('a', 'b', 'c') t2 = enum_t('x', 'y', 'z') common_t = calculator.common_type(t1, t2) expect(common_t).to eq(enum_t('a', 'b', 'c', 'x', 'y', 'z')) end it 'computed variant commonality to type union where added types are not sub-types' do a_t1 = integer_t a_t2 = enum_t('b') v_a = variant_t(a_t1, a_t2) b_t1 = integer_t b_t2 = enum_t('a') v_b = variant_t(b_t1, b_t2) common_t = calculator.common_type(v_a, v_b) expect(common_t.class).to eq(PVariantType) expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2, b_t1, b_t2])) end it 'computed variant commonality to type union where added types are sub-types' do a_t1 = integer_t a_t2 = string_t v_a = variant_t(a_t1, a_t2) b_t1 = integer_t b_t2 = enum_t('a') v_b = variant_t(b_t1, b_t2) common_t = calculator.common_type(v_a, v_b) expect(common_t.class).to eq(PVariantType) expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2])) end context 'commonality of scalar data types' do it 'Numeric and String == ScalarData' do expect(calculator.common_type(PNumericType::DEFAULT, PStringType::DEFAULT).class).to eq(PScalarDataType) end it 'Numeric and Boolean == ScalarData' do expect(calculator.common_type(PNumericType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarDataType) end it 'String and Boolean == ScalarData' do expect(calculator.common_type(PStringType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarDataType) end end context 'commonality of scalar types' do it 'Regexp and Integer == Scalar' do expect(calculator.common_type(PRegexpType::DEFAULT, PScalarDataType::DEFAULT).class).to eq(PScalarType) end it 'Regexp and SemVer == ScalarData' do expect(calculator.common_type(PRegexpType::DEFAULT, PSemVerType::DEFAULT).class).to eq(PScalarType) end it 'Timestamp and Timespan == ScalarData' do expect(calculator.common_type(PTimestampType::DEFAULT, PTimespanType::DEFAULT).class).to eq(PScalarType) end it 'Timestamp and Boolean == ScalarData' do expect(calculator.common_type(PTimestampType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarType) end end context 'of callables' do it 'incompatible instances => generic callable' do t1 = callable_t(String) t2 = callable_t(Integer) common_t = calculator.common_type(t1, t2) expect(common_t.class).to be(PCallableType) expect(common_t.param_types).to be_nil expect(common_t.block_type).to be_nil end it 'compatible instances => the most specific' do t1 = callable_t(String) scalar_t = PScalarType.new t2 = callable_t(scalar_t) common_t = calculator.common_type(t1, t2) expect(common_t.class).to be(PCallableType) expect(common_t.param_types.class).to be(PTupleType) expect(common_t.param_types.types).to eql([string_t]) expect(common_t.block_type).to be_nil end it 'block_type is included in the check (incompatible block)' do b1 = callable_t(String) b2 = callable_t(Integer) t1 = callable_t(String, b1) t2 = callable_t(String, b2) common_t = calculator.common_type(t1, t2) expect(common_t.class).to be(PCallableType) expect(common_t.param_types).to be_nil expect(common_t.block_type).to be_nil end it 'block_type is included in the check (compatible block)' do b1 = callable_t(String) t1 = callable_t(String, b1) scalar_t = PScalarType::DEFAULT b2 = callable_t(scalar_t) t2 = callable_t(String, b2) common_t = calculator.common_type(t1, t2) expect(common_t.param_types.class).to be(PTupleType) expect(common_t.block_type).to eql(callable_t(scalar_t)) end it 'return_type is included in the check (incompatible return_type)' do t1 = callable_t([String], String) t2 = callable_t([String], Integer) common_t = calculator.common_type(t1, t2) expect(common_t.class).to be(PCallableType) expect(common_t.param_types).to be_nil expect(common_t.return_type).to be_nil end it 'return_type is included in the check (compatible return_type)' do t1 = callable_t([String], Numeric) t2 = callable_t([String], Integer) common_t = calculator.common_type(t1, t2) expect(common_t.class).to be(PCallableType) expect(common_t.param_types).to be_a(PTupleType) expect(common_t.return_type).to eql(PNumericType::DEFAULT) end end end context 'computes assignability' do include_context 'types_setup' it 'such that all types are assignable to themselves' do all_types.each do |tc| t = tc::DEFAULT expect(t).to be_assignable_to(t) end end context 'for Unit, such that' do it 'all types are assignable to Unit' do t = PUnitType::DEFAULT all_types.each { |t2| expect(t2::DEFAULT).to be_assignable_to(t) } end it 'Unit is assignable to all other types' do t = PUnitType::DEFAULT all_types.each { |t2| expect(t).to be_assignable_to(t2::DEFAULT) } end it 'Unit is assignable to Unit' do t = PUnitType::DEFAULT t2 = PUnitType::DEFAULT expect(t).to be_assignable_to(t2) end end context 'for Any, such that' do it 'all types are assignable to Any' do t = PAnyType::DEFAULT all_types.each { |t2| expect(t2::DEFAULT).to be_assignable_to(t) } end it 'Any is not assignable to anything but Any and Optional (implied Optional[Any])' do tested_types = all_types() - [PAnyType, POptionalType] t = PAnyType::DEFAULT tested_types.each { |t2| expect(t).not_to be_assignable_to(t2::DEFAULT) } end end context "for NotUndef, such that" do it 'all types except types assignable from Undef are assignable to NotUndef' do t = not_undef_t tc = TypeCalculator.singleton undef_t = PUndefType::DEFAULT all_types.each do |c| t2 = c::DEFAULT if tc.assignable?(t2, undef_t) expect(t2).not_to be_assignable_to(t) else expect(t2).to be_assignable_to(t) end end end it 'type NotUndef[T] is assignable from T unless T is assignable from Undef ' do tc = TypeCalculator.singleton undef_t = PUndefType::DEFAULT all_types().select do |c| t2 = c::DEFAULT not_undef_t = not_undef_t(t2) if tc.assignable?(t2, undef_t) expect(t2).not_to be_assignable_to(not_undef_t) else expect(t2).to be_assignable_to(not_undef_t) end end end it 'type T is assignable from NotUndef[T] unless T is assignable from Undef' do tc = TypeCalculator.singleton undef_t = PUndefType::DEFAULT all_types().select do |c| t2 = c::DEFAULT not_undef_t = not_undef_t(t2) unless tc.assignable?(t2, undef_t) expect(not_undef_t).to be_assignable_to(t2) end end end end context "for TypeReference, such that" do it 'no other type is assignable' do t = PTypeReferenceType::DEFAULT all_instances = (all_types - [ PTypeReferenceType, # Avoid comparison with t PTypeAliasType # DEFAULT resolves to PTypeReferenceType::DEFAULT, i.e. t ]).map {|c| c::DEFAULT } # Add a non-empty variant all_instances << variant_t(PAnyType::DEFAULT, PUnitType::DEFAULT) # Add a type alias that doesn't resolve to 't' all_instances << type_alias_t('MyInt', 'Integer').resolve(nil) all_instances.each { |i| expect(i).not_to be_assignable_to(t) } end it 'a TypeReference to the exact same type is assignable' do expect(type_reference_t('Integer[0,10]')).to be_assignable_to(type_reference_t('Integer[0,10]')) end it 'a TypeReference to the different type is not assignable' do expect(type_reference_t('String')).not_to be_assignable_to(type_reference_t('Integer')) end it 'a TypeReference to the different type is not assignable even if the referenced type is' do expect(type_reference_t('Integer[1,2]')).not_to be_assignable_to(type_reference_t('Integer[0,3]')) end end context 'for Data, such that' do let(:data) { TypeFactory.data } data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc| it "it is assignable from #{tc.name}" do expect(tc).to be_assignable_to(data) end end data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc| it "it is assignable from Optional[#{tc.name}]" do expect(optional_t(tc)).to be_assignable_to(data) end end it 'it is not assignable to any of its subtypes' do types_to_test = data_compatible_types types_to_test.each {|t2| expect(data).not_to be_assignable_to(type_from_class(t2)) } end it 'it is not assignable to any disjunct type' do tested_types = all_types - [PAnyType, POptionalType, PInitType] - scalar_data_types tested_types.each {|t2| expect(data).not_to be_assignable_to(t2::DEFAULT) } end end context 'for Rich Data, such that' do let(:rich_data) { TypeFactory.rich_data } rich_data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc| it "it is assignable from #{tc.name}" do expect(tc).to be_assignable_to(rich_data) end end rich_data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc| it "it is assignable from Optional[#{tc.name}]" do expect(optional_t(tc)).to be_assignable_to(rich_data) end end it 'it is not assignable to any of its subtypes' do types_to_test = rich_data_compatible_types types_to_test.each {|t2| expect(rich_data).not_to be_assignable_to(type_from_class(t2)) } end it 'it is not assignable to any disjunct type' do tested_types = all_types - [PAnyType, POptionalType, PInitType] - scalar_types tested_types.each {|t2| expect(rich_data).not_to be_assignable_to(t2::DEFAULT) } end end context 'for Variant, such that' do it 'it is assignable to a type if all contained types are assignable to that type' do v = variant_t(range_t(10, 12),range_t(14, 20)) expect(v).to be_assignable_to(integer_t) expect(v).to be_assignable_to(range_t(10, 20)) # test that both types are assignable to one of the variants OK expect(v).to be_assignable_to(variant_t(range_t(10, 20), range_t(30, 40))) # test where each type is assignable to different types in a variant is OK expect(v).to be_assignable_to(variant_t(range_t(10, 13), range_t(14, 40))) # not acceptable expect(v).not_to be_assignable_to(range_t(0, 4)) expect(v).not_to be_assignable_to(string_t) end it 'an empty Variant is assignable to another empty Variant' do expect(empty_variant_t).to be_assignable_to(empty_variant_t) end it 'an empty Variant is assignable to Any' do expect(empty_variant_t).to be_assignable_to(PAnyType::DEFAULT) end it 'an empty Variant is assignable to Unit' do expect(empty_variant_t).to be_assignable_to(PUnitType::DEFAULT) end it 'an empty Variant is not assignable to any type except empty Variant, Any, NotUndef, and Unit' do assignables = [PUnitType, PAnyType, PNotUndefType] unassignables = all_types - assignables
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/recursion_guard_spec.rb
spec/unit/pops/types/recursion_guard_spec.rb
require 'spec_helper' require 'puppet/pops/types/recursion_guard' module Puppet::Pops::Types describe 'the RecursionGuard' do let(:guard) { RecursionGuard.new } it "should detect recursion in 'this' context" do x = Object.new expect(guard.add_this(x)).to eq(RecursionGuard::NO_SELF_RECURSION) expect(guard.add_this(x)).to eq(RecursionGuard::SELF_RECURSION_IN_THIS) end it "should detect recursion in 'that' context" do x = Object.new expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION) expect(guard.add_that(x)).to eq(RecursionGuard::SELF_RECURSION_IN_THAT) end it "should keep 'this' and 'that' context separate" do x = Object.new expect(guard.add_this(x)).to eq(RecursionGuard::NO_SELF_RECURSION) expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION) end it "should detect when there's a recursion in both 'this' and 'that' context" do x = Object.new y = Object.new expect(guard.add_this(x)).to eq(RecursionGuard::NO_SELF_RECURSION) expect(guard.add_that(y)).to eq(RecursionGuard::NO_SELF_RECURSION) expect(guard.add_this(x)).to eq(RecursionGuard::SELF_RECURSION_IN_THIS) expect(guard.add_that(y)).to eq(RecursionGuard::SELF_RECURSION_IN_BOTH) end it "should report that 'this' is recursive after a recursion has been detected" do x = Object.new guard.add_this(x) guard.add_this(x) expect(guard.recursive_this?(x)).to be_truthy end it "should report that 'that' is recursive after a recursion has been detected" do x = Object.new guard.add_that(x) guard.add_that(x) expect(guard.recursive_that?(x)).to be_truthy end it "should not report that 'this' is recursive after a recursion of 'that' has been detected" do x = Object.new guard.add_that(x) guard.add_that(x) expect(guard.recursive_this?(x)).to be_falsey end it "should not report that 'that' is recursive after a recursion of 'this' has been detected" do x = Object.new guard.add_that(x) guard.add_that(x) expect(guard.recursive_this?(x)).to be_falsey end it "should not call 'hash' on an added instance" do x = double() expect(x).not_to receive(:hash) expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION) end it "should not call '==' on an added instance" do x = double() expect(x).not_to receive(:==) expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION) end it "should not call 'eq?' on an added instance" do x = double() expect(x).not_to receive(:eq?) expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION) end it "should not call 'eql?' on an added instance" do x = double() expect(x).not_to receive(:eql?) expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION) end it "should not call 'equal?' on an added instance" do x = double() expect(x).not_to receive(:equal?) expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/type_factory_spec.rb
spec/unit/pops/types/type_factory_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops module Types describe 'The type factory' do context 'when creating' do it 'integer() returns PIntegerType' do expect(TypeFactory.integer().class()).to eq(PIntegerType) end it 'float() returns PFloatType' do expect(TypeFactory.float().class()).to eq(PFloatType) end it 'string() returns PStringType' do expect(TypeFactory.string().class()).to eq(PStringType) end it 'boolean() returns PBooleanType' do expect(TypeFactory.boolean().class()).to eq(PBooleanType) end it 'pattern() returns PPatternType' do expect(TypeFactory.pattern().class()).to eq(PPatternType) end it 'regexp() returns PRegexpType' do expect(TypeFactory.regexp().class()).to eq(PRegexpType) end it 'enum() returns PEnumType' do expect(TypeFactory.enum().class()).to eq(PEnumType) end it 'variant() returns PVariantType' do expect(TypeFactory.variant().class()).to eq(PVariantType) end it 'scalar() returns PScalarType' do expect(TypeFactory.scalar().class()).to eq(PScalarType) end it 'data() returns Data' do expect(TypeFactory.data.name).to eq('Data') end it 'optional() returns POptionalType' do expect(TypeFactory.optional().class()).to eq(POptionalType) end it 'collection() returns PCollectionType' do expect(TypeFactory.collection().class()).to eq(PCollectionType) end it 'catalog_entry() returns PCatalogEntryType' do expect(TypeFactory.catalog_entry().class()).to eq(PCatalogEntryType) end it 'struct() returns PStructType' do expect(TypeFactory.struct().class()).to eq(PStructType) end it "object() returns PObjectType" do expect(TypeFactory.object.class).to eq(PObjectType) end it 'tuple() returns PTupleType' do expect(TypeFactory.tuple.class()).to eq(PTupleType) end it 'undef() returns PUndefType' do expect(TypeFactory.undef().class()).to eq(PUndefType) end it 'type_alias() returns PTypeAliasType' do expect(TypeFactory.type_alias().class()).to eq(PTypeAliasType) end it 'sem_ver() returns PSemVerType' do expect(TypeFactory.sem_ver.class).to eq(PSemVerType) end it 'sem_ver(r1, r2) returns constrained PSemVerType' do expect(TypeFactory.sem_ver('1.x', '3.x').ranges).to include(SemanticPuppet::VersionRange.parse('1.x'), SemanticPuppet::VersionRange.parse('3.x')) end it 'sem_ver_range() returns PSemVerRangeType' do expect(TypeFactory.sem_ver_range.class).to eq(PSemVerRangeType) end it 'default() returns PDefaultType' do expect(TypeFactory.default().class()).to eq(PDefaultType) end it 'range(to, from) returns PIntegerType' do t = TypeFactory.range(1,2) expect(t.class()).to eq(PIntegerType) expect(t.from).to eq(1) expect(t.to).to eq(2) end it 'range(default, default) returns PIntegerType' do t = TypeFactory.range(:default,:default) expect(t.class()).to eq(PIntegerType) expect(t.from).to eq(nil) expect(t.to).to eq(nil) end it 'float_range(to, from) returns PFloatType' do t = TypeFactory.float_range(1.0, 2.0) expect(t.class()).to eq(PFloatType) expect(t.from).to eq(1.0) expect(t.to).to eq(2.0) end it 'float_range(default, default) returns PFloatType' do t = TypeFactory.float_range(:default, :default) expect(t.class()).to eq(PFloatType) expect(t.from).to eq(nil) expect(t.to).to eq(nil) end it 'resource() creates a generic PResourceType' do pr = TypeFactory.resource() expect(pr.class()).to eq(PResourceType) expect(pr.type_name).to eq(nil) end it 'resource(x) creates a PResourceType[x]' do pr = TypeFactory.resource('x') expect(pr.class()).to eq(PResourceType) expect(pr.type_name).to eq('X') end it 'host_class() creates a generic PClassType' do hc = TypeFactory.host_class() expect(hc.class()).to eq(PClassType) expect(hc.class_name).to eq(nil) end it 'host_class(x) creates a PClassType[x]' do hc = TypeFactory.host_class('x') expect(hc.class()).to eq(PClassType) expect(hc.class_name).to eq('x') end it 'host_class(::x) creates a PClassType[x]' do hc = TypeFactory.host_class('::x') expect(hc.class()).to eq(PClassType) expect(hc.class_name).to eq('x') end it 'array_of(integer) returns PArrayType[PIntegerType]' do at = TypeFactory.array_of(1) expect(at.class()).to eq(PArrayType) expect(at.element_type.class).to eq(PIntegerType) end it 'array_of(PIntegerType) returns PArrayType[PIntegerType]' do at = TypeFactory.array_of(PIntegerType::DEFAULT) expect(at.class()).to eq(PArrayType) expect(at.element_type.class).to eq(PIntegerType) end it 'array_of_data returns Array[Data]' do at = TypeFactory.array_of_data expect(at.class()).to eq(PArrayType) expect(at.element_type.name).to eq('Data') end it 'hash_of_data returns Hash[String,Data]' do ht = TypeFactory.hash_of_data expect(ht.class()).to eq(PHashType) expect(ht.key_type.class).to eq(PStringType) expect(ht.value_type.name).to eq('Data') end it 'ruby(1) returns PRuntimeType[ruby, \'Integer\']' do ht = TypeFactory.ruby(1) expect(ht.class()).to eq(PRuntimeType) expect(ht.runtime).to eq(:ruby) expect(ht.runtime_type_name).to eq(1.class.name) end it 'a size constrained collection can be created from array' do t = TypeFactory.array_of(TypeFactory.data, TypeFactory.range(1,2)) expect(t.size_type.class).to eq(PIntegerType) expect(t.size_type.from).to eq(1) expect(t.size_type.to).to eq(2) end it 'a size constrained collection can be created from hash' do t = TypeFactory.hash_of(TypeFactory.scalar, TypeFactory.data, TypeFactory.range(1,2)) expect(t.size_type.class).to eq(PIntegerType) expect(t.size_type.from).to eq(1) expect(t.size_type.to).to eq(2) end it 'a typed empty array, the resulting array erases the type' do t = Puppet::Pops::Types::TypeFactory.array_of(Puppet::Pops::Types::TypeFactory.data, Puppet::Pops::Types::TypeFactory.range(0,0)) expect(t.size_type.class).to eq(Puppet::Pops::Types::PIntegerType) expect(t.size_type.from).to eq(0) expect(t.size_type.to).to eq(0) expect(t.element_type).to eq(Puppet::Pops::Types::PUnitType::DEFAULT) end it 'a typed empty hash, the resulting hash erases the key and value type' do t = Puppet::Pops::Types::TypeFactory.hash_of(Puppet::Pops::Types::TypeFactory.scalar, Puppet::Pops::Types::TypeFactory.data, Puppet::Pops::Types::TypeFactory.range(0,0)) expect(t.size_type.class).to eq(Puppet::Pops::Types::PIntegerType) expect(t.size_type.from).to eq(0) expect(t.size_type.to).to eq(0) expect(t.key_type).to eq(Puppet::Pops::Types::PUnitType::DEFAULT) expect(t.value_type).to eq(Puppet::Pops::Types::PUnitType::DEFAULT) end context 'callable types' do it 'the callable methods produces a Callable' do t = TypeFactory.callable() expect(t.class).to be(PCallableType) expect(t.param_types.class).to be(PTupleType) expect(t.param_types.types).to be_empty expect(t.block_type).to be_nil end it 'callable method with types produces the corresponding Tuple for parameters and generated names' do tf = TypeFactory t = tf.callable(tf.integer, tf.string) expect(t.class).to be(PCallableType) expect(t.param_types.class).to be(PTupleType) expect(t.param_types.types).to eql([tf.integer, tf.string]) expect(t.block_type).to be_nil end it 'callable accepts min range to be given' do tf = TypeFactory t = tf.callable(tf.integer, tf.string, 1) expect(t.class).to be(PCallableType) expect(t.param_types.class).to be(PTupleType) expect(t.param_types.size_type.from).to eql(1) expect(t.param_types.size_type.to).to be_nil end it 'callable accepts max range to be given' do tf = TypeFactory t = tf.callable(tf.integer, tf.string, 1, 3) expect(t.class).to be(PCallableType) expect(t.param_types.class).to be(PTupleType) expect(t.param_types.size_type.from).to eql(1) expect(t.param_types.size_type.to).to eql(3) end it 'callable accepts max range to be given as :default' do tf = TypeFactory t = tf.callable(tf.integer, tf.string, 1, :default) expect(t.class).to be(PCallableType) expect(t.param_types.class).to be(PTupleType) expect(t.param_types.size_type.from).to eql(1) expect(t.param_types.size_type.to).to be_nil end it 'the all_callables method produces a Callable matching any Callable' do t = TypeFactory.all_callables() expect(t.class).to be(PCallableType) expect(t.param_types).to be_nil expect(t.block_type).to be_nil end it 'with block are created by placing a Callable last' do block_t = TypeFactory.callable(String) t = TypeFactory.callable(String, block_t) expect(t.block_type).to be(block_t) end it 'min size constraint can be used with a block last' do block_t = TypeFactory.callable(String) t = TypeFactory.callable(String, 1, block_t) expect(t.block_type).to be(block_t) expect(t.param_types.size_type.from).to eql(1) expect(t.param_types.size_type.to).to be_nil end it 'min, max size constraint can be used with a block last' do block_t = TypeFactory.callable(String) t = TypeFactory.callable(String, 1, 3, block_t) expect(t.block_type).to be(block_t) expect(t.param_types.size_type.from).to eql(1) expect(t.param_types.size_type.to).to eql(3) end it 'the with_block methods decorates a Callable with a block_type' do t = TypeFactory.callable t2 = TypeFactory.callable(t) block_t = t2.block_type # given t is returned after mutation expect(block_t).to be(t) expect(block_t.class).to be(PCallableType) expect(block_t.param_types.class).to be(PTupleType) expect(block_t.param_types.types).to be_empty expect(block_t.block_type).to be_nil end it 'the with_optional_block methods decorates a Callable with an optional block_type' do b = TypeFactory.callable t = TypeFactory.optional(b) t2 = TypeFactory.callable(t) opt_t = t2.block_type expect(opt_t.class).to be(POptionalType) block_t = opt_t.optional_type # given t is returned after mutation expect(opt_t).to be(t) expect(block_t).to be(b) expect(block_t.class).to be(PCallableType) expect(block_t.param_types.class).to be(PTupleType) expect(block_t.param_types.types).to be_empty expect(block_t.block_type).to be_nil end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/task_spec.rb
spec/unit/pops/types/task_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' require 'puppet/parser/script_compiler' module Puppet::Pops module Types describe 'The Task Type' do include PuppetSpec::Compiler include PuppetSpec::Files context 'when loading' do let(:testing_env) do { 'testing' => { 'modules' => modules, 'manifests' => manifests } } end let(:manifests) { {} } let(:environments_dir) { Puppet[:environmentpath] } let(:testing_env_dir) do dir_contained_in(environments_dir, testing_env) env_dir = File.join(environments_dir, 'testing') PuppetSpec::Files.record_tmp(env_dir) env_dir end let(:modules_dir) { File.join(testing_env_dir, 'modules') } let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) } let(:node) { Puppet::Node.new('test', :environment => env) } let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } } let(:task_t) { TypeFactory.task } before(:each) { Puppet[:tasks] = true } context 'tasks' do let(:compiler) { Puppet::Parser::ScriptCompiler.new(env, node.name) } let(:modules) do { 'testmodule' => testmodule } end let(:module_loader) { Puppet.lookup(:loaders).find_loader('testmodule') } def compile(code = nil) Puppet[:code] = code Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile do |catalog| yield if block_given? catalog end end end context 'without metadata' do let(:testmodule) { { 'tasks' => { 'hello' => <<-RUBY require 'json' args = JSON.parse(STDIN.read) puts({message: args['message']}.to_json) exit 0 RUBY } } } it 'loads task without metadata as a generic Task' do compile do task = module_loader.load(:task, 'testmodule::hello') expect(task_t.instance?(task)).to be_truthy expect(task.name).to eq('testmodule::hello') expect(task._pcore_type).to eq(task_t) end end context 'without --tasks' do before(:each) { Puppet[:tasks] = false } it 'evaluator does not recognize generic tasks' do compile do expect(module_loader.load(:task, 'testmodule::hello')).to be_nil end end end end context 'with metadata' do let(:testmodule) { { 'tasks' => { 'hello.rb' => <<-RUBY, require 'json' args = JSON.parse(STDIN.read) puts({message: args['message']}.to_json) exit 0 RUBY 'hello.json' => <<-JSON, { "puppet_task_version": 1, "supports_noop": true, "parameters": { "message": { "type": "String", "description": "the message", "sensitive": false }, "font": { "type": "Optional[String]" } }} JSON 'non_data.rb' => <<-RUBY, require 'json' args = JSON.parse(STDIN.read) puts({message: args['message']}.to_json) exit 0 RUBY 'non_data.json' => <<-JSON { "puppet_task_version": 1, "supports_noop": true, "parameters": { "arg": { "type": "Hash", "description": "the non data param" } }} JSON } } } it 'loads a task with parameters' do compile do task = module_loader.load(:task, 'testmodule::hello') expect(task_t.instance?(task)).to be_truthy expect(task.name).to eq('testmodule::hello') expect(task._pcore_type).to eq(task_t) expect(task.metadata['supports_noop']).to eql(true) expect(task.metadata['puppet_task_version']).to eql(1) expect(task.files).to eql([{"name" => "hello.rb", "path" => "#{modules_dir}/testmodule/tasks/hello.rb"}]) expect(task.metadata['parameters']['message']['description']).to eql('the message') expect(task.parameters['message']).to be_a(Puppet::Pops::Types::PStringType) end end it 'loads a task with non-Data parameter' do compile do task = module_loader.load(:task, 'testmodule::non_data') expect(task_t.instance?(task)).to be_truthy expect(task.parameters['arg']).to be_a(Puppet::Pops::Types::PHashType) end end context 'without an implementation file' do let(:testmodule) { { 'tasks' => { 'init.json' => '{}' } } } it 'fails to load the task' do compile do expect { module_loader.load(:task, 'testmodule') }.to raise_error(Puppet::Module::Task::InvalidTask, /No source besides task metadata was found/) end end end context 'with multiple implementation files' do let(:metadata) { '{}' } let(:testmodule) { { 'tasks' => { 'init.sh' => '', 'init.ps1' => '', 'init.json' => metadata, } } } it "fails if metadata doesn't specify implementations" do compile do expect { module_loader.load(:task, 'testmodule') }.to raise_error(Puppet::Module::Task::InvalidTask, /Multiple executables were found .*/) end end it "returns the implementations if metadata lists them all" do impls = [{'name' => 'init.sh', 'requirements' => ['shell']}, {'name' => 'init.ps1', 'requirements' => ['powershell']}] metadata.replace({'implementations' => impls}.to_json) compile do task = module_loader.load(:task, 'testmodule') expect(task_t.instance?(task)).to be_truthy expect(task.files).to eql([ {"name" => "init.sh", "path" => "#{modules_dir}/testmodule/tasks/init.sh"}, {"name" => "init.ps1", "path" => "#{modules_dir}/testmodule/tasks/init.ps1"} ]) expect(task.metadata['implementations']).to eql([ {"name" => "init.sh", "requirements" => ['shell']}, {"name" => "init.ps1", "requirements" => ['powershell']} ]) end end it "returns a single implementation if metadata only specifies one implementation" do impls = [{'name' => 'init.ps1', 'requirements' => ['powershell']}] metadata.replace({'implementations' => impls}.to_json) compile do task = module_loader.load(:task, 'testmodule') expect(task_t.instance?(task)).to be_truthy expect(task.files).to eql([ {"name" => "init.ps1", "path" => "#{modules_dir}/testmodule/tasks/init.ps1"} ]) expect(task.metadata['implementations']).to eql([ {"name" => "init.ps1", "requirements" => ['powershell']} ]) end end it "fails if a specified implementation doesn't exist" do impls = [{'name' => 'init.sh', 'requirements' => ['shell']}, {'name' => 'init.ps1', 'requirements' => ['powershell']}, {'name' => 'init.rb', 'requirements' => ['puppet-agent']}] metadata.replace({'implementations' => impls}.to_json) compile do expect { module_loader.load(:task, 'testmodule') }.to raise_error(Puppet::Module::Task::InvalidTask, /Task metadata for task testmodule specifies missing implementation init\.rb/) end end it "fails if the implementations key isn't an array" do metadata.replace({'implementations' => {'init.rb' => []}}.to_json) compile do expect { module_loader.load(:task, 'testmodule') }.to raise_error(Puppet::Module::Task::InvalidMetadata, /Task metadata for task testmodule does not specify implementations as an array/) end end end context 'with multiple tasks sharing executables' do let(:foo_metadata) { '{}' } let(:bar_metadata) { '{}' } let(:testmodule) { { 'tasks' => { 'foo.sh' => '', 'foo.ps1' => '', 'foo.json' => foo_metadata, 'bar.json' => bar_metadata, 'baz.json' => bar_metadata, } } } it 'loads a task that uses executables named after another task' do metadata = { implementations: [ {name: 'foo.sh', requirements: ['shell']}, {name: 'foo.ps1', requirements: ['powershell']}, ] } bar_metadata.replace(metadata.to_json) compile do task = module_loader.load(:task, 'testmodule::bar') expect(task.files).to eql([ {'name' => 'foo.sh', 'path' => "#{modules_dir}/testmodule/tasks/foo.sh"}, {'name' => 'foo.ps1', 'path' => "#{modules_dir}/testmodule/tasks/foo.ps1"}, ]) end end it 'fails to load the task if it has no implementations section and no associated executables' do compile do expect { module_loader.load(:task, 'testmodule::bar') }.to raise_error(Puppet::Module::Task::InvalidTask, /No source besides task metadata was found/) end end it 'fails to load the task if it has no files at all' do compile do expect(module_loader.load(:task, 'testmodule::qux')).to be_nil end end end context 'with adjacent directory for init task' do let(:testmodule) { { 'tasks' => { 'init' => { 'foo.sh' => 'echo hello' }, 'init.sh' => 'echo hello', 'init.json' => <<-JSON { "supports_noop": true, "parameters": { "message": { "type": "String" } } } JSON } } } it 'loads the init task with parameters and implementations' do compile do task = module_loader.load(:task, 'testmodule') expect(task_t.instance?(task)).to be_truthy expect(task.files).to eql([{"name" => "init.sh", "path" => "#{modules_dir}/testmodule/tasks/init.sh"}]) expect(task.metadata['parameters']).to be_a(Hash) expect(task.parameters['message']).to be_a(Puppet::Pops::Types::PStringType) end end end context 'with adjacent directory for named task' do let(:testmodule) { { 'tasks' => { 'hello' => { 'foo.sh' => 'echo hello' }, 'hello.sh' => 'echo hello', 'hello.json' => <<-JSON { "supports_noop": true, "parameters": { "message": { "type": "String" } } } JSON } } } it 'loads a named task with parameters and implementations' do compile do task = module_loader.load(:task, 'testmodule::hello') expect(task_t.instance?(task)).to be_truthy expect(task.files).to eql([{"name" => "hello.sh", "path" => "#{modules_dir}/testmodule/tasks/hello.sh"}]) expect(task.metadata['parameters']).to be_a(Hash) expect(task.parameters['message']).to be_a(Puppet::Pops::Types::PStringType) end end end context 'using more than two segments in the name' do let(:testmodule) { { 'tasks' => { 'hello' => { 'foo.sh' => 'echo hello' } } } } it 'task is not found' do compile do expect(module_loader.load(:task, 'testmodule::hello::foo')).to be_nil end end end context 'that has no parameters' do let(:testmodule) { { 'tasks' => { 'hello' => 'echo hello', 'hello.json' => '{ "supports_noop": false }' } } } it 'loads the task with parameters set to undef' do compile do task = module_loader.load(:task, 'testmodule::hello') expect(task_t.instance?(task)).to be_truthy expect(task.metadata['parameters']).to be_nil end end end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/deferred_spec.rb
spec/unit/pops/types/deferred_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Deferred type' do context 'when used in Puppet expressions' do include PuppetSpec::Compiler it 'is equal to itself only' do expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true false false)) $t = Deferred notice(Deferred =~ Type[Deferred]) notice(Deferred == Deferred) notice(Deferred < Deferred) notice(Deferred > Deferred) CODE end context 'a Deferred instance' do it 'can be created using positional arguments' do code = <<-CODE $o = Deferred('michelangelo', [1,2,3]) notice($o) CODE expect(eval_and_collect_notices(code)).to eq([ "Deferred({'name' => 'michelangelo', 'arguments' => [1, 2, 3]})" ]) end it 'can be created using named arguments' do code = <<-CODE $o = Deferred(name =>'michelangelo', arguments => [1,2,3]) notice($o) CODE expect(eval_and_collect_notices(code)).to eq([ "Deferred({'name' => 'michelangelo', 'arguments' => [1, 2, 3]})" ]) end it 'is inferred to have the type Deferred' do pending 'bug in type() function outputs the entire pcore definition' code = <<-CODE $o = Deferred('michelangelo', [1,2,3]) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq([ "Deferred" ]) end it 'exposes name' do code = <<-CODE $o = Deferred(name =>'michelangelo', arguments => [1,2,3]) notice($o.name) CODE expect(eval_and_collect_notices(code)).to eq(["michelangelo"]) end it 'exposes arguments' do code = <<-CODE $o = Deferred(name =>'michelangelo', arguments => [1,2,3]) notice($o.arguments) CODE expect(eval_and_collect_notices(code)).to eq(["[1, 2, 3]"]) end it 'is an instance of its inferred type' do code = <<-CODE $o = Deferred(name =>'michelangelo', arguments => [1,2,3]) notice($o =~ type($o)) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'is an instance of Deferred' do code = <<-CODE $o = Deferred(name =>'michelangelo', arguments => [1,2,3]) notice($o =~ Deferred) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/type_acceptor_spec.rb
spec/unit/pops/types/type_acceptor_spec.rb
require 'spec_helper' require 'puppet/pops/types/type_acceptor' class PuppetSpec::TestTypeAcceptor include Puppet::Pops::Types::TypeAcceptor attr_reader :visitors, :guard def initialize @visitors = [] @guard = nil end def visit(type, guard) @visitors << type @guard = guard end end module Puppet::Pops::Types describe 'the Puppet::Pops::Types::TypeAcceptor' do let!(:acceptor_class) { PuppetSpec::TestTypeAcceptor } let(:acceptor) { acceptor_class.new } let(:guard) { RecursionGuard.new } it "should get a visit from the type that accepts it" do PAnyType::DEFAULT.accept(acceptor, nil) expect(acceptor.visitors).to include(PAnyType::DEFAULT) end it "should receive the guard as an argument" do PAnyType::DEFAULT.accept(acceptor, guard) expect(acceptor.guard).to equal(guard) end it "should get a visit from the type of a Type that accepts it" do t = PTypeType.new(PAnyType::DEFAULT) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PAnyType::DEFAULT) end [ PTypeType, PNotUndefType, PIterableType, PIteratorType, POptionalType ].each do |tc| it "should get a visit from the contained type of an #{tc.class.name} that accepts it" do t = tc.new(PStringType::DEFAULT) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PStringType::DEFAULT) end end it "should get a visit from the size type of String type that accepts it" do sz = PIntegerType.new(0,4) t = PStringType.new(sz) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, sz) end it "should get a visit from all contained types of an Array type that accepts it" do sz = PIntegerType.new(0,4) t = PArrayType.new(PAnyType::DEFAULT, sz) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PAnyType::DEFAULT, sz) end it "should get a visit from all contained types of a Hash type that accepts it" do sz = PIntegerType.new(0,4) t = PHashType.new(PStringType::DEFAULT, PAnyType::DEFAULT, sz) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PAnyType::DEFAULT, sz) end it "should get a visit from all contained types of a Tuple type that accepts it" do sz = PIntegerType.new(0,4) t = PTupleType.new([PStringType::DEFAULT, PIntegerType::DEFAULT], sz) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT, sz) end it "should get a visit from all contained types of a Struct type that accepts it" do t = PStructType.new([PStructElement.new(PStringType::DEFAULT, PIntegerType::DEFAULT)]) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT) end it "should get a visit from all contained types of a Callable type that accepts it" do sz = PIntegerType.new(0,4) args = PTupleType.new([PStringType::DEFAULT, PIntegerType::DEFAULT], sz) block = PCallableType::DEFAULT t = PCallableType.new(args, block) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT, sz, args, block) end it "should get a visit from all contained types of a Variant type that accepts it" do t = PVariantType.new([PStringType::DEFAULT, PIntegerType::DEFAULT]) t.accept(acceptor, nil) expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_sensitive_type_spec.rb
spec/unit/pops/types/p_sensitive_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Sensitive Type' do include PuppetSpec::Compiler context 'as a type' do it 'can be created without a parameter with the type factory' do t = TypeFactory.sensitive expect(t).to be_a(PSensitiveType) expect(t).to eql(PSensitiveType::DEFAULT) end it 'can be created with a parameter with the type factory' do t = TypeFactory.sensitive(PIntegerType::DEFAULT) expect(t).to be_a(PSensitiveType) expect(t.type).to eql(PIntegerType::DEFAULT) end it 'string representation of unparameterized instance is "Sensitive"' do expect(PSensitiveType::DEFAULT.to_s).to eql('Sensitive') end context 'when used in Puppet expressions' do it 'is equal to itself only' do code = <<-CODE $t = Sensitive notice(Sensitive =~ Type[ Sensitive ]) notice(Sensitive == Sensitive) notice(Sensitive < Sensitive) notice(Sensitive > Sensitive) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false', 'false']) end context "when parameterized" do it 'is equal other types with the same parameterization' do code = <<-CODE notice(Sensitive[String] == Sensitive[String]) notice(Sensitive[Numeric] != Sensitive[Integer]) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'true']) end it 'orders parameterized types based on the type system hierarchy' do code = <<-CODE notice(Sensitive[Numeric] > Sensitive[Integer]) notice(Sensitive[Numeric] < Sensitive[Integer]) CODE expect(eval_and_collect_notices(code)).to eq(['true', 'false']) end it 'does not order incomparable parameterized types' do code = <<-CODE notice(Sensitive[String] < Sensitive[Integer]) notice(Sensitive[String] > Sensitive[Integer]) CODE expect(eval_and_collect_notices(code)).to eq(['false', 'false']) end it 'generalizes passed types to prevent information leakage' do code =<<-CODE $it = String[7, 7] $st = Sensitive[$it] notice(type($st)) CODE expect(eval_and_collect_notices(code)).to eq(['Type[Sensitive[String]]']) end end end end context 'a Sensitive instance' do it 'can be created from a string and does not leak its contents' do code =<<-CODE $o = Sensitive("hunter2") notice($o) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]', 'Sensitive[String]']) end it 'matches the appropriate parameterized type' do code =<<-CODE $o = Sensitive("hunter2") notice(assert_type(Sensitive[String], $o)) notice(assert_type(Sensitive[String[7, 7]], $o)) CODE expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]', 'Sensitive [value redacted]']) end it 'verifies the constrains of the parameterized type' do pending "the ability to enforce constraints without leaking information" code =<<-CODE $o = Sensitive("hunter2") notice(assert_type(Sensitive[String[10, 20]], $o)) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects a Sensitive\[String\[10, 20\]\] value, got Sensitive\[String\[7, 7\]\]/) end it 'does not match an inappropriate parameterized type' do code =<<-CODE $o = Sensitive("hunter2") notice(assert_type(Sensitive[Integer], $o) |$expected, $actual| { "$expected != $actual" }) CODE expect(eval_and_collect_notices(code)).to eq(['Sensitive[Integer] != Sensitive[String]']) end it 'equals another instance with the same value' do code =<<-CODE $i = Sensitive('secret') $o = Sensitive('secret') notice($i == $o) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'has equal hash keys for same values' do code =<<-CODE $i = Sensitive('secret') $o = Sensitive('secret') notice({$i => 1} == {$o => 1}) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'can be created from another sensitive instance ' do code =<<-CODE $o = Sensitive("hunter2") $x = Sensitive($o) notice(assert_type(Sensitive[String], $x)) CODE expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]']) end it 'can be given to a user defined resource as a parameter' do code =<<-CODE define keeper_of_secrets(Sensitive $x) { notice(assert_type(Sensitive[String], $x)) } keeper_of_secrets { 'test': x => Sensitive("long toe") } CODE expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]']) end it 'can be given to a class as a parameter' do code =<<-CODE class keeper_of_secrets(Sensitive $x) { notice(assert_type(Sensitive[String], $x)) } class { 'keeper_of_secrets': x => Sensitive("long toe") } CODE expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]']) end it 'can be given to a function as a parameter' do code =<<-CODE function keeper_of_secrets(Sensitive $x) { notice(assert_type(Sensitive[String], $x)) } keeper_of_secrets(Sensitive("long toe")) CODE expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]']) end end it "enforces wrapped type constraints" do pending "the ability to enforce constraints without leaking information" code =<<-CODE class secrets_handler(Sensitive[Array[String[4, 8]]] $pwlist) { notice($pwlist) } class { "secrets_handler": pwlist => Sensitive(['hi', 'longlonglong']) } CODE expect { expect(eval_and_collect_notices(code)) }.to raise_error(Puppet::Error, /expects a String\[4, 8\], got String/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/error_spec.rb
spec/unit/pops/types/error_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Error type' do context 'when used in Puppet expressions' do include PuppetSpec::Compiler it 'is equal to itself only' do expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true false false)) $t = Error notice(Error =~ Type[Error]) notice(Error == Error) notice(Error < Error) notice(Error > Error) CODE end context "when parameterized" do it 'is equal other types with the same parameterization' do code = <<-CODE notice(Error['puppet/error'] == Error['puppet/error', default]) notice(Error['puppet/error', 'ouch'] == Error['puppet/error', 'ouch']) notice(Error['puppet/error', 'ouch'] != Error['puppet/error', 'ouch!']) CODE expect(eval_and_collect_notices(code)).to eq(%w(true true true)) end it 'is assignable from more qualified types' do expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true true)) notice(Error > Error['puppet/error']) notice(Error['puppet/error'] > Error['puppet/error', 'ouch']) notice(Error['puppet/error', default] > Error['puppet/error', 'ouch']) CODE end it 'is not assignable unless kind is assignable' do expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true false true false true false true)) notice(Error[/a/] > Error['hah']) notice(Error[/a/] > Error['hbh']) notice(Error[Enum[a,b,c]] > Error[a]) notice(Error[Enum[a,b,c]] > Error[d]) notice(Error[Pattern[/a/, /b/]] > Error[a]) notice(Error[Pattern[/a/, /b/]] > Error[c]) notice(Error[Pattern[/a/, /b/]] > Error[Enum[a, b]]) CODE end it 'presents parsable string form' do code = <<-CODE notice(Error['a']) notice(Error[/a/]) notice(Error[Enum['a', 'b']]) notice(Error[Pattern[/a/, /b/]]) notice(Error['a', default]) notice(Error[/a/, default]) notice(Error[Enum['a', 'b'], default]) notice(Error[Pattern[/a/, /b/], default]) notice(Error[default,'a']) notice(Error[default,/a/]) notice(Error[default,Enum['a', 'b']]) notice(Error[default,Pattern[/a/, /b/]]) notice(Error['a','a']) notice(Error[/a/,/a/]) notice(Error[Enum['a', 'b'],Enum['a', 'b']]) notice(Error[Pattern[/a/, /b/],Pattern[/a/, /b/]]) CODE expect(eval_and_collect_notices(code)).to eq([ "Error['a']", 'Error[/a/]', "Error[Enum['a', 'b']]", "Error[Pattern[/a/, /b/]]", "Error['a']", 'Error[/a/]', "Error[Enum['a', 'b']]", "Error[Pattern[/a/, /b/]]", "Error[default, 'a']", 'Error[default, /a/]', "Error[default, Enum['a', 'b']]", "Error[default, Pattern[/a/, /b/]]", "Error['a', 'a']", 'Error[/a/, /a/]', "Error[Enum['a', 'b'], Enum['a', 'b']]", "Error[Pattern[/a/, /b/], Pattern[/a/, /b/]]", ]) end end context 'an Error instance' do it 'can be created using positional arguments' do code = <<-CODE $o = Error('bad things happened', 'puppet/error', {'detail' => 'val'}, 'OOPS') notice($o) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq([ "Error({'msg' => 'bad things happened', 'kind' => 'puppet/error', 'details' => {'detail' => 'val'}, 'issue_code' => 'OOPS'})", "Error['puppet/error', 'OOPS']" ]) end it 'can be created using named arguments' do code = <<-CODE $o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED') notice($o) notice(type($o)) CODE expect(eval_and_collect_notices(code)).to eq([ "Error({'msg' => 'Sorry, not implemented', 'kind' => 'puppet/error', 'issue_code' => 'NOT_IMPLEMENTED'})", "Error['puppet/error', 'NOT_IMPLEMENTED']" ]) end it 'exposes message' do code = <<-CODE $o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED') notice($o.message) CODE expect(eval_and_collect_notices(code)).to eq(["Sorry, not implemented"]) end it 'exposes kind' do code = <<-CODE $o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED') notice($o.kind) CODE expect(eval_and_collect_notices(code)).to eq(["puppet/error"]) end it 'exposes issue_code' do code = <<-CODE $o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED') notice($o.issue_code) CODE expect(eval_and_collect_notices(code)).to eq(["NOT_IMPLEMENTED"]) end it 'exposes details' do code = <<-CODE $o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', details => { 'detailk' => 'detailv' }) notice($o.details) CODE expect(eval_and_collect_notices(code)).to eq(["{detailk => detailv}"]) end it 'is an instance of its inferred type' do code = <<-CODE $o = Error('bad things happened', 'puppet/error') notice($o =~ type($o)) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'is an instance of Error with matching kind' do code = <<-CODE $o = Error('bad things happened', 'puppet/error') notice($o =~ Error[/puppet\\/error/]) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'is an instance of Error with matching issue_code' do code = <<-CODE $o = Error('bad things happened', 'puppet/error', {}, 'FEE') notice($o =~ Error[default, 'FEE']) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'is an instance of Error with matching kind and issue_code' do code = <<-CODE $o = Error('bad things happened', 'puppet/error', {}, 'FEE') notice($o =~ Error['puppet/error', 'FEE']) CODE expect(eval_and_collect_notices(code)).to eq(['true']) end it 'is not an instance of Error unless kind matches' do code = <<-CODE $o = Error('bad things happened', 'puppetlabs/error') notice($o =~ Error[/puppet\\/error/]) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'is not an instance of Error unless issue_code matches' do code = <<-CODE $o = Error('bad things happened', 'puppetlabs/error', {}, 'BAR') notice($o =~ Error[default, 'FOO']) CODE expect(eval_and_collect_notices(code)).to eq(['false']) end it 'is not an instance of Error unless both kind and issue is a match' do code = <<-CODE $o = Error('bad things happened', 'puppet/error', {}, 'FEE') notice($o =~ Error['puppetlabs/error', 'FEE']) notice($o =~ Error['puppet/error', 'FUM']) CODE expect(eval_and_collect_notices(code)).to eq(['false', 'false']) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/class_loader_spec.rb
spec/unit/pops/types/class_loader_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'the Puppet::Pops::Types::ClassLoader' do it 'should produce path alternatives for CamelCase classes' do expected_paths = ['puppet_x/some_thing', 'puppetx/something'] # path_for_name method is private expect(Puppet::Pops::Types::ClassLoader.send(:paths_for_name, ['PuppetX', 'SomeThing'])).to include(*expected_paths) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/type_formatter_spec.rb
spec/unit/pops/types/type_formatter_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops::Types describe 'The type formatter' do let(:s) { TypeFormatter.new } let(:f) { TypeFactory } def drop_indent(str) ld = str.index("\n") if ld.nil? str else str.gsub(Regexp.compile("^ {#{ld - 1}}"), '') end end context 'when representing a literal as a string' do { 'true' => true, 'false' => false, 'undef' => nil, '23.4' => 23.4, '145' => 145, "'string'" => 'string', '/expr/' => /expr/, '[1, 2, 3]' => [1, 2, 3], "{'a' => 32, 'b' => [1, 2, 3]}" => {'a' => 32,'b' => [1, 2, 3]} }.each_pair do |str, value| it "should yield '#{str}' for a value of #{str}" do expect(s.string(value)).to eq(str) end end end context 'when using indent' do it 'should put hash entries on new indented lines' do expect(s.indented_string({'a' => 32,'b' => [1, 2, {'c' => 'd'}]})).to eq(<<-FORMATTED) { 'a' => 32, 'b' => [ 1, 2, { 'c' => 'd' } ] } FORMATTED end it 'should start on given indent level' do expect(s.indented_string({'a' => 32,'b' => [1, 2, {'c' => 'd'}]}, 3)).to eq(<<-FORMATTED) { 'a' => 32, 'b' => [ 1, 2, { 'c' => 'd' } ] } FORMATTED end it 'should use given indent width' do expect(s.indented_string({'a' => 32,'b' => [1, 2, {'c' => 'd'}]}, 2, 4)).to eq(<<-FORMATTED) { 'a' => 32, 'b' => [ 1, 2, { 'c' => 'd' } ] } FORMATTED end end context 'when representing the type as string' do include_context 'types_setup' it "should yield 'Type' for PTypeType" do expect(s.string(f.type_type)).to eq('Type') end it "should yield 'Any' for PAnyType" do expect(s.string(f.any)).to eq('Any') end it "should yield 'Scalar' for PScalarType" do expect(s.string(f.scalar)).to eq('Scalar') end it "should yield 'Boolean' for PBooleanType" do expect(s.string(f.boolean)).to eq('Boolean') end it "should yield 'Boolean[true]' for PBooleanType parameterized with true" do expect(s.string(f.boolean(true))).to eq('Boolean[true]') end it "should yield 'Boolean[false]' for PBooleanType parameterized with false" do expect(s.string(f.boolean(false))).to eq('Boolean[false]') end it "should yield 'Data' for the Data type" do expect(s.string(f.data)).to eq('Data') end it "should yield 'Numeric' for PNumericType" do expect(s.string(f.numeric)).to eq('Numeric') end it "should yield 'Integer' and from/to for PIntegerType" do expect(s.string(f.integer)).to eq('Integer') expect(s.string(f.range(1,1))).to eq('Integer[1, 1]') expect(s.string(f.range(1,2))).to eq('Integer[1, 2]') expect(s.string(f.range(:default, 2))).to eq('Integer[default, 2]') expect(s.string(f.range(2, :default))).to eq('Integer[2]') end it "should yield 'Float' for PFloatType" do expect(s.string(f.float)).to eq('Float') end it "should yield 'Regexp' for PRegexpType" do expect(s.string(f.regexp)).to eq('Regexp') end it "should yield 'Regexp[/pat/]' for parameterized PRegexpType" do expect(s.string(f.regexp('a/b'))).to eq('Regexp[/a\/b/]') end it "should yield 'String' for PStringType" do expect(s.string(f.string)).to eq('String') end it "should yield 'String' for PStringType with value" do expect(s.string(f.string('a'))).to eq('String') end it "should yield 'String['a']' for PStringType with value if printed with debug_string" do expect(s.debug_string(f.string('a'))).to eq("String['a']") end it "should yield 'String' and from/to for PStringType" do expect(s.string(f.string(f.range(1,1)))).to eq('String[1, 1]') expect(s.string(f.string(f.range(1,2)))).to eq('String[1, 2]') expect(s.string(f.string(f.range(:default, 2)))).to eq('String[0, 2]') expect(s.string(f.string(f.range(2, :default)))).to eq('String[2]') end it "should yield 'Array[Integer]' for PArrayType[PIntegerType]" do expect(s.string(f.array_of(f.integer))).to eq('Array[Integer]') end it "should yield 'Array' for PArrayType::DEFAULT" do expect(s.string(f.array_of_any)).to eq('Array') end it "should yield 'Array[0, 0]' for an empty array" do t = f.array_of(PUnitType::DEFAULT, f.range(0,0)) expect(s.string(t)).to eq('Array[0, 0]') end it "should yield 'Hash[0, 0]' for an empty hash" do t = f.hash_of(PUnitType::DEFAULT, PUnitType::DEFAULT, f.range(0,0)) expect(s.string(t)).to eq('Hash[0, 0]') end it "should yield 'Collection' and from/to for PCollectionType" do expect(s.string(f.collection(f.range(1,1)))).to eq('Collection[1, 1]') expect(s.string(f.collection(f.range(1,2)))).to eq('Collection[1, 2]') expect(s.string(f.collection(f.range(:default, 2)))).to eq('Collection[0, 2]') expect(s.string(f.collection(f.range(2, :default)))).to eq('Collection[2]') end it "should yield 'Array' and from/to for PArrayType" do expect(s.string(f.array_of(f.string, f.range(1,1)))).to eq('Array[String, 1, 1]') expect(s.string(f.array_of(f.string, f.range(1,2)))).to eq('Array[String, 1, 2]') expect(s.string(f.array_of(f.string, f.range(:default, 2)))).to eq('Array[String, 0, 2]') expect(s.string(f.array_of(f.string, f.range(2, :default)))).to eq('Array[String, 2]') end it "should yield 'Iterable' for PIterableType" do expect(s.string(f.iterable)).to eq('Iterable') end it "should yield 'Iterable[Integer]' for PIterableType[PIntegerType]" do expect(s.string(f.iterable(f.integer))).to eq('Iterable[Integer]') end it "should yield 'Iterator' for PIteratorType" do expect(s.string(f.iterator)).to eq('Iterator') end it "should yield 'Iterator[Integer]' for PIteratorType[PIntegerType]" do expect(s.string(f.iterator(f.integer))).to eq('Iterator[Integer]') end it "should yield 'Timespan' for PTimespanType" do expect(s.string(f.timespan())).to eq('Timespan') end it "should yield 'Timespan[{hours => 1}] for PTimespanType[Timespan]" do expect(s.string(f.timespan({'hours' => 1}))).to eq("Timespan['0-01:00:00.0']") end it "should yield 'Timespan[default, {hours => 2}] for PTimespanType[nil, Timespan]" do expect(s.string(f.timespan(nil, {'hours' => 2}))).to eq("Timespan[default, '0-02:00:00.0']") end it "should yield 'Timespan[{hours => 1}, {hours => 2}] for PTimespanType[Timespan, Timespan]" do expect(s.string(f.timespan({'hours' => 1}, {'hours' => 2}))).to eq("Timespan['0-01:00:00.0', '0-02:00:00.0']") end it "should yield 'Timestamp' for PTimestampType" do expect(s.string(f.timestamp())).to eq('Timestamp') end it "should yield 'Timestamp['2016-09-05T13:00:00.000 UTC'] for PTimestampType[Timestamp]" do expect(s.string(f.timestamp('2016-09-05T13:00:00.000 UTC'))).to eq("Timestamp['2016-09-05T13:00:00.000000000 UTC']") end it "should yield 'Timestamp[default, '2016-09-05T13:00:00.000 UTC'] for PTimestampType[nil, Timestamp]" do expect(s.string(f.timestamp(nil, '2016-09-05T13:00:00.000 UTC'))).to eq("Timestamp[default, '2016-09-05T13:00:00.000000000 UTC']") end it "should yield 'Timestamp['2016-09-05T13:00:00.000 UTC', '2016-12-01T00:00:00.000 UTC'] for PTimestampType[Timestamp, Timestamp]" do expect(s.string(f.timestamp('2016-09-05T13:00:00.000 UTC', '2016-12-01T00:00:00.000 UTC'))).to( eq("Timestamp['2016-09-05T13:00:00.000000000 UTC', '2016-12-01T00:00:00.000000000 UTC']")) end it "should yield 'Tuple[Integer]' for PTupleType[PIntegerType]" do expect(s.string(f.tuple([f.integer]))).to eq('Tuple[Integer]') end it "should yield 'Tuple[T, T,..]' for PTupleType[T, T, ...]" do expect(s.string(f.tuple([f.integer, f.integer, f.string]))).to eq('Tuple[Integer, Integer, String]') end it "should yield 'Tuple' and from/to for PTupleType" do types = [f.string] expect(s.string(f.tuple(types, f.range(1,1)))).to eq('Tuple[String, 1, 1]') expect(s.string(f.tuple(types, f.range(1,2)))).to eq('Tuple[String, 1, 2]') expect(s.string(f.tuple(types, f.range(:default, 2)))).to eq('Tuple[String, 0, 2]') expect(s.string(f.tuple(types, f.range(2, :default)))).to eq('Tuple[String, 2]') end it "should yield 'Struct' and details for PStructType" do struct_t = f.struct({'a'=>Integer, 'b'=>String}) expect(s.string(struct_t)).to eq("Struct[{'a' => Integer, 'b' => String}]") struct_t = f.struct({}) expect(s.string(struct_t)).to eq('Struct') end it "should yield 'Hash[String, Integer]' for PHashType[PStringType, PIntegerType]" do expect(s.string(f.hash_of(f.integer, f.string))).to eq('Hash[String, Integer]') end it "should yield 'Hash' and from/to for PHashType" do expect(s.string(f.hash_of(f.string, f.string, f.range(1,1)))).to eq('Hash[String, String, 1, 1]') expect(s.string(f.hash_of(f.string, f.string, f.range(1,2)))).to eq('Hash[String, String, 1, 2]') expect(s.string(f.hash_of(f.string, f.string, f.range(:default, 2)))).to eq('Hash[String, String, 0, 2]') expect(s.string(f.hash_of(f.string, f.string, f.range(2, :default)))).to eq('Hash[String, String, 2]') end it "should yield 'Hash' for PHashType::DEFAULT" do expect(s.string(f.hash_of_any)).to eq('Hash') end it "should yield 'Class' for a PClassType" do expect(s.string(f.host_class)).to eq('Class') end it "should yield 'Class[x]' for a PClassType[x]" do expect(s.string(f.host_class('x'))).to eq('Class[x]') end it "should yield 'Resource' for a PResourceType" do expect(s.string(f.resource)).to eq('Resource') end it "should yield 'File' for a PResourceType['File']" do expect(s.string(f.resource('File'))).to eq('File') end it "should yield 'File['/tmp/foo']' for a PResourceType['File', '/tmp/foo']" do expect(s.string(f.resource('File', '/tmp/foo'))).to eq("File['/tmp/foo']") end it "should yield 'Enum[s,...]' for a PEnumType[s,...]" do t = f.enum('a', 'b', 'c') expect(s.string(t)).to eq("Enum['a', 'b', 'c']") end it "should yield 'Enum[s,...]' for a PEnumType[s,...,false]" do t = f.enum('a', 'b', 'c', false) expect(s.string(t)).to eq("Enum['a', 'b', 'c']") end it "should yield 'Enum[s,...,true]' for a PEnumType[s,...,true]" do t = f.enum('a', 'b', 'c', true) expect(s.string(t)).to eq("Enum['a', 'b', 'c', true]") end it "should yield 'Pattern[/pat/,...]' for a PPatternType['pat',...]" do t = f.pattern('a') t2 = f.pattern('a', 'b', 'c') expect(s.string(t)).to eq('Pattern[/a/]') expect(s.string(t2)).to eq('Pattern[/a/, /b/, /c/]') end it "should escape special characters in the string for a PPatternType['pat',...]" do t = f.pattern('a/b') expect(s.string(t)).to eq("Pattern[/a\\/b/]") end it "should yield 'Variant[t1,t2,...]' for a PVariantType[t1, t2,...]" do t1 = f.string t2 = f.integer t3 = f.pattern('a') t = f.variant(t1, t2, t3) expect(s.string(t)).to eq('Variant[String, Integer, Pattern[/a/]]') end it "should yield 'Callable' for generic callable" do expect(s.string(f.all_callables)).to eql('Callable') end it "should yield 'Callable[0,0]' for callable without params" do expect(s.string(f.callable)).to eql('Callable[0, 0]') end it "should yield 'Callable[[0,0],rt]' for callable without params but with return type" do expect(s.string(f.callable([], Float))).to eql('Callable[[0, 0], Float]') end it "should yield 'Callable[t,t]' for callable with typed parameters" do expect(s.string(f.callable(String, Integer))).to eql('Callable[String, Integer]') end it "should yield 'Callable[[t,t],rt]' for callable with typed parameters and return type" do expect(s.string(f.callable([String, Integer], Float))).to eql('Callable[[String, Integer], Float]') end it "should yield 'Callable[t,min,max]' for callable with size constraint (infinite max)" do expect(s.string(f.callable(String, 0))).to eql('Callable[String, 0]') end it "should yield 'Callable[t,min,max]' for callable with size constraint (capped max)" do expect(s.string(f.callable(String, 0, 3))).to eql('Callable[String, 0, 3]') end it "should yield 'Callable[min,max]' callable with size > 0" do expect(s.string(f.callable(0, 0))).to eql('Callable[0, 0]') expect(s.string(f.callable(0, 1))).to eql('Callable[0, 1]') expect(s.string(f.callable(0, :default))).to eql('Callable[0]') end it "should yield 'Callable[Callable]' for callable with block" do expect(s.string(f.callable(f.all_callables))).to eql('Callable[0, 0, Callable]') expect(s.string(f.callable(f.string, f.all_callables))).to eql('Callable[String, Callable]') expect(s.string(f.callable(f.string, 1,1, f.all_callables))).to eql('Callable[String, 1, 1, Callable]') end it 'should yield Unit for a Unit type' do expect(s.string(PUnitType::DEFAULT)).to eql('Unit') end it "should yield 'NotUndef' for a PNotUndefType" do t = f.not_undef expect(s.string(t)).to eq('NotUndef') end it "should yield 'NotUndef[T]' for a PNotUndefType[T]" do t = f.not_undef(f.data) expect(s.string(t)).to eq('NotUndef[Data]') end it "should yield 'NotUndef['string']' for a PNotUndefType['string']" do t = f.not_undef('hey') expect(s.string(t)).to eq("NotUndef['hey']") end it "should yield the name of an unparameterized type reference" do t = f.type_reference('What') expect(s.string(t)).to eq("TypeReference['What']") end it "should yield the name and arguments of an parameterized type reference" do t = f.type_reference('What[Undef, String]') expect(s.string(t)).to eq("TypeReference['What[Undef, String]']") end it "should yield the name of a type alias" do t = f.type_alias('Alias', 'Integer') expect(s.string(t)).to eq('Alias') end it "should yield 'Type[Runtime[ruby, Puppet]]' for the Puppet module" do expect(s.string(Puppet)).to eq("Runtime[ruby, 'Puppet']") end it "should yield 'Type[Runtime[ruby, Puppet::Pops]]' for the Puppet::Resource class" do expect(s.string(Puppet::Resource)).to eq("Runtime[ruby, 'Puppet::Resource']") end it "should yield \"SemVer['1.x', '3.x']\" for the PSemVerType['1.x', '3.x']" do expect(s.string(PSemVerType.new(['1.x', '3.x']))).to eq("SemVer['1.x', '3.x']") end it 'should present a valid simple name' do (all_types - [PTypeType, PClassType]).each do |t| name = t::DEFAULT.simple_name expect(t.name).to match("^Puppet::Pops::Types::P#{name}Type$") end expect(PTypeType::DEFAULT.simple_name).to eql('Type') expect(PClassType::DEFAULT.simple_name).to eql('Class') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/ruby_generator_spec.rb
spec/unit/pops/types/ruby_generator_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' require 'puppet/pops/types/ruby_generator' def root_binding return binding end module Puppet::Pops module Types describe 'Puppet Ruby Generator' do include PuppetSpec::Compiler let!(:parser) { TypeParser.singleton } let(:generator) { RubyGenerator.new } context 'when generating classes for Objects having attribute names that are Ruby reserved words' do let (:source) { <<-PUPPET } type MyObject = Object[{ attributes => { alias => String, begin => String, break => String, def => String, do => String, end => String, ensure => String, for => String, module => String, next => String, nil => String, not => String, redo => String, rescue => String, retry => String, return => String, self => String, super => String, then => String, until => String, when => String, while => String, yield => String, }, }] $x = MyObject({ alias => 'value of alias', begin => 'value of begin', break => 'value of break', def => 'value of def', do => 'value of do', end => 'value of end', ensure => 'value of ensure', for => 'value of for', module => 'value of module', next => 'value of next', nil => 'value of nil', not => 'value of not', redo => 'value of redo', rescue => 'value of rescue', retry => 'value of retry', return => 'value of return', self => 'value of self', super => 'value of super', then => 'value of then', until => 'value of until', when => 'value of when', while => 'value of while', yield => 'value of yield', }) notice($x.alias) notice($x.begin) notice($x.break) notice($x.def) notice($x.do) notice($x.end) notice($x.ensure) notice($x.for) notice($x.module) notice($x.next) notice($x.nil) notice($x.not) notice($x.redo) notice($x.rescue) notice($x.retry) notice($x.return) notice($x.self) notice($x.super) notice($x.then) notice($x.until) notice($x.when) notice($x.while) notice($x.yield) PUPPET it 'can create an instance and access all attributes' do expect(eval_and_collect_notices(source)).to eql([ 'value of alias', 'value of begin', 'value of break', 'value of def', 'value of do', 'value of end', 'value of ensure', 'value of for', 'value of module', 'value of next', 'value of nil', 'value of not', 'value of redo', 'value of rescue', 'value of retry', 'value of return', 'value of self', 'value of super', 'value of then', 'value of until', 'value of when', 'value of while', 'value of yield', ]) end end context 'when generating classes for Objects having function names that are Ruby reserved words' do let (:source) { <<-PUPPET } type MyObject = Object[{ functions => { alias => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of alias'" }}}, begin => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of begin'" }}}, break => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of break'" }}}, def => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of def'" }}}, do => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of do'" }}}, end => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of end'" }}}, ensure => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of ensure'" }}}, for => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of for'" }}}, module => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of module'" }}}, next => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of next'" }}}, nil => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of nil'" }}}, not => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of not'" }}}, redo => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of redo'" }}}, rescue => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of rescue'" }}}, retry => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of retry'" }}}, return => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of return'" }}}, self => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of self'" }}}, super => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of super'" }}}, then => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of then'" }}}, until => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of until'" }}}, when => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of when'" }}}, while => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of while'" }}}, yield => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of yield'" }}}, }, }] $x = MyObject() notice($x.alias) notice($x.begin) notice($x.break) notice($x.def) notice($x.do) notice($x.end) notice($x.ensure) notice($x.for) notice($x.module) notice($x.next) notice($x.nil) notice($x.not) notice($x.redo) notice($x.rescue) notice($x.retry) notice($x.return) notice($x.self) notice($x.super) notice($x.then) notice($x.until) notice($x.when) notice($x.while) notice($x.yield) PUPPET it 'can create an instance and call all functions' do expect(eval_and_collect_notices(source)).to eql([ 'value of alias', 'value of begin', 'value of break', 'value of def', 'value of do', 'value of end', 'value of ensure', 'value of for', 'value of module', 'value of next', 'value of nil', 'value of not', 'value of redo', 'value of rescue', 'value of retry', 'value of return', 'value of self', 'value of super', 'value of then', 'value of until', 'value of when', 'value of while', 'value of yield', ]) end end context 'when generating from Object types' do let (:type_decls) { <<-CODE.unindent } type MyModule::FirstGenerated = Object[{ attributes => { name => String, age => { type => Integer, value => 30 }, what => { type => String, value => 'what is this', kind => constant }, uc_name => { type => String, kind => derived, annotations => { RubyMethod => { body => '@name.upcase' } } }, other_name => { type => String, kind => derived }, }, functions => { some_other => { type => Callable[1,1] }, name_and_age => { type => Callable[1,1], annotations => { RubyMethod => { parameters => 'joiner', body => '"\#{@name}\#{joiner}\#{@age}"' } } }, '[]' => { type => Callable[1,1], annotations => { RubyMethod => { parameters => 'key', body => @(EOF) case key when 'name' name when 'age' age else nil end |-EOF } } } } }] type MyModule::SecondGenerated = Object[{ parent => MyModule::FirstGenerated, attributes => { address => String, zipcode => String, email => String, another => { type => Optional[MyModule::FirstGenerated], value => undef }, number => Integer, aref => { type => Optional[MyModule::FirstGenerated], value => undef, kind => reference } } }] CODE let(:type_usage) { '' } let(:source) { type_decls + type_usage } context 'when generating anonymous classes' do loader = nil let(:first_type) { parser.parse('MyModule::FirstGenerated', loader) } let(:second_type) { parser.parse('MyModule::SecondGenerated', loader) } let(:first) { generator.create_class(first_type) } let(:second) { generator.create_class(second_type) } let(:notices) { [] } before(:each) do notices.concat(eval_and_collect_notices(source) do |topscope| loader = topscope.compiler.loaders.find_loader(nil) end) end context 'the generated class' do it 'inherits the PuppetObject module' do expect(first < PuppetObject).to be_truthy end it 'is the superclass of a generated subclass' do expect(second < first).to be_truthy end end context 'the #create class method' do it 'has an arity that reflects optional arguments' do expect(first.method(:create).arity).to eql(-2) expect(second.method(:create).arity).to eql(-6) end it 'creates an instance of the class' do inst = first.create('Bob Builder', 52) expect(inst).to be_a(first) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(52) end it 'created instance has a [] method' do inst = first.create('Bob Builder', 52) expect(inst['name']).to eq('Bob Builder') expect(inst['age']).to eq(52) end it 'will perform type assertion of the arguments' do expect { first.create('Bob Builder', '52') }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String') ) end it 'will not accept nil as given value for an optional parameter that does not accept nil' do expect { first.create('Bob Builder', nil) }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef') ) end it 'reorders parameters to but the optional parameters last' do inst = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst.name).to eq('Bob Builder') expect(inst.address).to eq('42 Cool Street') expect(inst.zipcode).to eq('12345') expect(inst.email).to eq('bob@example.com') expect(inst.number).to eq(23) expect(inst.what).to eql('what is this') expect(inst.age).to eql(30) expect(inst.another).to be_nil end it 'generates a code body for derived attribute from a RubyMethod body attribute' do inst = first.create('Bob Builder', 52) expect(inst.uc_name).to eq('BOB BUILDER') end it "generates a code body with 'not implemented' in the absense of a RubyMethod body attribute" do inst = first.create('Bob Builder', 52) expect { inst.other_name }.to raise_error(/no method is implemented for derived attribute MyModule::FirstGenerated\[other_name\]/) end it 'generates parameter list and a code body for derived function from a RubyMethod body attribute' do inst = first.create('Bob Builder', 52) expect(inst.name_and_age(' of age ')).to eq('Bob Builder of age 52') end end context 'the #from_hash class method' do it 'has an arity of one' do expect(first.method(:from_hash).arity).to eql(1) expect(second.method(:from_hash).arity).to eql(1) end it 'creates an instance of the class' do inst = first.from_hash('name' => 'Bob Builder', 'age' => 52) expect(inst).to be_a(first) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(52) end it 'accepts an initializer where optional keys are missing' do inst = first.from_hash('name' => 'Bob Builder') expect(inst).to be_a(first) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(30) end it 'does not accept an initializer where optional values are nil and type does not accept nil' do expect { first.from_hash('name' => 'Bob Builder', 'age' => nil) }.to( raise_error(TypeAssertionError, "MyModule::FirstGenerated initializer has wrong type, entry 'age' expects an Integer value, got Undef") ) end end context 'creates an instance' do it 'that the TypeCalculator infers to the Object type' do expect(TypeCalculator.infer(first.from_hash('name' => 'Bob Builder'))).to eq(first_type) end it "where attributes of kind 'reference' are not considered part of #_pcore_all_contents" do inst = first.from_hash('name' => 'Bob Builder') wrinst = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23, 40, inst, inst) results = [] wrinst._pcore_all_contents([]) { |v| results << v } expect(results).to eq([inst]) end end context 'when used from Puppet' do let(:type_usage) { <<-PUPPET.unindent } $i = MyModule::FirstGenerated('Bob Builder', 52) notice($i['name']) notice($i['age']) PUPPET it 'The [] method is present on a created instance' do expect(notices).to eql(['Bob Builder', '52']) end end end context 'when generating static code' do module_def = nil before(:each) do # Ideally, this would be in a before(:all) but that is impossible since lots of Puppet # environment specific settings are configured by the spec_helper in before(:each) if module_def.nil? first_type = nil second_type = nil eval_and_collect_notices(source) do first_type = parser.parse('MyModule::FirstGenerated') second_type = parser.parse('MyModule::SecondGenerated') Loaders.implementation_registry.register_type_mapping( PRuntimeType.new(:ruby, [/^PuppetSpec::RubyGenerator::(\w+)$/, 'MyModule::\1']), [/^MyModule::(\w+)$/, 'PuppetSpec::RubyGenerator::\1']) module_def = generator.module_definition([first_type, second_type], 'Generated stuff') end Loaders.clear Puppet[:code] = nil # Create the actual classes in the PuppetSpec::RubyGenerator module Puppet.override(:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))) do eval(module_def, root_binding) end end end after(:all) do # Don't want generated module to leak outside this test PuppetSpec.send(:remove_const, :RubyGenerator) if PuppetSpec.const_defined?(:RubyGenerator) end it 'the #_pcore_type class method returns a resolved Type' do first_type = PuppetSpec::RubyGenerator::FirstGenerated._pcore_type expect(first_type).to be_a(PObjectType) second_type = PuppetSpec::RubyGenerator::SecondGenerated._pcore_type expect(second_type).to be_a(PObjectType) expect(second_type.parent).to eql(first_type) end context 'the #create class method' do it 'has an arity that reflects optional arguments' do expect(PuppetSpec::RubyGenerator::FirstGenerated.method(:create).arity).to eql(-2) expect(PuppetSpec::RubyGenerator::SecondGenerated.method(:create).arity).to eql(-6) end it 'creates an instance of the class' do inst = PuppetSpec::RubyGenerator::FirstGenerated.create('Bob Builder', 52) expect(inst).to be_a(PuppetSpec::RubyGenerator::FirstGenerated) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(52) end it 'will perform type assertion of the arguments' do expect { PuppetSpec::RubyGenerator::FirstGenerated.create('Bob Builder', '52') }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String') ) end it 'will not accept nil as given value for an optional parameter that does not accept nil' do expect { PuppetSpec::RubyGenerator::FirstGenerated.create('Bob Builder', nil) }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef') ) end it 'reorders parameters to but the optional parameters last' do inst = PuppetSpec::RubyGenerator::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst.name).to eq('Bob Builder') expect(inst.address).to eq('42 Cool Street') expect(inst.zipcode).to eq('12345') expect(inst.email).to eq('bob@example.com') expect(inst.number).to eq(23) expect(inst.what).to eql('what is this') expect(inst.age).to eql(30) expect(inst.another).to be_nil end end context 'the #from_hash class method' do it 'has an arity of one' do expect(PuppetSpec::RubyGenerator::FirstGenerated.method(:from_hash).arity).to eql(1) expect(PuppetSpec::RubyGenerator::SecondGenerated.method(:from_hash).arity).to eql(1) end it 'creates an instance of the class' do inst = PuppetSpec::RubyGenerator::FirstGenerated.from_hash('name' => 'Bob Builder', 'age' => 52) expect(inst).to be_a(PuppetSpec::RubyGenerator::FirstGenerated) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(52) end it 'accepts an initializer where optional keys are missing' do inst = PuppetSpec::RubyGenerator::FirstGenerated.from_hash('name' => 'Bob Builder') expect(inst).to be_a(PuppetSpec::RubyGenerator::FirstGenerated) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(30) end it 'does not accept an initializer where optional values are nil and type does not accept nil' do expect { PuppetSpec::RubyGenerator::FirstGenerated.from_hash('name' => 'Bob Builder', 'age' => nil) }.to( raise_error(TypeAssertionError, "MyModule::FirstGenerated initializer has wrong type, entry 'age' expects an Integer value, got Undef") ) end end end end context 'when generating from TypeSets' do def source <<-CODE type MyModule = TypeSet[{ pcore_version => '1.0.0', version => '1.0.0', types => { MyInteger => Integer, FirstGenerated => Object[{ attributes => { name => String, age => { type => Integer, value => 30 }, what => { type => String, value => 'what is this', kind => constant } } }], SecondGenerated => Object[{ parent => FirstGenerated, attributes => { address => String, zipcode => String, email => String, another => { type => Optional[FirstGenerated], value => undef }, number => MyInteger } }] }, }] type OtherModule = TypeSet[{ pcore_version => '1.0.0', version => '1.0.0', types => { MyFloat => Float, ThirdGenerated => Object[{ attributes => { first => My::FirstGenerated } }], FourthGenerated => Object[{ parent => My::SecondGenerated, attributes => { complex => { type => Optional[ThirdGenerated], value => undef }, n1 => My::MyInteger, n2 => MyFloat } }] }, references => { My => { name => 'MyModule', version_range => '1.x' } } }] CODE end context 'when generating anonymous classes' do typeset = nil let(:first_type) { typeset['My::FirstGenerated'] } let(:second_type) { typeset['My::SecondGenerated'] } let(:third_type) { typeset['ThirdGenerated'] } let(:fourth_type) { typeset['FourthGenerated'] } let(:first) { generator.create_class(first_type) } let(:second) { generator.create_class(second_type) } let(:third) { generator.create_class(third_type) } let(:fourth) { generator.create_class(fourth_type) } before(:each) do eval_and_collect_notices(source) do typeset = parser.parse('OtherModule') end end after(:each) { typeset = nil } context 'the typeset' do it 'produces expected string representation' do expect(typeset.to_s).to eq( "TypeSet[{pcore_version => '1.0.0', name_authority => 'http://puppet.com/2016.1/runtime', name => 'OtherModule', version => '1.0.0', types => {"+ "MyFloat => Float, "+ "ThirdGenerated => Object[{attributes => {'first' => My::FirstGenerated}}], "+ "FourthGenerated => Object[{parent => My::SecondGenerated, attributes => {"+ "'complex' => {type => Optional[ThirdGenerated], value => undef}, "+ "'n1' => My::MyInteger, "+ "'n2' => MyFloat"+ "}}]}, references => {My => {'name' => 'MyModule', 'version_range' => '1.x'}}}]") end end context 'the generated class' do it 'inherits the PuppetObject module' do expect(first < PuppetObject).to be_truthy end it 'is the superclass of a generated subclass' do expect(second < first).to be_truthy end end context 'the #create class method' do it 'has an arity that reflects optional arguments' do expect(first.method(:create).arity).to eql(-2) expect(second.method(:create).arity).to eql(-6) expect(third.method(:create).arity).to eql(1) expect(fourth.method(:create).arity).to eql(-8) end it 'creates an instance of the class' do inst = first.create('Bob Builder', 52) expect(inst).to be_a(first) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(52) end it 'will perform type assertion of the arguments' do expect { first.create('Bob Builder', '52') }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String') ) end it 'will not accept nil as given value for an optional parameter that does not accept nil' do expect { first.create('Bob Builder', nil) }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef') ) end it 'reorders parameters to but the optional parameters last' do inst = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst.name).to eq('Bob Builder') expect(inst.address).to eq('42 Cool Street') expect(inst.zipcode).to eq('12345') expect(inst.email).to eq('bob@example.com') expect(inst.number).to eq(23) expect(inst.what).to eql('what is this') expect(inst.age).to eql(30) expect(inst.another).to be_nil end it 'two instances with the same attribute values are equal using #eql?' do inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) inst2 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst1.eql?(inst2)).to be_truthy end it 'two instances with the same attribute values are equal using #==' do inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) inst2 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst1 == inst2).to be_truthy end it 'two instances with the different attribute in super class values are different' do inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) inst2 = second.create('Bob Engineer', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst1 == inst2).to be_falsey end it 'two instances with the different attribute in sub class values are different' do inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) inst2 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@other.com', 23) expect(inst1 == inst2).to be_falsey end end context 'the #from_hash class method' do it 'has an arity of one' do expect(first.method(:from_hash).arity).to eql(1) expect(second.method(:from_hash).arity).to eql(1) end it 'creates an instance of the class' do inst = first.from_hash('name' => 'Bob Builder', 'age' => 52) expect(inst).to be_a(first) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(52) end it 'accepts an initializer where optional keys are missing' do inst = first.from_hash('name' => 'Bob Builder') expect(inst).to be_a(first) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(30) end it 'does not accept an initializer where optional values are nil and type does not accept nil' do expect { first.from_hash('name' => 'Bob Builder', 'age' => nil) }.to( raise_error(TypeAssertionError, "MyModule::FirstGenerated initializer has wrong type, entry 'age' expects an Integer value, got Undef") ) end end context 'creates an instance' do it 'that the TypeCalculator infers to the Object type' do expect(TypeCalculator.infer(first.from_hash('name' => 'Bob Builder'))).to eq(first_type) end end end context 'when generating static code' do module_def = nil module_def2 = nil before(:each) do # Ideally, this would be in a before(:all) but that is impossible since lots of Puppet # environment specific settings are configured by the spec_helper in before(:each) if module_def.nil? eval_and_collect_notices(source) do typeset1 = parser.parse('MyModule') typeset2 = parser.parse('OtherModule') Loaders.implementation_registry.register_type_mapping( PRuntimeType.new(:ruby, [/^PuppetSpec::RubyGenerator::My::(\w+)$/, 'MyModule::\1']), [/^MyModule::(\w+)$/, 'PuppetSpec::RubyGenerator::My::\1']) Loaders.implementation_registry.register_type_mapping( PRuntimeType.new(:ruby, [/^PuppetSpec::RubyGenerator::Other::(\w+)$/, 'OtherModule::\1']), [/^OtherModule::(\w+)$/, 'PuppetSpec::RubyGenerator::Other::\1']) module_def = generator.module_definition_from_typeset(typeset1) module_def2 = generator.module_definition_from_typeset(typeset2) end Loaders.clear Puppet[:code] = nil # Create the actual classes in the PuppetSpec::RubyGenerator module Puppet.override(:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))) do eval(module_def, root_binding) eval(module_def2, root_binding) end end end after(:all) do # Don't want generated module to leak outside this test PuppetSpec.send(:remove_const, :RubyGenerator) if PuppetSpec.const_defined?(:RubyGenerator) end it 'the #_pcore_type class method returns a resolved Type' do first_type = PuppetSpec::RubyGenerator::My::FirstGenerated._pcore_type expect(first_type).to be_a(PObjectType) second_type = PuppetSpec::RubyGenerator::My::SecondGenerated._pcore_type expect(second_type).to be_a(PObjectType) expect(second_type.parent).to eql(first_type) end context 'the #create class method' do it 'has an arity that reflects optional arguments' do expect(PuppetSpec::RubyGenerator::My::FirstGenerated.method(:create).arity).to eql(-2) expect(PuppetSpec::RubyGenerator::My::SecondGenerated.method(:create).arity).to eql(-6) end it 'creates an instance of the class' do inst = PuppetSpec::RubyGenerator::My::FirstGenerated.create('Bob Builder', 52) expect(inst).to be_a(PuppetSpec::RubyGenerator::My::FirstGenerated) expect(inst.name).to eq('Bob Builder') expect(inst.age).to eq(52) end it 'will perform type assertion of the arguments' do expect { PuppetSpec::RubyGenerator::My::FirstGenerated.create('Bob Builder', '52') }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String') ) end it 'will not accept nil as given value for an optional parameter that does not accept nil' do expect { PuppetSpec::RubyGenerator::My::FirstGenerated.create('Bob Builder', nil) }.to( raise_error(TypeAssertionError, 'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef') ) end it 'reorders parameters to but the optional parameters last' do inst = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst.name).to eq('Bob Builder') expect(inst.address).to eq('42 Cool Street') expect(inst.zipcode).to eq('12345') expect(inst.email).to eq('bob@example.com') expect(inst.number).to eq(23) expect(inst.what).to eql('what is this') expect(inst.age).to eql(30) expect(inst.another).to be_nil end it 'two instances with the same attribute values are equal using #eql?' do inst1 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) inst2 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) expect(inst1.eql?(inst2)).to be_truthy end it 'two instances with the same attribute values are equal using #==' do inst1 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23) inst2 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/p_binary_type_spec.rb
spec/unit/pops/types/p_binary_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' module Puppet::Pops module Types describe 'Binary Type' do include PuppetSpec::Compiler context 'as a type' do it 'can be created with the type factory' do t = TypeFactory.binary() expect(t).to be_a(PBinaryType) expect(t).to eql(PBinaryType::DEFAULT) end end context 'a Binary instance' do it 'can be created from a raw String using %r, raw string mode' do str = [0xF1].pack("C*") code = <<-CODE $x = Binary($testing, '%r') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code, Puppet::Node.new('foonode'), { 'testing' => str })).to eql(['8Q==']) end it 'can be created from a String using %s, string mode' do # the text 'binar' needs padding with '=' code = <<-CODE $x = Binary('binary', '%s') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['YmluYXJ5']) end it 'format %s errors if encoding is bad in given string when using format %s and a broken UTF-8 string' do str = [0xF1].pack("C*") str.force_encoding('UTF-8') code = <<-CODE $x = Binary($testing, '%s') notice(assert_type(Binary, $x)) CODE expect { eval_and_collect_notices(code, Puppet::Node.new('foonode'), { 'testing' => str }) }.to raise_error(/.*The given string in encoding 'UTF-8' is invalid\. Cannot create a Binary UTF-8 representation.*/) end it 'format %s errors if encoding is correct but string cannot be transcoded to UTF-8' do str = [0xF1].pack("C*") code = <<-CODE $x = Binary($testing, '%s') notice(assert_type(Binary, $x)) CODE expect { eval_and_collect_notices(code, Puppet::Node.new('foonode'), { 'testing' => str }) }.to raise_error(/.*"\\xF1" from ASCII-8BIT to UTF-8.*/) end it 'can be created from a strict Base64 encoded String using default format' do code = <<-CODE $x = Binary('YmluYXI=') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['YmluYXI=']) end it 'will error creation in strict mode if padding is missing when using default format' do # the text 'binar' needs padding with '=' (missing here to trigger error code = <<-CODE $x = Binary('YmluYXI') notice(assert_type(Binary, $x)) CODE expect{ eval_and_collect_notices(code) }.to raise_error(/invalid base64/) end it 'can be created from a Base64 encoded String using %B, strict mode' do # the text 'binar' needs padding with '=' code = <<-CODE $x = Binary('YmluYXI=', '%B') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['YmluYXI=']) end it 'will error creation in strict mode if padding is missing' do # the text 'binar' needs padding with '=' (missing here to trigger error code = <<-CODE $x = Binary('YmluYXI', '%B') notice(assert_type(Binary, $x)) CODE expect{ eval_and_collect_notices(code) }.to raise_error(/invalid base64/) end it 'will not error creation in base mode if padding is missing' do # the text 'binar' needs padding with '=' (missing here to trigger possible error) code = <<-CODE $x = Binary('YmluYXI', '%b') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['YmluYXI=']) end it 'will not error creation in base mode if padding is not required' do # the text 'binary' does not need padding with '=' code = <<-CODE $x = Binary('YmluYXJ5', '%b') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['YmluYXJ5']) end it 'can be compared to another instance for equality' do code = <<-CODE $x = Binary('YmluYXJ5') $y = Binary('YmluYXJ5') notice($x == $y) notice($x != $y) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'false']) end it 'can be created from an array of byte values' do # the text 'binar' needs padding with '=' code = <<-CODE $x = Binary([251, 239, 255]) notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['++//']) end it "can be created from an hash with value and format" do # the text 'binar' needs padding with '=' code = <<-CODE $x = Binary({value => '--__', format => '%u'}) notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['++//']) end it "can be created from an hash with value and default format" do code = <<-CODE $x = Binary({value => 'YmluYXI='}) notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['YmluYXI=']) end it 'can be created from a hash with value being an array' do # the text 'binar' needs padding with '=' code = <<-CODE $x = Binary({value => [251, 239, 255]}) notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['++//']) end it "can be created from an Base64 using URL safe encoding by specifying '%u' format'" do # the text 'binar' needs padding with '=' code = <<-CODE $x = Binary('--__', '%u') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['++//']) end it "when created with URL safe encoding chars in '%b' format, these are skipped" do code = <<-CODE $x = Binary('--__YmluYXJ5', '%b') notice(assert_type(Binary, $x)) CODE expect(eval_and_collect_notices(code)).to eql(['YmluYXJ5']) end it "will error in strict format if string contains URL safe encoded chars" do code = <<-CODE $x = Binary('--__YmluYXJ5', '%B') notice(assert_type(Binary, $x)) CODE expect { eval_and_collect_notices(code) }.to raise_error(/invalid base64/) end [ '<', '<=', '>', '>=' ].each do |op| it "cannot be compared to another instance for magnitude using #{op}" do code = <<-"CODE" $x = Binary('YmluYXJ5') $y = Binary('YmluYXJ5') $x #{op} $y CODE expect { eval_and_collect_notices(code)}.to raise_error(/Comparison of: Binary #{op} Binary, is not possible/) end end it 'can be matched against a Binary in case expression' do code = <<-CODE case Binary('YmluYXJ5') { Binary('YWxpZW4='): { notice('nope') } Binary('YmluYXJ5'): { notice('yay') } default: { notice('nope') } } CODE expect(eval_and_collect_notices(code)).to eql(['yay']) end it "can be matched against a Binary subsequence using 'in' expression" do # finding 'one' in 'one two three' code = <<-CODE notice(Binary("b25l") in Binary("b25lIHR3byB0aHJlZQ==")) notice(Binary("c25l") in Binary("b25lIHR3byB0aHJlZQ==")) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'false']) end it "can be matched against a byte value using 'in' expression" do # finding 'e' (ascii 101) in 'one two three' code = <<-CODE notice(101 in Binary("b25lIHR3byB0aHJlZQ==")) notice(101.0 in Binary("b25lIHR3byB0aHJlZQ==")) notice(102 in Binary("b25lIHR3byB0aHJlZQ==")) CODE expect(eval_and_collect_notices(code)).to eql(['true', 'true', 'false']) end it "has a length method in ruby returning the length measured in bytes" do # \u{1f452} is "woman's hat emoji - 4 bytes in UTF-8" a_binary = PBinaryType::Binary.new("\u{1f452}") expect(a_binary.length).to be(4) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/types/type_asserter_spec.rb
spec/unit/pops/types/type_asserter_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops::Types describe 'the type asserter' do let!(:asserter) { TypeAsserter } context 'when deferring formatting of subject' it 'can use an array' do expect{ asserter.assert_instance_of(['The %s in the %s', 'gizmo', 'gadget'], PIntegerType::DEFAULT, 'lens') }.to( raise_error(TypeAssertionError, 'The gizmo in the gadget has wrong type, expects an Integer value, got String')) end it 'can use an array obtained from block' do expect do asserter.assert_instance_of('gizmo', PIntegerType::DEFAULT, 'lens') { |s| ['The %s in the %s', s, 'gadget'] } end.to(raise_error(TypeAssertionError, 'The gizmo in the gadget has wrong type, expects an Integer value, got String')) end it 'can use an subject obtained from zero argument block' do expect do asserter.assert_instance_of(nil, PIntegerType::DEFAULT, 'lens') { 'The gizmo in the gadget' } end.to(raise_error(TypeAssertionError, 'The gizmo in the gadget has wrong type, expects an Integer value, got String')) end it 'does not produce a string unless the assertion fails' do expect(TypeAsserter).not_to receive(:report_type_mismatch) asserter.assert_instance_of(nil, PIntegerType::DEFAULT, 1) end it 'does not format string unless the assertion fails' do fmt_string = 'The %s in the %s' expect(fmt_string).not_to receive(:'%') asserter.assert_instance_of([fmt_string, 'gizmo', 'gadget'], PIntegerType::DEFAULT, 1) end it 'does not call block unless the assertion fails' do expect do asserter.assert_instance_of(nil, PIntegerType::DEFAULT, 1) { |s| raise Error } end.not_to raise_error end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/validator/validator_spec.rb
spec/unit/pops/validator/validator_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/pops' require_relative '../parser/parser_rspec_helper' describe "validating 4x" do include ParserRspecHelper include PuppetSpec::Pops let(:acceptor) { Puppet::Pops::Validation::Acceptor.new() } let(:validator) { Puppet::Pops::Validation::ValidatorFactory_4_0.new().validator(acceptor) } let(:environment) { Puppet::Node::Environment.create(:bar, ['path']) } def validate(factory) validator.validate(factory.model) acceptor end def deprecation_count(acceptor) acceptor.diagnostics.select {|d| d.severity == :deprecation }.count end def with_environment(environment, env_params = {}) override_env = environment override_env = environment.override_with({ modulepath: env_params[:modulepath] || environment.full_modulepath, manifest: env_params[:manifest] || environment.manifest, config_version: env_params[:config_version] || environment.config_version }) if env_params.count > 0 Puppet.override(current_environment: override_env) do yield end end it 'should raise error for illegal class names' do expect(validate(parse('class aaa::_bbb {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) expect(validate(parse('class Aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) expect(validate(parse('class ::aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) end it 'should raise error for illegal define names' do expect(validate(parse('define aaa::_bbb {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) expect(validate(parse('define Aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) expect(validate(parse('define ::aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) end it 'should raise error for illegal function names' do expect(validate(parse('function aaa::_bbb() {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) expect(validate(parse('function Aaa() {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) expect(validate(parse('function ::aaa() {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) end it 'should raise error for illegal definition locations' do with_environment(environment) do expect(validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('class bbb() {}', 'path/aaa/manifests/init.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('define aaa::bbb::ccc::eee() {}', 'path/aaa/manifests/bbb/ddd.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error for legal definition locations' do with_environment(environment) do expect(validate(parse('function aaa::bbb() {}', 'path/aaa/manifests/bbb.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('class aaa() {}', 'path/aaa/manifests/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('function aaa::bbB::ccc() {}', 'path/aaa/manifests/bBb.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('function aaa::bbb::ccc() {}', 'path/aaa/manifests/bbb/CCC.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error for class locations when not parsing a file' do #nil/'' file means eval or some other way to get puppet language source code into the catalog with_environment(environment) do expect(validate(parse('function aaa::ccc() {}', nil))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('function aaa::ccc() {}', ''))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error for definitions inside initial --manifest file' do with_environment(environment, :manifest => 'a/manifest/file.pp') do expect(validate(parse('class aaa() {}', 'a/manifest/file.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error for definitions inside initial --manifest directory' do with_environment(environment, :manifest => 'a/manifest/dir') do expect(validate(parse('class aaa() {}', 'a/manifest/dir/file1.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('class bbb::ccc::ddd() {}', 'a/manifest/dir/and/more/stuff.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error for definitions not inside initial --manifest but also not in modulepath' do with_environment(environment, :manifest => 'a/manifest/somewhere/else') do expect(validate(parse('class aaa() {}', 'a/random/dir/file1.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error for empty files in modulepath' do with_environment(environment) do expect(validate(parse('', 'path/aaa/manifests/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION) expect(validate(parse('#this is a comment', 'path/aaa/manifests/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION) end end it 'should raise error if the file is in the modulepath but is not well formed' do with_environment(environment) do expect(validate(parse('class aaa::bbb::ccc() {}', 'path/manifest/aaa/bbb.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('class aaa::bbb::ccc() {}', 'path/aaa/bbb/manifest/ccc.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error for definitions not inside initial --manifest but also not in modulepath because of only a case difference' do with_environment(environment) do expect(validate(parse('class aaa::bb() {}', 'Path/aaa/manifests/ccc.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error when one modulepath is a substring of another' do with_environment(environment, modulepath: ['path', 'pathplus']) do expect(validate(parse('class aaa::ccc() {}', 'pathplus/aaa/manifests/ccc.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should not raise error when a modulepath ends with a file separator' do with_environment(environment, modulepath: ['path/']) do expect(validate(parse('class aaa::ccc() {}', 'pathplus/aaa/manifests/ccc.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'should raise error for illegal type names' do expect(validate(parse('type ::Aaa = Any'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME) end it 'should raise error for illegal variable names' do expect(validate(fqn('Aaa').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME) expect(validate(fqn('AAA').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME) expect(validate(fqn('aaa::_aaa').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME) end it 'should not raise error for variable name with underscore first in first name segment' do expect(validate(fqn('_aa').var())).to_not have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME) expect(validate(fqn('::_aa').var())).to_not have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME) end context 'with the default settings for --strict' do it 'produces an error for duplicate keys in a literal hash' do acceptor = validate(parse('{ a => 1, a => 2 }')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_KEY) end it 'produces an error for illegal function locations' do with_environment(environment) do acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'produces an error for illegal top level constructs' do with_environment(environment) do acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION) end end end context 'with --strict set to warning' do before(:each) { Puppet[:strict] = :warning } it 'produces a warning for duplicate keys in a literal hash' do acceptor = validate(parse('{ a => 1, a => 2 }')) expect(acceptor.warning_count).to eql(1) expect(acceptor.error_count).to eql(0) expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_KEY) end it 'produces an error for virtual class resource' do acceptor = validate(parse('@class { test: }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end it 'produces an error for exported class resource' do acceptor = validate(parse('@@class { test: }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end it 'produces an error for illegal function locations' do with_environment(environment) do acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'produces an error for illegal top level constructs' do with_environment(environment) do acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION) end end end context 'with --strict set to error' do before(:each) { Puppet[:strict] = :error } it 'produces an error for duplicate keys in a literal hash' do acceptor = validate(parse('{ a => 1, a => 2 }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_KEY) end it 'produces an error for virtual class resource' do acceptor = validate(parse('@class { test: }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end it 'does not produce an error for regular class resource' do acceptor = validate(parse('class { test: }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(0) expect(acceptor).not_to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end it 'produces an error for exported class resource' do acceptor = validate(parse('@@class { test: }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end it 'produces an error for illegal function locations' do with_environment(environment) do acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'produces an error for illegal top level constructs' do with_environment(environment) do acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION) end end end context 'with --strict set to off' do before(:each) { Puppet[:strict] = :off } it 'does not produce an error or warning for duplicate keys in a literal hash' do acceptor = validate(parse('{ a => 1, a => 2 }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(0) expect(acceptor).to_not have_issue(Puppet::Pops::Issues::DUPLICATE_KEY) end it 'produces an error for illegal function locations' do with_environment(environment) do acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'produces an error for illegal top level constructs' do with_environment(environment) do acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp')) expect(deprecation_count(acceptor)).to eql(0) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION) end end end context 'irrespective of --strict' do it 'produces an error for duplicate default in a case expression' do acceptor = validate(parse('case 1 { default: {1} default : {2} }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_DEFAULT) end it 'produces an error for duplicate default in a selector expression' do acceptor = validate(parse(' 1 ? { default => 1, default => 2 }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_DEFAULT) end it 'produces an error for virtual class resource' do acceptor = validate(parse('@class { test: }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end it 'produces an error for exported class resource' do acceptor = validate(parse('@@class { test: }')) expect(acceptor.warning_count).to eql(0) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end it 'produces a deprecation warning for non-literal class parameters' do acceptor = validate(parse('class test(Integer[2-1] $port) {}')) expect(deprecation_count(acceptor)).to eql(1) expect(acceptor.warning_count).to eql(1) expect(acceptor.error_count).to eql(0) expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_NONLITERAL_PARAMETER_TYPE) end end context 'with --tasks set' do before(:each) { Puppet[:tasks] = true } it 'raises an error for illegal plan names' do with_environment(environment) do expect(validate(parse('plan aaa::ccc::eee() {}', 'path/aaa/plans/bbb/ccc/eee.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('plan aaa() {}', 'path/aaa/plans/aaa.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('plan aaa::bbb() {}', 'path/aaa/plans/bbb/bbb.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'accepts legal plan names' do with_environment(environment) do expect(validate(parse('plan aaa::ccc::eee() {}', 'path/aaa/plans/ccc/eee.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('plan aaa() {}', 'path/aaa/plans/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) expect(validate(parse('plan aaa::bbb() {}', 'path/aaa/plans/bbb.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION) end end it 'produces an error for collect expressions with virtual query' do acceptor = validate(parse("User <| title == 'admin' |>")) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for collect expressions with exported query' do acceptor = validate(parse("User <<| title == 'admin' |>>")) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for class expressions' do acceptor = validate(parse('class test {}')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for node expressions' do acceptor = validate(parse('node default {}')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for relationship expressions' do acceptor = validate(parse('$x -> $y')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for resource expressions' do acceptor = validate(parse('notify { nope: }')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for resource default expressions' do acceptor = validate(parse("File { mode => '0644' }")) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for resource override expressions' do acceptor = validate(parse("File['/tmp/foo'] { mode => '0644' }")) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for resource definitions' do acceptor = validate(parse('define foo($a) {}')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end context 'validating apply() blocks' do it 'allows empty apply() blocks' do acceptor = validate(parse('apply("foo.example.com") { }')) expect(acceptor.error_count).to eql(0) end it 'allows apply() with a single expression' do acceptor = validate(parse('apply("foo.example.com") { include foo }')) expect(acceptor.error_count).to eql(0) end it 'allows apply() with multiple expressions' do acceptor = validate(parse('apply("foo.example.com") { $message = "hello!"; notify { $message: } }')) expect(acceptor.error_count).to eql(0) end it 'allows apply to be used as a resource attribute name' do acceptor = validate(parse('apply("foo.example.com") { sometype { "resourcetitle": apply => "applyvalue" } }')) expect(acceptor.error_count).to eql(0) end it 'accepts multiple arguments' do acceptor = validate(parse('apply(["foo.example.com"], { "other" => "args" }) { }')) expect(acceptor.error_count).to eql(0) end it 'allows virtual resource collectors' do acceptor = validate(parse("apply('foo.example.com') { @user { 'foo': }; User <| title == 'foo' |> }")) expect(acceptor.error_count).to eql(0) end it 'rejects exported resource collectors' do acceptor = validate(parse("apply('foo.example.com') { @@user { 'foo': }; User <<| title == 'foo' |>> }")) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING) end it 'allows relationship expressions' do acceptor = validate(parse('apply("foo.example.com") { $x -> $y }')) expect(acceptor.error_count).to eql(0) end it 'allows resource default expressions' do acceptor = validate(parse("apply('foo.example.com') { File { mode => '0644' } }")) expect(acceptor.error_count).to eql(0) end it 'allows resource override expressions' do acceptor = validate(parse("apply('foo.example.com') { File['/tmp/foo'] { mode => '0644' } }")) expect(acceptor.error_count).to eql(0) end it 'can be assigned' do acceptor = validate(parse('$result = apply("foo.example.com") { notify { "hello!": } }')) expect(acceptor.error_count).to eql(0) end it 'produces an error for class expressions' do acceptor = validate(parse('apply("foo.example.com") { class test {} }')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'allows node expressions' do acceptor = validate(parse('apply("foo.example.com") { node default {} }')) expect(acceptor.error_count).to eql(0) end it 'produces an error for node expressions nested in a block' do acceptor = validate(parse('apply("foo.example.com") { if true { node default {} } }')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::NOT_TOP_LEVEL) end it 'produces an error for resource definitions' do acceptor = validate(parse('apply("foo.example.com") { define foo($a) {} }')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING) end it 'produces an error for apply() inside apply()' do acceptor = validate(parse('apply("foo.example.com") { apply("foo.example.com") { } }')) expect(acceptor.error_count).to eql(1) expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING) end it 'allows multiple consecutive apply() blocks' do acceptor = validate(parse('apply("foo.example.com") { } apply("foo.example.com") { }')) expect(acceptor.error_count).to eql(0) end end end context 'for non productive expressions' do [ '1', '3.14', "'a'", '"a"', '"${$a=10}"', # interpolation with side effect 'false', 'true', 'default', 'undef', '[1,2,3]', '{a=>10}', 'if 1 {2}', 'if 1 {2} else {3}', 'if 1 {2} elsif 3 {4}', 'unless 1 {2}', 'unless 1 {2} else {3}', '1 ? 2 => 3', '1 ? { 2 => 3}', '-1', '-foo()', # unary minus on productive '1+2', '1<2', '(1<2)', '!true', '!foo()', # not on productive '$a', '$a[1]', 'name', 'Type', 'Type[foo]' ].each do |expr| it "produces error for non productive: #{expr}" do source = "#{expr}; $a = 10" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST) end it "does not produce error when last for non productive: #{expr}" do source = " $a = 10; #{expr}" expect(validate(parse(source))).to_not have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST) end end [ 'if 1 {$a = 1}', 'if 1 {2} else {$a=1}', 'if 1 {2} elsif 3 {$a=1}', 'unless 1 {$a=1}', 'unless 1 {2} else {$a=1}', '$a = 1 ? 2 => 3', '$a = 1 ? { 2 => 3}', 'Foo[a] -> Foo[b]', '($a=1)', 'foo()', '$a.foo()', '"foo" =~ /foo/', # may produce or modify $n vars '"foo" !~ /foo/', # may produce or modify $n vars ].each do |expr| it "does not produce error when for productive: #{expr}" do source = "#{expr}; $x = 1" expect(validate(parse(source))).to_not have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST) end end ['class', 'define', 'node'].each do |type| it "flags non productive expression last in #{type}" do source = <<-SOURCE #{type} nope { 1 } end SOURCE expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::IDEM_NOT_ALLOWED_LAST) end it "detects a resource declared without title in #{type} when it is the only declaration present" do source = <<-SOURCE #{type} nope { notify { message => 'Nope' } } SOURCE expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE) end it "detects a resource declared without title in #{type} when it is in between other declarations" do source = <<-SOURCE #{type} nope { notify { succ: message => 'Nope' } notify { message => 'Nope' } notify { pred: message => 'Nope' } } SOURCE expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE) end it "detects a resource declared without title in #{type} when it is declarated first" do source = <<-SOURCE #{type} nope { notify { message => 'Nope' } notify { pred: message => 'Nope' } } SOURCE expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE) end it "detects a resource declared without title in #{type} when it is declarated last" do source = <<-SOURCE #{type} nope { notify { succ: message => 'Nope' } notify { message => 'Nope' } } SOURCE expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE) end end end context 'for reserved words' do ['private', 'attr'].each do |word| it "produces an error for the word '#{word}'" do source = "$a = #{word}" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_WORD) end end end context 'for reserved type names' do [# type/Type, is a reserved name but results in syntax error because it is a keyword in lower case form 'any', 'unit', 'scalar', 'boolean', 'numeric', 'integer', 'float', 'collection', 'array', 'hash', 'tuple', 'struct', 'variant', 'optional', 'enum', 'regexp', 'pattern', 'runtime', 'init', 'object', 'sensitive', 'semver', 'semverrange', 'string', 'timestamp', 'timespan', 'typeset', ].each do |name| it "produces an error for 'class #{name}'" do source = "class #{name} {}" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_TYPE_NAME) end it "produces an error for 'define #{name}'" do source = "define #{name} {}" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_TYPE_NAME) end end end context 'for keywords' do it "should allow using the 'type' as the name of a function with no parameters" do source = "type()" expect(validate(parse(source))).not_to have_any_issues end it "should allow using the keyword 'type' as the name of a function with parameters" do source = "type('a', 'b')" expect(validate(parse(source))).not_to have_any_issues end it "should allow using the 'type' as the name of a function with no parameters and a block" do source = "type() |$x| { $x }" expect(validate(parse(source))).not_to have_any_issues end it "should allow using the keyword 'type' as the name of a function with parameters and a block" do source = "type('a', 'b') |$x| { $x }" expect(validate(parse(source))).not_to have_any_issues end end context 'for hash keys' do it "should not allow reassignment of hash keys" do source = "$my_hash = {'one' => '1', 'two' => '2' }; $my_hash['one']='1.5'" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::ILLEGAL_INDEXED_ASSIGNMENT) end end context 'for parameter names' do ['class', 'define'].each do |word| it "should require that #{word} parameter names are unique" do expect(validate(parse("#{word} foo($a = 10, $a = 20) {}"))).to have_issue(Puppet::Pops::Issues::DUPLICATE_PARAMETER) end end it "should require that template parameter names are unique" do expect(validate(parse_epp("<%-| $a, $a |-%><%= $a == doh %>"))).to have_issue(Puppet::Pops::Issues::DUPLICATE_PARAMETER) end end context 'for parameter defaults' do ['class', 'define'].each do |word| it "should not permit assignments in #{word} parameter default expressions" do expect { parse("#{word} foo($a = $x = 10) {}") }.to raise_error(Puppet::ParseErrorWithIssue, /Syntax error at '='/) end end ['class', 'define'].each do |word| it "should not permit assignments in #{word} parameter default nested expressions" do expect(validate(parse("#{word} foo($a = [$x = 10]) {}"))).to have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT) end it "should not permit assignments to subsequently declared parameters in #{word} parameter default nested expressions" do expect(validate(parse("#{word} foo($a = ($b = 3), $b = 5) {}"))).to have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT) end it "should not permit assignments to previously declared parameters in #{word} parameter default nested expressions" do expect(validate(parse("#{word} foo($a = 10, $b = ($a = 10)) {}"))).to have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT) end it "should permit assignments in #{word} parameter default inside nested lambda expressions" do expect(validate(parse( "#{word} foo($a = [1,2,3], $b = 0, $c = $a.map |$x| { $b = $x; $b * $a.reduce |$x, $y| {$x + $y}}) {}"))).not_to( have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT)) end end end context 'for reserved parameter names' do ['name', 'title'].each do |word| it "produces an error when $#{word} is used as a parameter in a class" do source = "class x ($#{word}) {}" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_PARAMETER) end it "produces an error when $#{word} is used as a parameter in a define" do source = "define x ($#{word}) {}" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_PARAMETER) end end end context 'for numeric parameter names' do ['1', '0x2', '03'].each do |word| it "produces an error when $#{word} is used as a parameter in a class" do source = "class x ($#{word}) {}" expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::ILLEGAL_NUMERIC_PARAMETER) end end end context 'for badly formed non-numeric parameter names' do ['Ateam', 'a::team'].each do |word| it "produces an error when $#{word} is used as a parameter in a class" do source = "class x ($#{word}) {}"
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/loaders/static_loader_spec.rb
spec/unit/pops/loaders/static_loader_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/loaders' describe 'the static loader' do let(:loader) do loader = Puppet::Pops::Loader::StaticLoader.new() loader.runtime_3_init loader end it 'has no parent' do expect(loader.parent).to be(nil) end it 'identifies itself in string form' do expect(loader.to_s).to be_eql('(StaticLoader)') end it 'support the Loader API' do # it may produce things later, this is just to test that calls work as they should - now all lookups are nil. a_typed_name = typed_name(:function, 'foo') expect(loader[a_typed_name]).to be(nil) expect(loader.load_typed(a_typed_name)).to be(nil) expect(loader.find(a_typed_name)).to be(nil) end context 'provides access to resource types built into puppet' do %w{ Component Exec File Filebucket Group Notify Package Resources Schedule Service Stage Tidy User Whit }.each do |name | it "such that #{name} is available" do expect(loader.load(:type, name.downcase)).to be_the_type(resource_type(name)) end end end context 'provides access to app-management specific resource types built into puppet' do it "such that Node is available" do expect(loader.load(:type, 'node')).to be_the_type(resource_type('Node')) end end context 'without init_runtime3 initialization' do let(:loader) { Puppet::Pops::Loader::StaticLoader.new() } it 'does not provide access to resource types built into puppet' do expect(loader.load(:type, 'file')).to be_nil end end def typed_name(type, name) Puppet::Pops::Loader::TypedName.new(type, name) end def resource_type(name) Puppet::Pops::Types::TypeFactory.resource(name) end matcher :be_the_type do |type| calc = Puppet::Pops::Types::TypeCalculator.new match do |actual| calc.assignable?(actual, type) && calc.assignable?(type, actual) end failure_message do |actual| "expected #{type.to_s}, but was #{actual.to_s}" end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/loaders/dependency_loader_spec.rb
spec/unit/pops/loaders/dependency_loader_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/pops' require 'puppet/loaders' describe 'dependency loader' do include PuppetSpec::Files let(:static_loader) { Puppet::Pops::Loader::StaticLoader.new() } let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) } describe 'FileBased module loader' do it 'prints a pretty name for itself when inspected' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo.rb' => 'Puppet::Functions.create_function("foo") { def foo; end; }' }}}}}) loader = loader_for('testmodule', module_dir) expect(loader.inspect).to eq("(DependencyLoader 'test-dep' [(ModuleLoader::FileBased 'testmodule' 'testmodule')])") expect(loader.to_s).to eq("(DependencyLoader 'test-dep' [(ModuleLoader::FileBased 'testmodule' 'testmodule')])") end it 'load something in global name space raises an error' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo.rb' => 'Puppet::Functions.create_function("foo") { def foo; end; }' }}}}}) loader = loader_for('testmodule', module_dir) expect do loader.load_typed(typed_name(:function, 'testmodule::foo')).value end.to raise_error(ArgumentError, /produced mis-matched name, expected 'testmodule::foo', got foo/) end it 'can load something in a qualified name space' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo.rb' => 'Puppet::Functions.create_function("testmodule::foo") { def foo; end; }' }}}}}) loader = loader_for('testmodule', module_dir) function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value expect(function.class.name).to eq('testmodule::foo') expect(function.is_a?(Puppet::Functions::Function)).to eq(true) end it 'can load something in a qualified name space more than once' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo.rb' => 'Puppet::Functions.create_function("testmodule::foo") { def foo; end; }' }}}}}) loader = loader_for('testmodule', module_dir) function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value expect(function.class.name).to eq('testmodule::foo') expect(function.is_a?(Puppet::Functions::Function)).to eq(true) function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value expect(function.class.name).to eq('testmodule::foo') expect(function.is_a?(Puppet::Functions::Function)).to eq(true) end describe "when parsing files from disk" do # First line of Rune version of Rune poem at http://www.columbia.edu/~fdc/utf8/ # characters chosen since they will not parse on Windows with codepage 437 or 1252 # Section 3.2.1.3 of Ruby spec guarantees that \u strings are encoded as UTF-8 let (:node) { Puppet::Node.new('node') } let (:rune_utf8) { "\u16A0\u16C7\u16BB" } # ᚠᛇᚻ let (:code_utf8) do <<-CODE Puppet::Functions.create_function('testmodule::foo') { def foo return \"#{rune_utf8}\" end } CODE end context 'when loading files from disk' do it 'should always read files as UTF-8' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo.rb' => code_utf8 }}}}}) loader = loader_for('testmodule', module_dir) function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value expect(function.call({})).to eq(rune_utf8) end it 'currently ignores the UTF-8 BOM (Byte Order Mark) when loading module files' do bom = "\uFEFF" module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo.rb' => "#{bom}#{code_utf8}" }}}}}) loader = loader_for('testmodule', module_dir) function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value expect(function.call({})).to eq(rune_utf8) end end end end def loader_for(name, dir) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, name, dir) Puppet::Pops::Loader::DependencyLoader.new(static_loader, 'test-dep', [module_loader], loaders.environment) end def typed_name(type, name) Puppet::Pops::Loader::TypedName.new(type, name) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/loaders/loader_spec.rb
spec/unit/pops/loaders/loader_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'puppet/pops' require 'puppet/loaders' module Puppet::Pops module Loader describe 'The Loader' do include PuppetSpec::Compiler include PuppetSpec::Files before(:each) do Puppet[:tasks] = true end let(:testing_env) do { 'testing' => { 'functions' => functions, 'lib' => { 'puppet' => lib_puppet }, 'manifests' => manifests, 'modules' => modules, 'plans' => plans, 'tasks' => tasks, 'types' => types, } } end let(:functions) { {} } let(:manifests) { {} } let(:modules) { {} } let(:plans) { {} } let(:lib_puppet) { {} } let(:tasks) { {} } let(:types) { {} } let(:environments_dir) { Puppet[:environmentpath] } let(:testing_env_dir) do dir_contained_in(environments_dir, testing_env) env_dir = File.join(environments_dir, 'testing') PuppetSpec::Files.record_tmp(env_dir) env_dir end let(:modules_dir) { File.join(testing_env_dir, 'modules') } let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) } let(:node) { Puppet::Node.new('test', :environment => env) } let(:loader) { Loaders.find_loader(nil) } let(:tasks_feature) { false } before(:each) do Puppet[:tasks] = tasks_feature loaders = Loaders.new(env) Puppet.push_context(:loaders => loaders) loaders.pre_load end after(:each) { Puppet.pop_context } context 'when doing discovery' do context 'of things' do it 'finds statically basic types' do expect(loader.discover(:type)).to include(tn(:type, 'integer')) end it 'finds statically loaded types' do expect(loader.discover(:type)).to include(tn(:type, 'file')) end it 'finds statically loaded Object types' do expect(loader.discover(:type)).to include(tn(:type, 'puppet::ast::accessexpression')) end context 'in environment' do let(:types) { { 'global.pp' => <<-PUPPET.unindent, type Global = Integer PUPPET 'environment' => { 'env.pp' => <<-PUPPET.unindent, type Environment::Env = String PUPPET } } } let(:functions) { { 'globfunc.pp' => 'function globfunc() {}', 'environment' => { 'envfunc.pp' => 'function environment::envfunc() {}' } } } let(:lib_puppet) { { 'functions' => { 'globrubyfunc.rb' => 'Puppet::Functions.create_function(:globrubyfunc) { def globrubyfunc; end }', 'environment' => { 'envrubyfunc.rb' => "Puppet::Functions.create_function(:'environment::envrubyfunc') { def envrubyfunc; end }", } } } } it 'finds global types in environment' do expect(loader.discover(:type)).to include(tn(:type, 'global')) end it 'finds global functions in environment' do expect(loader.discover(:function)).to include(tn(:function, 'lookup')) end it 'finds types prefixed with Environment in environment' do expect(loader.discover(:type)).to include(tn(:type, 'environment::env')) end it 'finds global functions in environment' do expect(loader.discover(:function)).to include(tn(:function, 'globfunc')) end it 'finds functions prefixed with Environment in environment' do expect(loader.discover(:function)).to include(tn(:function, 'environment::envfunc')) end it 'finds global ruby functions in environment' do expect(loader.discover(:function)).to include(tn(:function, 'globrubyfunc')) end it 'finds ruby functions prefixed with Environment in environment' do expect(loader.discover(:function)).to include(tn(:function, 'environment::envrubyfunc')) end it 'can filter the list of discovered entries using a block' do expect(loader.discover(:function) { |t| t.name =~ /rubyfunc\z/ }).to contain_exactly( tn(:function, 'environment::envrubyfunc'), tn(:function, 'globrubyfunc') ) end context 'with multiple modules' do let(:metadata_json_a) { { 'name' => 'example/a', 'version' => '0.1.0', 'source' => 'git@github.com/example/example-a.git', 'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}], 'author' => 'Bob the Builder', 'license' => 'Apache-2.0' } } let(:metadata_json_b) { { 'name' => 'example/b', 'version' => '0.1.0', 'source' => 'git@github.com/example/example-b.git', 'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}], 'author' => 'Bob the Builder', 'license' => 'Apache-2.0' } } let(:metadata_json_c) { { 'name' => 'example/c', 'version' => '0.1.0', 'source' => 'git@github.com/example/example-c.git', 'dependencies' => [], 'author' => 'Bob the Builder', 'license' => 'Apache-2.0' } } let(:modules) { { 'a' => { 'functions' => a_functions, 'lib' => { 'puppet' => a_lib_puppet }, 'plans' => a_plans, 'tasks' => a_tasks, 'types' => a_types, 'metadata.json' => metadata_json_a.to_json }, 'b' => { 'functions' => b_functions, 'lib' => { 'puppet' => b_lib_puppet }, 'plans' => b_plans, 'tasks' => b_tasks, 'types' => b_types, 'metadata.json' => metadata_json_b.to_json }, 'c' => { 'types' => c_types, 'tasks' => c_tasks, 'metadata.json' => metadata_json_c.to_json }, } } let(:a_plans) { { 'aplan.pp' => <<-PUPPET.unindent, plan a::aplan() {} PUPPET } } let(:a_types) { { 'atype.pp' => <<-PUPPET.unindent, type A::Atype = Integer PUPPET } } let(:a_tasks) { { 'atask' => '', } } let(:a_functions) { { 'afunc.pp' => 'function a::afunc() {}', } } let(:a_lib_puppet) { { 'functions' => { 'a' => { 'arubyfunc.rb' => "Puppet::Functions.create_function(:'a::arubyfunc') { def arubyfunc; end }", } } } } let(:b_plans) { { 'init.pp' => <<-PUPPET.unindent, plan b() {} PUPPET 'aplan.pp' => <<-PUPPET.unindent, plan b::aplan() {} PUPPET 'yamlplan.yaml' => '{}', 'conflict.yaml' => '{}', 'conflict.pp' => <<-PUPPET.unindent, plan b::conflict() {} PUPPET } } let(:b_types) { { 'atype.pp' => <<-PUPPET.unindent, type B::Atype = Integer PUPPET } } let(:b_tasks) { { 'init.json' => <<-JSON.unindent, { "description": "test task b", "parameters": {} } JSON 'init.sh' => "# doing exactly nothing\n", 'atask' => "# doing exactly nothing\n", 'atask.json' => <<-JSON.unindent, { "description": "test task b::atask", "input_method": "stdin", "parameters": { "string_param": { "description": "A string parameter", "type": "String[1]" }, "int_param": { "description": "An integer parameter", "type": "Integer" } } } JSON } } let(:b_functions) { { 'afunc.pp' => 'function b::afunc() {}', } } let(:b_lib_puppet) { { 'functions' => { 'b' => { 'arubyfunc.rb' => "Puppet::Functions.create_function(:'b::arubyfunc') { def arubyfunc; end }", } } } } let(:c_types) { { 'atype.pp' => <<-PUPPET.unindent, type C::Atype = Integer PUPPET } } let(:c_tasks) { { 'foo.sh' => <<-SH.unindent, # This is a task that does nothing SH 'fee.md' => <<-MD.unindent, This is not a task because it has .md extension MD 'fum.conf' => <<-CONF.unindent, text=This is not a task because it has .conf extension CONF 'bad_syntax.sh' => '', 'bad_syntax.json' => <<-TXT.unindent, text => This is not a task because JSON is unparsable TXT 'missing_adjacent.json' => <<-JSON.unindent, { "description": "This is not a task because there is no adjacent file with the same base name", "parameters": { "string_param": { "type": "String[1]" } } } JSON } } it 'private loader finds types in all modules' do expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:type, 'a::atype'), tn(:type, 'b::atype'), tn(:type, 'c::atype'))) end it 'module loader finds types only in itself' do expect(Loaders.find_loader('a').discover(:type) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:type, 'a::atype'))) end it 'private loader finds functions in all modules' do expect(loader.private_loader.discover(:function) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:function, 'a::afunc'), tn(:function, 'b::afunc'), tn(:function, 'a::arubyfunc'), tn(:function, 'b::arubyfunc'))) end it 'module loader finds functions only in itself' do expect(Loaders.find_loader('a').discover(:function) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:function, 'a::afunc'), tn(:function, 'a::arubyfunc'))) end it 'discover is only called once on dependent loader' do times_called = 0 allow_any_instance_of(ModuleLoaders::FileBased).to receive(:discover).with(:type, nil, Pcore::RUNTIME_NAME_AUTHORITY) { times_called += 1 }.and_return([]) expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(contain_exactly()) expect(times_called).to eq(4) end context 'with tasks enabled' do let(:tasks_feature) { true } it 'private loader finds plans in all modules' do expect(loader.private_loader.discover(:plan) { |t| t.name =~ /^.(?:::.*)?\z/ }).to( contain_exactly(tn(:plan, 'b'), tn(:plan, 'a::aplan'), tn(:plan, 'b::aplan'), tn(:plan, 'b::conflict'))) end it 'module loader finds plans only in itself' do expect(Loaders.find_loader('a').discover(:plan)).to( contain_exactly(tn(:plan, 'a::aplan'))) end context 'with a yaml plan instantiator defined' do before :each do Puppet.push_context(:yaml_plan_instantiator => double(:create => double('plan'))) end after :each do Puppet.pop_context end it 'module loader finds yaml plans' do expect(Loaders.find_loader('b').discover(:plan)).to( include(tn(:plan, 'b::yamlplan'))) end it 'module loader excludes plans with both .pp and .yaml versions' do expect(Loaders.find_loader('b').discover(:plan)).not_to( include(tn(:plan, 'b::conflict'))) end end it 'private loader finds types in all modules' do expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:type, 'a::atype'), tn(:type, 'b::atype'), tn(:type, 'c::atype'))) end it 'private loader finds tasks in all modules' do expect(loader.private_loader.discover(:task) { |t| t.name =~ /^.(?:::.*)?\z/ }).to( contain_exactly(tn(:task, 'a::atask'), tn(:task, 'b::atask'), tn(:task, 'b'), tn(:task, 'c::foo'))) end it 'module loader finds types only in itself' do expect(Loaders.find_loader('a').discover(:type) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:type, 'a::atype'))) end it 'module loader finds tasks only in itself' do expect(Loaders.find_loader('a').discover(:task) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:task, 'a::atask'))) end it 'module loader does not consider files with .md and .conf extension to be tasks' do expect(Loaders.find_loader('c').discover(:task) { |t| t.name =~ /(?:foo|fee|fum)\z/ }).to( contain_exactly(tn(:task, 'c::foo'))) end it 'without error_collector, invalid task metadata results in warnings' do logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(Loaders.find_loader('c').discover(:task)).to( contain_exactly(tn(:task, 'c::foo'))) end expect(logs.select { |log| log.level == :warning }.map { |log| log.message }).to( contain_exactly(/unexpected token/, /No source besides task metadata was found/) ) end it 'with error_collector, errors are collected and no warnings are logged' do logs = [] error_collector = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(Loaders.find_loader('c').discover(:task, error_collector)).to( contain_exactly(tn(:task, 'c::foo'))) end expect(logs.select { |log| log.level == :warning }.map { |log| log.message }).to be_empty expect(error_collector.size).to eql(2) expect(error_collector.all? { |e| e.is_a?(Puppet::DataTypes::Error) }) expect(error_collector.all? { |e| e.issue_code == Puppet::Pops::Issues::LOADER_FAILURE.issue_code }) expect(error_collector.map { |e| e.details['original_error'] }).to( contain_exactly(/unexpected token/, /No source besides task metadata was found/) ) end context 'and an environment without directory' do let(:environments_dir) { tmpdir('loader_spec') } let(:env) { Puppet::Node::Environment.create(:none_such, [modules_dir]) } it 'an EmptyLoader is used and module loader finds types' do expect_any_instance_of(Puppet::Pops::Loader::ModuleLoaders::EmptyLoader).to receive(:find).and_return(nil) expect(Loaders.find_loader('a').discover(:type) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:type, 'a::atype'))) end it 'an EmptyLoader is used and module loader finds tasks' do expect_any_instance_of(Puppet::Pops::Loader::ModuleLoaders::EmptyLoader).to receive(:find).and_return(nil) expect(Loaders.find_loader('a').discover(:task) { |t| t.name =~ /^.::.*\z/ }).to( contain_exactly(tn(:task, 'a::atask'))) end end end context 'with no explicit dependencies' do let(:modules) do { 'a' => { 'functions' => a_functions, 'lib' => { 'puppet' => a_lib_puppet }, 'plans' => a_plans, 'tasks' => a_tasks, 'types' => a_types, }, 'b' => { 'functions' => b_functions, 'lib' => { 'puppet' => b_lib_puppet }, 'plans' => b_plans, 'tasks' => b_tasks, 'types' => b_types, }, 'c' => { 'types' => c_types, }, } end it 'discover is only called once on dependent loader' do times_called = 0 allow_any_instance_of(ModuleLoaders::FileBased).to receive(:discover).with(:type, nil, Pcore::RUNTIME_NAME_AUTHORITY) { times_called += 1 }.and_return([]) expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(contain_exactly()) expect(times_called).to eq(4) end end end end end end def tn(type, name) TypedName.new(type, name) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/loaders/module_loaders_spec.rb
spec/unit/pops/loaders/module_loaders_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/pops' require 'puppet/loaders' require 'puppet_spec/compiler' describe 'FileBased module loader' do include PuppetSpec::Files let(:static_loader) { Puppet::Pops::Loader::StaticLoader.new() } let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) } it 'can load a 4x function API ruby function in global name space' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'foo4x.rb' => <<-CODE Puppet::Functions.create_function(:foo4x) do def foo4x() 'yay' end end CODE } } } }) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) function = module_loader.load_typed(typed_name(:function, 'foo4x')).value expect(function.class.name).to eq('foo4x') expect(function.is_a?(Puppet::Functions::Function)).to eq(true) end it 'can load a 4x function API ruby function in qualified name space' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo4x.rb' => <<-CODE Puppet::Functions.create_function('testmodule::foo4x') do def foo4x() 'yay' end end CODE } } } }}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) function = module_loader.load_typed(typed_name(:function, 'testmodule::foo4x')).value expect(function.class.name).to eq('testmodule::foo4x') expect(function.is_a?(Puppet::Functions::Function)).to eq(true) end it 'system loader has itself as private loader' do module_loader = loaders.puppet_system_loader expect(module_loader.private_loader).to be(module_loader) end it 'makes parent loader win over entries in child' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule' => { 'foo.rb' => <<-CODE Puppet::Functions.create_function('testmodule::foo') do def foo() 'yay' end end CODE }}}}}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) module_dir2 = dir_containing('testmodule2', { 'lib' => { 'puppet' => { 'functions' => { 'testmodule2' => { 'foo.rb' => <<-CODE raise "should not get here" CODE }}}}}) module_loader2 = Puppet::Pops::Loader::ModuleLoaders::FileBased.new(module_loader, loaders, 'testmodule2', module_dir2, 'test2') function = module_loader2.load_typed(typed_name(:function, 'testmodule::foo')).value expect(function.class.name).to eq('testmodule::foo') expect(function.is_a?(Puppet::Functions::Function)).to eq(true) end context 'loading tasks' do before(:each) do Puppet[:tasks] = true Puppet.push_context(:loaders => loaders) end after(:each) { Puppet.pop_context } it 'can load tasks with multiple files' do module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => '{}'}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) task = module_loader.load_typed(typed_name(:task, 'testmodule::foo')).value expect(task.name).to eq('testmodule::foo') expect(task.files.length).to eq(1) expect(task.files[0]['name']).to eq('foo.py') end it 'can load tasks with multiple implementations' do metadata = { 'implementations' => [{'name' => 'foo.py'}, {'name' => 'foo.ps1'}] } module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.ps1' => '', 'foo.json' => metadata.to_json}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) task = module_loader.load_typed(typed_name(:task, 'testmodule::foo')).value expect(task.name).to eq('testmodule::foo') expect(task.files.map {|impl| impl['name']}).to eq(['foo.py', 'foo.ps1']) end it 'can load multiple tasks with multiple files' do module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => '{}', 'foobar.py' => '', 'foobar.json' => '{}'}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) foo_task = module_loader.load_typed(typed_name(:task, 'testmodule::foo')).value foobar_task = module_loader.load_typed(typed_name(:task, 'testmodule::foobar')).value expect(foo_task.name).to eq('testmodule::foo') expect(foo_task.files.length).to eq(1) expect(foo_task.files[0]['name']).to eq('foo.py') expect(foobar_task.name).to eq('testmodule::foobar') expect(foobar_task.files.length).to eq(1) expect(foobar_task.files[0]['name']).to eq('foobar.py') end it "won't load tasks with invalid names" do module_dir = dir_containing('testmodule', 'tasks' => {'a-b.py' => '', 'foo.tar.gz' => ''}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) tasks = module_loader.discover(:task) expect(tasks).to be_empty expect(module_loader.load_typed(typed_name(:task, 'testmodule::foo'))).to be_nil end it "lists tasks without executables, if they specify implementations" do module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'bar.rb' => '', 'baz.json' => {'implementations' => ['name' => 'foo.py']}.to_json, 'qux.json' => '{}'}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) tasks = module_loader.discover(:task) expect(tasks.length).to eq(3) expect(tasks.map(&:name).sort).to eq(['testmodule::bar', 'testmodule::baz', 'testmodule::foo']) expect(module_loader.load_typed(typed_name(:task, 'testmodule::foo'))).not_to be_nil expect(module_loader.load_typed(typed_name(:task, 'testmodule::bar'))).not_to be_nil expect(module_loader.load_typed(typed_name(:task, 'testmodule::baz'))).not_to be_nil expect { module_loader.load_typed(typed_name(:task, 'testmodule::qux')) }.to raise_error(/No source besides task metadata was found/) end it 'raises and error when `parameters` is not a hash' do metadata = { 'parameters' => 'foo' } module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))} .to raise_error(Puppet::ParseError, /Failed to load metadata for task testmodule::foo: 'parameters' must be a hash/) end it 'raises and error when `implementations` `requirements` key is not an array' do metadata = { 'implementations' => { 'name' => 'foo.py', 'requirements' => 'foo'} } module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))} .to raise_error(Puppet::Module::Task::InvalidMetadata, /Task metadata for task testmodule::foo does not specify implementations as an array/) end it 'raises and error when top-level `files` is not an array' do metadata = { 'files' => 'foo' } module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))} .to raise_error(Puppet::Module::Task::InvalidMetadata, /The 'files' task metadata expects an array, got foo/) end it 'raises and error when `files` nested in `interpreters` is not an array' do metadata = { 'implementations' => [{'name' => 'foo.py', 'files' => 'foo'}] } module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir) expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))} .to raise_error(Puppet::Module::Task::InvalidMetadata, /The 'files' task metadata expects an array, got foo/) end end def typed_name(type, name) Puppet::Pops::Loader::TypedName.new(type, name) end context 'module function and class using a module type alias' do include PuppetSpec::Compiler let(:modules) do { 'mod' => { 'functions' => { 'afunc.pp' => <<-PUPPET.unindent function mod::afunc(Mod::Analias $v) { notice($v) } PUPPET }, 'types' => { 'analias.pp' => <<-PUPPET.unindent type Mod::Analias = Enum[a,b] PUPPET }, 'manifests' => { 'init.pp' => <<-PUPPET.unindent class mod(Mod::Analias $v) { notify { $v: } } PUPPET } } } end let(:testing_env) do { 'testing' => { 'modules' => modules } } end let(:environments_dir) { Puppet[:environmentpath] } let(:testing_env_dir) do dir_contained_in(environments_dir, testing_env) env_dir = File.join(environments_dir, 'testing') PuppetSpec::Files.record_tmp(env_dir) env_dir end let(:env) { Puppet::Node::Environment.create(:testing, [File.join(testing_env_dir, 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } # The call to mod:afunc will load the function, and as a consequence, make an attempt to load # the parameter type Mod::Analias. That load in turn, will trigger the Runtime3TypeLoader which # will load the manifests in Mod. The init.pp manifest also references the Mod::Analias parameter # which results in a recursive call to the same loader. This test asserts that this recursive # call is handled OK. # See PUP-7391 for more info. it 'should handle a recursive load' do expect(eval_and_collect_notices("mod::afunc('b')", node)).to eql(['b']) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/loaders/loaders_spec.rb
spec/unit/pops/loaders/loaders_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'puppet/pops' require 'puppet/loaders' describe 'loader helper classes' do it 'NamedEntry holds values and is frozen' do ne = Puppet::Pops::Loader::Loader::NamedEntry.new('name', 'value', 'origin') expect(ne.frozen?).to be_truthy expect(ne.typed_name).to eql('name') expect(ne.origin).to eq('origin') expect(ne.value).to eq('value') end it 'TypedName holds values and is frozen' do tn = Puppet::Pops::Loader::TypedName.new(:function, '::foo::bar') expect(tn.frozen?).to be_truthy expect(tn.type).to eq(:function) expect(tn.name_parts).to eq(['foo', 'bar']) expect(tn.name).to eq('foo::bar') expect(tn.qualified?).to be_truthy end it 'TypedName converts name to lower case' do tn = Puppet::Pops::Loader::TypedName.new(:type, '::Foo::Bar') expect(tn.name_parts).to eq(['foo', 'bar']) expect(tn.name).to eq('foo::bar') end it 'TypedName is case insensitive' do expect(Puppet::Pops::Loader::TypedName.new(:type, '::Foo::Bar')).to eq(Puppet::Pops::Loader::TypedName.new(:type, '::foo::bar')) end end describe 'loaders' do include PuppetSpec::Files include PuppetSpec::Compiler let(:module_without_metadata) { File.join(config_dir('wo_metadata_module'), 'modules') } let(:module_without_lib) { File.join(config_dir('module_no_lib'), 'modules') } let(:mix_4x_and_3x_functions) { config_dir('mix_4x_and_3x_functions') } let(:module_with_metadata) { File.join(config_dir('single_module'), 'modules') } let(:dependent_modules_with_metadata) { config_dir('dependent_modules_with_metadata') } let(:no_modules) { config_dir('no_modules') } let(:user_metadata_path) { File.join(dependent_modules_with_metadata, 'modules/user/metadata.json') } let(:usee_metadata_path) { File.join(dependent_modules_with_metadata, 'modules/usee/metadata.json') } let(:usee2_metadata_path) { File.join(dependent_modules_with_metadata, 'modules/usee2/metadata.json') } let(:empty_test_env) { environment_for() } # Loaders caches the puppet_system_loader, must reset between tests before :each do allow(File).to receive(:read).and_call_original end context 'when loading pp resource types using auto loading' do let(:pp_resources) { config_dir('pp_resources') } let(:environments) { Puppet::Environments::Directories.new(my_fixture_dir, []) } let(:env) { Puppet::Node::Environment.create(:'pp_resources', [File.join(pp_resources, 'modules')]) } let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) } let(:loader) { Puppet::Pops::Loaders.loaders.find_loader(nil) } before(:each) do Puppet.push_context({ :environments => environments }) Puppet.push_context({ :loaders => compiler.loaders }) end after(:each) do Puppet.pop_context() end it 'finds a resource type that resides under <environment root>/.resource_types' do rt = loader.load(:resource_type_pp, 'myresource') expect(rt).to be_a(Puppet::Pops::Resource::ResourceTypeImpl) end it 'does not allow additional logic in the file' do expect{loader.load(:resource_type_pp, 'addlogic')}.to raise_error(ArgumentError, /it has additional logic/) end it 'does not allow creation of classes other than Puppet::Resource::ResourceType3' do expect{loader.load(:resource_type_pp, 'badcall')}.to raise_error(ArgumentError, /no call to Puppet::Resource::ResourceType3.new found/) end it 'does not allow creation of other types' do expect{loader.load(:resource_type_pp, 'wrongname')}.to raise_error(ArgumentError, /produced resource type with the wrong name, expected 'wrongname', actual 'notwrongname'/) end it 'errors with message about empty file for files that contain no logic' do expect{loader.load(:resource_type_pp, 'empty')}.to raise_error(ArgumentError, /it is empty/) end it 'creates a pcore resource type loader' do pcore_loader = env.loaders.runtime3_type_loader.resource_3x_loader expect(pcore_loader.loader_name).to eq('pcore_resource_types') expect(pcore_loader).to be_a(Puppet::Pops::Loader::ModuleLoaders::FileBased) end it 'does not create a pcore resource type loader if requested not to' do env.loaders = nil # clear cached loaders loaders = Puppet::Pops::Loaders.new(env, false, false) expect(loaders.runtime3_type_loader.resource_3x_loader).to be_nil end it 'does not create a pcore resource type loader for an empty environment' do loaders = Puppet::Pops::Loaders.new(empty_test_env) expect(loaders.runtime3_type_loader.resource_3x_loader).to be_nil end end def expect_loader_hierarchy(loaders, expected_loaders) actual_loaders = [] loader = loaders.private_environment_loader while loader actual_loaders << [loader.loader_name, loader] loader = loader.parent end expect(actual_loaders).to contain_exactly(*expected_loaders) end it 'creates a puppet_system loader' do loaders = Puppet::Pops::Loaders.new(empty_test_env) expect(loaders.puppet_system_loader()).to be_a(Puppet::Pops::Loader::ModuleLoaders::FileBased) end it 'creates a cached_puppet loader when for_agent is set to true' do loaders = Puppet::Pops::Loaders.new(empty_test_env, true) expect(loaders.puppet_cache_loader()).to be_a(Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased) end it 'creates a cached_puppet loader that can load version 4 functions, version 3 functions, and data types, in that order' do loaders = Puppet::Pops::Loaders.new(empty_test_env, true) expect(loaders.puppet_cache_loader.loadables).to eq([:func_4x, :func_3x, :datatype]) end it 'does not create a cached_puppet loader when for_agent is the default false value' do loaders = Puppet::Pops::Loaders.new(empty_test_env) expect(loaders.puppet_cache_loader()).to be(nil) end it 'creates an environment loader' do loaders = Puppet::Pops::Loaders.new(empty_test_env) expect(loaders.public_environment_loader()).to be_a(Puppet::Pops::Loader::SimpleEnvironmentLoader) expect(loaders.public_environment_loader().to_s).to eql("(SimpleEnvironmentLoader 'environment')") expect(loaders.private_environment_loader()).to be_a(Puppet::Pops::Loader::DependencyLoader) expect(loaders.private_environment_loader().to_s).to eql("(DependencyLoader 'environment private' [])") end it 'creates a hierarchy of loaders' do expect_loader_hierarchy( Puppet::Pops::Loaders.new(empty_test_env), [ [nil, Puppet::Pops::Loader::StaticLoader], ['puppet_system', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased], [empty_test_env.name, Puppet::Pops::Loader::Runtime3TypeLoader], ['environment', Puppet::Pops::Loader::SimpleEnvironmentLoader], ['environment private', Puppet::Pops::Loader::DependencyLoader], ] ) end it 'excludes the Runtime3TypeLoader when tasks are enabled' do Puppet[:tasks] = true expect_loader_hierarchy( Puppet::Pops::Loaders.new(empty_test_env), [ [nil, Puppet::Pops::Loader::StaticLoader], ['puppet_system', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased], ['environment', Puppet::Pops::Loader::ModuleLoaders::EmptyLoader], ['environment private', Puppet::Pops::Loader::DependencyLoader], ] ) end it 'includes the agent cache loader when for_agent is true' do expect_loader_hierarchy( Puppet::Pops::Loaders.new(empty_test_env, true), [ [nil, Puppet::Pops::Loader::StaticLoader], ['puppet_system', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased], ['cached_puppet_lib', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased], [empty_test_env.name, Puppet::Pops::Loader::Runtime3TypeLoader], ['environment', Puppet::Pops::Loader::SimpleEnvironmentLoader], ['environment private', Puppet::Pops::Loader::DependencyLoader], ], ) end context 'when loading from a module' do it 'loads a ruby function using a qualified or unqualified name' do loaders = Puppet::Pops::Loaders.new(environment_for(module_with_metadata)) modulea_loader = loaders.public_loader_for_module('modulea') unqualified_function = modulea_loader.load_typed(typed_name(:function, 'rb_func_a')).value qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::rb_func_a')).value expect(unqualified_function).to be_a(Puppet::Functions::Function) expect(qualified_function).to be_a(Puppet::Functions::Function) expect(unqualified_function.class.name).to eq('rb_func_a') expect(qualified_function.class.name).to eq('modulea::rb_func_a') end it 'loads a puppet function using a qualified name in module' do loaders = Puppet::Pops::Loaders.new(environment_for(module_with_metadata)) modulea_loader = loaders.public_loader_for_module('modulea') qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::hello')).value expect(qualified_function).to be_a(Puppet::Functions::Function) expect(qualified_function.class.name).to eq('modulea::hello') end it 'loads a puppet function from a module without a lib directory' do loaders = Puppet::Pops::Loaders.new(environment_for(module_without_lib)) modulea_loader = loaders.public_loader_for_module('modulea') qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::hello')).value expect(qualified_function).to be_a(Puppet::Functions::Function) expect(qualified_function.class.name).to eq('modulea::hello') end it 'loads a puppet function in a sub namespace of module' do loaders = Puppet::Pops::Loaders.new(environment_for(module_with_metadata)) modulea_loader = loaders.public_loader_for_module('modulea') qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::subspace::hello')).value expect(qualified_function).to be_a(Puppet::Functions::Function) expect(qualified_function.class.name).to eq('modulea::subspace::hello') end it 'loader does not add namespace if not given' do loaders = Puppet::Pops::Loaders.new(environment_for(module_without_metadata)) moduleb_loader = loaders.public_loader_for_module('moduleb') expect(moduleb_loader.load_typed(typed_name(:function, 'rb_func_b'))).to be_nil end it 'loader allows loading a function more than once' do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return('') allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) env = environment_for(File.join(dependent_modules_with_metadata, 'modules')) loaders = Puppet::Pops::Loaders.new(env) moduleb_loader = loaders.private_loader_for_module('user') function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()") function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()") end end context 'when loading from a module with metadata' do let(:env) { environment_for(File.join(dependent_modules_with_metadata, 'modules')) } let(:scope) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)).newscope(nil) } let(:environmentpath) { my_fixture_dir } let(:node) { Puppet::Node.new('test', :facts => Puppet::Node::Facts.new('facts', {}), :environment => 'dependent_modules_with_metadata') } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:user_metadata) { { 'name' => 'test-user', 'author' => 'test', 'description' => '', 'license' => '', 'source' => '', 'version' => '1.0.0', 'dependencies' => [] } } def compile_and_get_notifications(code) Puppet[:code] = code catalog = block_given? ? compiler.compile { |c| yield(compiler.topscope); c } : compiler.compile catalog.resources.map(&:ref).select { |r| r.start_with?('Notify[') }.map { |r| r[7..-2] } end around(:each) do |example| # Initialize settings to get a full compile as close as possible to a real # environment load Puppet.settings.initialize_global_settings # Initialize loaders based on the environmentpath. It does not work to # just set the setting environmentpath for some reason - this achieves the same: # - first a loader is created, loading directory environments from the fixture (there is # one environment, 'sample', which will be loaded since the node references this # environment by name). # - secondly, the created env loader is set as 'environments' in the puppet context. # environments = Puppet::Environments::Directories.new(environmentpath, []) Puppet.override(:environments => environments) do example.run end end it 'all dependent modules are visible' do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'}, { 'name' => 'test-usee2'} ]).to_json) allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) loaders = Puppet::Pops::Loaders.new(env) moduleb_loader = loaders.private_loader_for_module('user') function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()") function = moduleb_loader.load_typed(typed_name(:function, 'user::caller2')).value expect(function.call({})).to eql("usee2::callee() was told 'passed value' + I am user::caller2()") end it 'all other modules are visible when tasks are enabled' do Puppet[:tasks] = true env = environment_for(File.join(dependent_modules_with_metadata, 'modules')) loaders = Puppet::Pops::Loaders.new(env) moduleb_loader = loaders.private_loader_for_module('user') function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()") end [ 'outside a function', 'a puppet function declared under functions', 'a puppet function declared in init.pp', 'a ruby function'].each_with_index do |from, from_idx| [ {:from => from, :called => 'a puppet function declared under functions', :expects => "I'm the function usee::usee_puppet()"}, {:from => from, :called => 'a puppet function declared in init.pp', :expects => "I'm the function usee::usee_puppet_init()"}, {:from => from, :called => 'a ruby function', :expects => "I'm the function usee::usee_ruby()"} ].each_with_index do |desc, called_idx| case_number = from_idx * 3 + called_idx + 1 it "can call #{desc[:called]} from #{desc[:from]} when dependency is present in metadata.json" do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json) allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) Puppet[:code] = "$case_number = #{case_number}\ninclude ::user" catalog = compiler.compile resource = catalog.resource('Notify', "case_#{case_number}") expect(resource).not_to be_nil expect(resource['message']).to eq(desc[:expects]) end it "can call #{desc[:called]} from #{desc[:from]} when no metadata is present" do times_has_metadata_called = 0 allow_any_instance_of(Puppet::Module).to receive('has_metadata?') { times_has_metadata_called += 1 }.and_return(false) Puppet[:code] = "$case_number = #{case_number}\ninclude ::user" catalog = compiler.compile resource = catalog.resource('Notify', "case_#{case_number}") expect(resource).not_to be_nil expect(resource['message']).to eq(desc[:expects]) expect(times_has_metadata_called).to be >= 1 end it "can not call #{desc[:called]} from #{desc[:from]} if dependency is missing in existing metadata.json" do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => []).to_json) allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) Puppet[:code] = "$case_number = #{case_number}\ninclude ::user" catalog = compiler.compile resource = catalog.resource('Notify', "case_#{case_number}") expect(resource).not_to be_nil expect(resource['message']).to eq(desc[:expects]) end end end it "a type can reference an autoloaded type alias from another module when dependency is present in metadata.json" do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json) allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok']) assert_type(Usee::Zero, 0) notice(ok) CODE end it "a type can reference an autoloaded type alias from another module when no metadata is present" do expect_any_instance_of(Puppet::Module).to receive('has_metadata?').at_least(:once).and_return(false) expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok']) assert_type(Usee::Zero, 0) notice(ok) CODE end it "a type can reference a type alias from another module when other module has it declared in init.pp" do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json) allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok']) include 'usee' assert_type(Usee::One, 1) notice(ok) CODE end it "an autoloaded type can reference an autoloaded type alias from another module when dependency is present in metadata.json" do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json) allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok']) assert_type(User::WithUseeZero, [0]) notice(ok) CODE end it "an autoloaded type can reference an autoloaded type alias from another module when other module has it declared in init.pp" do allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json) allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT) expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok']) include 'usee' assert_type(User::WithUseeOne, [1]) notice(ok) CODE end end context 'when loading from a module without metadata' do it 'loads a ruby function with a qualified name' do loaders = Puppet::Pops::Loaders.new(environment_for(module_without_metadata)) moduleb_loader = loaders.public_loader_for_module('moduleb') function = moduleb_loader.load_typed(typed_name(:function, 'moduleb::rb_func_b')).value expect(function).to be_a(Puppet::Functions::Function) expect(function.class.name).to eq('moduleb::rb_func_b') end it 'all other modules are visible' do env = environment_for(module_with_metadata, module_without_metadata) loaders = Puppet::Pops::Loaders.new(env) moduleb_loader = loaders.private_loader_for_module('moduleb') function = moduleb_loader.load_typed(typed_name(:function, 'moduleb::rb_func_b')).value expect(function.call({})).to eql("I am modulea::rb_func_a() + I am moduleb::rb_func_b()") end end context 'when loading from an environment without modules' do let(:node) { Puppet::Node.new('test', :facts => Puppet::Node::Facts.new('facts', {}), :environment => 'no_modules') } it 'can load the same function twice with two different compilations and produce different values' do Puppet.settings.initialize_global_settings environments = Puppet::Environments::Directories.new(my_fixture_dir, []) Puppet.override(:environments => environments) do compiler = Puppet::Parser::Compiler.new(node) compiler.topscope['value_from_scope'] = 'first' catalog = compiler.compile expect(catalog.resource('Notify[first]')).to be_a(Puppet::Resource) expect(Puppet::Pops::Loader::RubyFunctionInstantiator).not_to receive(:create) compiler = Puppet::Parser::Compiler.new(node) compiler.topscope['value_from_scope'] = 'second' catalog = compiler.compile expect(catalog.resource('Notify[first]')).to be_nil expect(catalog.resource('Notify[second]')).to be_a(Puppet::Resource) end end end context 'when calling' do let(:env) { environment_for(mix_4x_and_3x_functions) } let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) } let(:scope) { compiler.topscope } let(:loader) { compiler.loaders.private_loader_for_module('user') } before(:each) do Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders) end it 'a 3x function in dependent module can be called from a 4x function' do function = loader.load_typed(typed_name(:function, 'user::caller')).value expect(function.call(scope)).to eql("usee::callee() got 'first' - usee::callee() got 'second'") end it 'a 3x function in dependent module can be called from a puppet function' do function = loader.load_typed(typed_name(:function, 'user::puppetcaller')).value expect(function.call(scope)).to eql("usee::callee() got 'first' - usee::callee() got 'second'") end it 'a 4x function can be called from a puppet function' do function = loader.load_typed(typed_name(:function, 'user::puppetcaller4')).value expect(function.call(scope)).to eql("usee::callee() got 'first' - usee::callee() got 'second'") end it 'a puppet function can be called from a 4x function' do function = loader.load_typed(typed_name(:function, 'user::callingpuppet')).value expect(function.call(scope)).to eql("Did you call to say you love me?") end it 'a 3x function can be called with caller scope propagated from a 4x function' do function = loader.load_typed(typed_name(:function, 'user::caller_ws')).value expect(function.call(scope, 'passed in scope')).to eql("usee::callee_ws() got 'passed in scope'") end it 'calls can be made to a non core function via the call() function' do call_function = loader.load_typed(typed_name(:function, 'call')).value expect(call_function.call(scope, 'user::puppetcaller4')).to eql("usee::callee() got 'first' - usee::callee() got 'second'") end end context 'when a 3x load takes place' do let(:env) { environment_for(mix_4x_and_3x_functions) } let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) } let(:scope) { compiler.topscope } let(:loader) { compiler.loaders.private_loader_for_module('user') } before(:each) do Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders) end after(:each) do Puppet.pop_context end it "a function with no illegal constructs can be loaded" do function = loader.load_typed(typed_name(:function, 'good_func_load')).value expect(function.call(scope)).to eql(Float("3.14")) end it "a function with syntax error has helpful error message" do expect { loader.load_typed(typed_name(:function, 'func_with_syntax_error')) }.to raise_error(/unexpected.*end'/) end end context 'when a 3x load has illegal method added' do let(:env) { environment_for(mix_4x_and_3x_functions) } let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) } let(:scope) { compiler.topscope } let(:loader) { compiler.loaders.private_loader_for_module('user') } before(:each) do Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders) end after(:each) do Puppet.pop_context end it "outside function body is reported as an error" do expect { loader.load_typed(typed_name(:function, 'bad_func_load')) }.to raise_error(/Illegal method definition/) end it "to self outside function body is reported as an error" do expect { loader.load_typed(typed_name(:function, 'bad_func_load5')) }.to raise_error(/Illegal method definition.*'bad_func_load5_illegal_method'/) end it "outside body is reported as an error even if returning the right func_info" do expect { loader.load_typed(typed_name(:function, 'bad_func_load2'))}.to raise_error(/Illegal method definition/) end it "inside function body is reported as an error" do expect { f = loader.load_typed(typed_name(:function, 'bad_func_load3')).value f.call(scope) }.to raise_error(/Illegal method definition.*'bad_func_load3_illegal_method'/) end it "to self inside function body is reported as an error" do expect { f = loader.load_typed(typed_name(:function, 'bad_func_load4')).value f.call(scope) }.to raise_error(/Illegal method definition.*'bad_func_load4_illegal_method'/) end end context 'when causing a 3x load followed by a 4x load' do let(:env) { environment_for(mix_4x_and_3x_functions) } let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) } let(:scope) { compiler.topscope } let(:loader) { compiler.loaders.private_loader_for_module('user') } before(:each) do Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders) end after(:each) do Puppet.pop_context end it 'a 3x function is loaded once' do # create a 3x function that when called will do a load of "callee_ws" Puppet::Parser::Functions::newfunction(:callee, :type => :rvalue, :arity => 1) do |args| function_callee_ws(['passed in scope']) end expect(Puppet).not_to receive(:warning) scope['passed_in_scope'] = 'value' function = loader.load_typed(typed_name(:function, 'callee')).value expect(function.call(scope, 'passed in scope')).to eql("usee::callee_ws() got 'value'") function = loader.load_typed(typed_name(:function, 'callee_ws')).value expect(function.call(scope, 'passed in scope')).to eql("usee::callee_ws() got 'value'") end it "an illegal function is loaded" do expect { loader.load_typed(typed_name(:function, 'bad_func_load3')).value }.to raise_error(SecurityError, /Illegal method definition of method 'bad_func_load3_illegal_method' in source .*bad_func_load3.rb on line 8 in legacy function/) end end context 'loading' do let(:env_name) { 'testenv' } let(:environments_dir) { Puppet[:environmentpath] } let(:env_dir) { File.join(environments_dir, env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')]) } let(:node) { Puppet::Node.new("test", :environment => env) } let(:env_dir_files) {} let(:populated_env_dir) do dir_contained_in(environments_dir, env_name => env_dir_files) PuppetSpec::Files.record_tmp(env_dir) env_dir end context 'non autoloaded types and functions' do let(:env_dir_files) { { 'modules' => { 'tstf' => { 'manifests' => { 'init.pp' => <<-PUPPET.unindent class tstf { notice(testfunc()) } PUPPET } }, 'tstt' => { 'manifests' => { 'init.pp' => <<-PUPPET.unindent class tstt { notice(assert_type(GlobalType, 23)) } PUPPET } } } } } it 'finds the function from a module' do expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eq(['hello from testfunc']) function testfunc() { 'hello from testfunc' } include 'tstf' PUPPET end it 'finds the type from a module' do expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eq(['23']) type GlobalType = Integer include 'tstt' PUPPET end end context 'types' do let(:env_name) { 'testenv' } let(:environments_dir) { Puppet[:environmentpath] } let(:env_dir) { File.join(environments_dir, env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')]) } let(:metadata_json) { <<-JSON { "name": "example/%1$s", "version": "0.0.2", "source": "git@github.com/example/example-%1$s.git", "dependencies": [], "author": "Bob the Builder", "license": "Apache-2.0"%2$s } JSON } let(:env_dir_files) do { 'types' => { 'c.pp' => 'type C = Integer' }, 'modules' => { 'a' => { 'manifests' => { 'init.pp' => 'class a { notice(A::A) }' }, 'types' => { 'a.pp' => 'type A::A = Variant[B::B, String]', 'n.pp' => 'type A::N = C::C' }, 'metadata.json' => sprintf(metadata_json, 'a', ', "dependencies": [{ "name": "example/b" }]') }, 'b' => { 'types' => { 'b.pp' => 'type B::B = Variant[C::C, Float]', 'x.pp' => 'type B::X = A::A' }, 'metadata.json' => sprintf(metadata_json, 'b', ', "dependencies": [{ "name": "example/c" }]') }, 'c' => { 'types' => { 'init_typeset.pp' => <<-PUPPET.unindent, type C = TypeSet[{ pcore_version => '1.0.0', types => { C => Integer, D => Float } }] PUPPET
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/loaders/loader_paths_spec.rb
spec/unit/pops/loaders/loader_paths_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/pops' require 'puppet/loaders' describe 'loader paths' do include PuppetSpec::Files let(:static_loader) { Puppet::Pops::Loader::StaticLoader.new() } let(:unused_loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:'*test*', [])) } it 'module loader has smart-paths that prunes unavailable paths' do module_dir = dir_containing('testmodule', {'lib' => {'puppet' => {'functions' => {'foo.rb' => 'Puppet::Functions.create_function("testmodule::foo") { def foo; end; }' } }}}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, unused_loaders, 'testmodule', module_dir) effective_paths = module_loader.smart_paths.effective_paths(:function) expect(effective_paths.size).to be_eql(1) expect(effective_paths[0].generic_path).to be_eql(File.join(module_dir, 'lib', 'puppet', 'functions')) end it 'all function smart-paths produces entries if they exist' do module_dir = dir_containing('testmodule', { 'lib' => { 'puppet' => { 'functions' => {'foo4x.rb' => 'ignored in this test'}, }}}) module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, unused_loaders, 'testmodule', module_dir) effective_paths = module_loader.smart_paths.effective_paths(:function) expect(effective_paths.size).to eq(1) expect(module_loader.path_index.size).to eq(1) path_index = module_loader.path_index expect(path_index).to include(File.join(module_dir, 'lib', 'puppet', 'functions', 'foo4x.rb')) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/loaders/environment_loader_spec.rb
spec/unit/pops/loaders/environment_loader_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/pops' require 'puppet/loaders' describe 'Environment loader' do include PuppetSpec::Files let(:env_name) { 'spec' } let(:code_dir) { Puppet[:environmentpath] } let(:env_dir) { File.join(code_dir, env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_code_dir, env_name, 'modules')]) } let(:populated_code_dir) do dir_contained_in(code_dir, env_name => env_content) PuppetSpec::Files.record_tmp(env_dir) code_dir end let(:env_content) { { 'lib' => { 'puppet' => { 'functions' => { 'ruby_foo.rb' => <<-RUBY.unindent, Puppet::Functions.create_function(:ruby_foo) do def ruby_foo() 'ruby_foo' end end RUBY 'environment' => { 'ruby_foo.rb' => <<-RUBY.unindent Puppet::Functions.create_function(:'environment::ruby_foo') do def ruby_foo() 'environment::ruby_foo' end end RUBY }, 'someother' => { 'ruby_foo.rb' => <<-RUBY.unindent Puppet::Functions.create_function(:'someother::ruby_foo') do def ruby_foo() 'someother::ruby_foo' end end RUBY }, } } }, 'functions' => { 'puppet_foo.pp' => <<-PUPPET.unindent, function puppet_foo() { 'puppet_foo' } PUPPET 'environment' => { 'puppet_foo.pp' => <<-PUPPET.unindent, function environment::puppet_foo() { 'environment::puppet_foo' } PUPPET }, 'someother' => { 'puppet_foo.pp' => <<-PUPPET.unindent, function somether::puppet_foo() { 'someother::puppet_foo' } PUPPET } }, 'types' => { 'footype.pp' => <<-PUPPET.unindent, type FooType = Enum['foo', 'bar', 'baz'] PUPPET 'environment' => { 'footype.pp' => <<-PUPPET.unindent, type Environment::FooType = Integer[0,9] PUPPET }, 'someother' => { 'footype.pp' => <<-PUPPET.unindent, type SomeOther::FooType = Float[0.0,9.0] PUPPET } } } } before(:each) do Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env)) end after(:each) do Puppet.pop_context end def load_or_nil(type, name) found = Puppet::Pops::Loaders.find_loader(nil).load_typed(Puppet::Pops::Loader::TypedName.new(type, name)) found.nil? ? nil : found.value end context 'loading a Ruby function' do it 'loads from global name space' do function = load_or_nil(:function, 'ruby_foo') expect(function).not_to be_nil expect(function.class.name).to eq('ruby_foo') expect(function).to be_a(Puppet::Functions::Function) end it 'loads from environment name space' do function = load_or_nil(:function, 'environment::ruby_foo') expect(function).not_to be_nil expect(function.class.name).to eq('environment::ruby_foo') expect(function).to be_a(Puppet::Functions::Function) end it 'fails to load from namespaces other than global or environment' do function = load_or_nil(:function, 'someother::ruby_foo') expect(function).to be_nil end end context 'loading a Puppet function' do it 'loads from global name space' do function = load_or_nil(:function, 'puppet_foo') expect(function).not_to be_nil expect(function.class.name).to eq('puppet_foo') expect(function).to be_a(Puppet::Functions::PuppetFunction) end it 'loads from environment name space' do function = load_or_nil(:function, 'environment::puppet_foo') expect(function).not_to be_nil expect(function.class.name).to eq('environment::puppet_foo') expect(function).to be_a(Puppet::Functions::PuppetFunction) end it 'fails to load from namespaces other than global or environment' do function = load_or_nil(:function, 'someother::puppet_foo') expect(function).to be_nil end end context 'loading a Puppet type' do it 'loads from global name space' do type = load_or_nil(:type, 'footype') expect(type).not_to be_nil expect(type).to be_a(Puppet::Pops::Types::PTypeAliasType) expect(type.name).to eq('FooType') end it 'loads from environment name space' do type = load_or_nil(:type, 'environment::footype') expect(type).not_to be_nil expect(type).to be_a(Puppet::Pops::Types::PTypeAliasType) expect(type.name).to eq('Environment::FooType') end it 'fails to load from namespaces other than global or environment' do type = load_or_nil(:type, 'someother::footype') expect(type).to be_nil end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/locator_spec.rb
spec/unit/pops/parser/locator_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::Parser::Locator do it "multi byte characters in a comment does not interfere with AST node text extraction" do parser = Puppet::Pops::Parser::Parser.new() model = parser.parse_string("# \u{0400}comment\nabcdef#XXXXXXXXXX").model expect(model.class).to eq(Puppet::Pops::Model::Program) expect(model.body.offset).to eq(12) expect(model.body.length).to eq(6) expect(model.body.locator.extract_text(model.body.offset, model.body.length)).to eq('abcdef') end it "multi byte characters in a comment does not interfere with AST node text extraction" do parser = Puppet::Pops::Parser::Parser.new() model = parser.parse_string("# \u{0400}comment\n1 + 2#XXXXXXXXXX").model expect(model.class).to eq(Puppet::Pops::Model::Program) expect(model.body.offset).to eq(14) # The '+' expect(model.body.length).to eq(1) expect(model.body.locator.extract_tree_text(model.body)).to eq('1 + 2') end it 'Locator caches last offset / line' do parser = Puppet::Pops::Parser::Parser.new() model = parser.parse_string("$a\n = 1\n + 1\n").model expect(model.body.locator).to receive(:ary_bsearch_i).with(anything, 2).once.and_return(:special_value) expect(model.body.locator.line_for_offset(2)).to eq(:special_value) expect(model.body.locator.line_for_offset(2)).to eq(:special_value) end it 'Locator invalidates last offset / line cache if asked for different offset' do parser = Puppet::Pops::Parser::Parser.new() model = parser.parse_string("$a\n = 1\n + 1\n").model expect(model.body.locator).to receive(:ary_bsearch_i).with(anything, 2).twice.and_return(:first_value, :third_value) expect(model.body.locator).to receive(:ary_bsearch_i).with(anything, 3).once.and_return(:second_value) expect(model.body.locator.line_for_offset(2)).to eq(:first_value) expect(model.body.locator.line_for_offset(3)).to eq(:second_value) # invalidates cache as side effect expect(model.body.locator.line_for_offset(2)).to eq(:third_value) end it 'A heredoc without margin and interpolated expression location has offset and length relative the source' do parser = Puppet::Pops::Parser::Parser.new() src = <<-CODE # line one # line two @("END"/L) Line four\\ Line five ${1 + 1} END CODE model = parser.parse_string(src).model interpolated_expr = model.body.text_expr.segments[1].expr expect(interpolated_expr.left_expr.offset).to eq(84) expect(interpolated_expr.left_expr.length).to eq(1) expect(interpolated_expr.right_expr.offset).to eq(96) expect(interpolated_expr.right_expr.length).to eq(1) expect(interpolated_expr.offset).to eq(86) # the + sign expect(interpolated_expr.length).to eq(1) # the + sign expect(interpolated_expr.locator.extract_tree_text(interpolated_expr)).to eq("1 +\n 1") end it 'A heredoc with margin and interpolated expression location has offset and length relative the source' do parser = Puppet::Pops::Parser::Parser.new() src = <<-CODE # line one # line two @("END"/L) Line four\\ Line five ${1 + 1} |- END CODE model = parser.parse_string(src).model interpolated_expr = model.body.text_expr.segments[1].expr expect(interpolated_expr.left_expr.offset).to eq(84) expect(interpolated_expr.left_expr.length).to eq(1) expect(interpolated_expr.right_expr.offset).to eq(96) expect(interpolated_expr.right_expr.length).to eq(1) expect(interpolated_expr.offset).to eq(86) # the + sign expect(interpolated_expr.length).to eq(1) # the + sign expect(interpolated_expr.locator.extract_tree_text(interpolated_expr)).to eq("1 +\n 1") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/parse_heredoc_spec.rb
spec/unit/pops/parser/parse_heredoc_spec.rb
require 'spec_helper' require 'puppet/pops' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/parser_rspec_helper') describe "egrammar parsing heredoc" do include ParserRspecHelper it "parses plain heredoc" do expect(dump(parse("@(END)\nThis is\nheredoc text\nEND\n"))).to eq([ "(@()", " 'This is\nheredoc text\n'", ")" ].join("\n")) end it "parses heredoc with margin" do src = [ "@(END)", " This is", " heredoc text", " | END", "" ].join("\n") expect(dump(parse(src))).to eq([ "(@()", " 'This is\nheredoc text\n'", ")" ].join("\n")) end it "parses heredoc with margin and right newline trim" do src = [ "@(END)", " This is", " heredoc text", " |- END", "" ].join("\n") expect(dump(parse(src))).to eq([ "(@()", " 'This is\nheredoc text'", ")" ].join("\n")) end it "parses syntax and escape specification" do src = <<-CODE @(END:syntax/t) Tex\\tt\\n |- END CODE expect(dump(parse(src))).to eq([ "(@(syntax)", " 'Tex\tt\\n'", ")" ].join("\n")) end it "parses interpolated heredoc expression" do src = <<-CODE @("END") Hello $name |- END CODE expect(dump(parse(src))).to eq([ "(@()", " (cat 'Hello ' (str $name))", ")" ].join("\n")) end it "parses interpolated heredoc expression containing escapes" do src = <<-CODE @("END") Hello \\$name |- END CODE expect(dump(parse(src))).to eq([ "(@()", " (cat 'Hello \\' (str $name))", ")" ].join("\n")) end it "parses interpolated heredoc expression containing escapes when escaping other things than $" do src = <<-CODE @("END"/t) Hello \\$name |- END CODE expect(dump(parse(src))).to eq([ "(@()", " (cat 'Hello \\' (str $name))", ")" ].join("\n")) end it "parses with escaped newlines without preceding whitespace" do src = <<-CODE @(END/L) First Line\\ Second Line |- END CODE parse(src) expect(dump(parse(src))).to eq([ "(@()", " 'First Line Second Line'", ")" ].join("\n")) end it "parses with escaped newlines with proper margin" do src = <<-CODE @(END/L) First Line\\ Second Line |- END CODE parse(src) expect(dump(parse(src))).to eq([ "(@()", " ' First Line Second Line'", ")" ].join("\n")) end it "parses interpolated heredoc expression with false start on $" do src = <<-CODE @("END") Hello $name$%a |- END CODE expect(dump(parse(src))).to eq([ "(@()", " (cat 'Hello ' (str $name) '$%a')", ")" ].join("\n")) end it "parses interpolated [] expression by looking at the correct preceding char for space when there is no heredoc margin" do # NOTE: Important not to use the left margin feature here src = <<-CODE $xxxxxxx = @("END") ${facts['os']['family']} XXXXXXX XXX END CODE expect(dump(parse(src))).to eq([ "(= $xxxxxxx (@()", " (cat (str (slice (slice $facts 'os') 'family')) '", "XXXXXXX XXX", "')", "))"].join("\n")) end it "parses interpolated [] expression by looking at the correct preceding char for space when there is a heredoc margin" do # NOTE: Important not to use the left margin feature here - the problem in PUP 9303 is triggered by lines and text before # an interpolation containing []. src = <<-CODE # comment # comment $xxxxxxx = @("END") 1 2 3 4 5 YYYYY${facts['fqdn']} XXXXXXX XXX | END CODE expect(dump(parse(src))).to eq([ "(= $xxxxxxx (@()", " (cat '1", "2", "3", "4", "5", "YYYYY' (str (slice $facts 'fqdn')) '", "XXXXXXX XXX", "')", "))"].join("\n")) end it "correctly reports an error location in a nested heredoc with margin" do # NOTE: Important not to use the left margin feature here - the problem in PUP 9303 is triggered by lines and text before # an interpolation containing []. src = <<-CODE # comment # comment $xxxxxxx = @("END") 1 2 3 4 5 YYYYY${facts]} XXXXXXX XXX | END CODE expect{parse(src)}.to raise_error(/Syntax error at '\]' \(line: 9, column: 15\)/) end it "correctly reports an error location in a heredoc with line endings escaped" do # DO NOT CHANGE INDENTATION OF THIS HEREDOC src = <<-CODE # line one # line two @("END"/L) First Line\\ Second Line ${facts]} |- END CODE expect{parse(src)}.to raise_error(/Syntax error at '\]' \(line: 5, column: 24\)/) end it "correctly reports an error location in a heredoc with line endings escaped when there is text in the margin" do # DO NOT CHANGE INDENTATION OR SPACING OF THIS HEREDOC src = <<-CODE # line one # line two @("END"/L) First Line\\ Second Line x Third Line ${facts]} |- END # line 8 # line 9 CODE expect{parse(src)}.to raise_error(/Syntax error at '\]' \(line: 6, column: 23\)/) end it "correctly reports an error location in a heredoc with line endings escaped when there is text in the margin" do # DO NOT CHANGE INDENTATION OR SPACING OF THIS HEREDOC src = <<-CODE @(END) AAA BBB CCC DDD EEE FFF |- END CODE expect(dump(parse(src))).to eq([ "(@()", " 'AAA", # no left space trimmed " BBB", " CCC", " DDD", "EEE", # left space trimmed " FFF'", # indented one because it is one in from margin marker ")"].join("\n")) end it 'parses multiple heredocs on the same line' do src = <<-CODE notice({ @(foo) => @(bar) }) hello -foo world -bar notice '!' CODE expect(dump(parse(src))).to eq([ '(block', ' (invoke notice ({} ((@()', ' \' hello\'', ' ) (@()', ' \' world\'', ' ))))', ' (invoke notice \'!\')', ')' ].join("\n")) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/epp_parser_spec.rb
spec/unit/pops/parser/epp_parser_spec.rb
require 'spec_helper' require 'puppet/pops' require File.join(File.dirname(__FILE__), '/../factory_rspec_helper') module EppParserRspecHelper include FactoryRspecHelper def parse(code) parser = Puppet::Pops::Parser::EppParser.new() parser.parse_string(code) end end describe "epp parser" do include EppParserRspecHelper it "should instantiate an epp parser" do parser = Puppet::Pops::Parser::EppParser.new() expect(parser.class).to eq(Puppet::Pops::Parser::EppParser) end it "should parse a code string and return a program with epp" do parser = Puppet::Pops::Parser::EppParser.new() model = parser.parse_string("Nothing to see here, move along...").model expect(model.class).to eq(Puppet::Pops::Model::Program) expect(model.body.class).to eq(Puppet::Pops::Model::LambdaExpression) expect(model.body.body.class).to eq(Puppet::Pops::Model::EppExpression) end context "when facing bad input it reports" do it "unbalanced tags" do expect { dump(parse("<% missing end tag")) }.to raise_error(/Unbalanced/) end it "abrupt end" do expect { dump(parse("dum di dum di dum <%")) }.to raise_error(/Unbalanced/) end it "nested epp tags" do expect { dump(parse("<% $a = 10 <% $b = 20 %>%>")) }.to raise_error(/Syntax error/) end it "nested epp expression tags" do expect { dump(parse("<%= 1+1 <%= 2+2 %>%>")) }.to raise_error(/Syntax error/) end it "rendering sequence of expressions" do expect { dump(parse("<%= 1 2 3 %>")) }.to raise_error(/Syntax error/) end end context "handles parsing of" do it "text (and nothing else)" do expect(dump(parse("Hello World"))).to eq([ "(lambda (epp (block", " (render-s 'Hello World')", ")))"].join("\n")) end it "template parameters" do expect(dump(parse("<%|$x|%>Hello World"))).to eq([ "(lambda (parameters x) (epp (block", " (render-s 'Hello World')", ")))"].join("\n")) end it "template parameters with default" do expect(dump(parse("<%|$x='cigar'|%>Hello World"))).to eq([ "(lambda (parameters (= x 'cigar')) (epp (block", " (render-s 'Hello World')", ")))"].join("\n")) end it "template parameters with and without default" do expect(dump(parse("<%|$x='cigar', $y|%>Hello World"))).to eq([ "(lambda (parameters (= x 'cigar') y) (epp (block", " (render-s 'Hello World')", ")))"].join("\n")) end it "template parameters + additional setup" do expect(dump(parse("<%|$x| $y = 10 %>Hello World"))).to eq([ "(lambda (parameters x) (epp (block", " (= $y 10)", " (render-s 'Hello World')", ")))"].join("\n")) end it "comments" do expect(dump(parse("<%#($x='cigar', $y)%>Hello World"))).to eq([ "(lambda (epp (block", " (render-s 'Hello World')", ")))" ].join("\n")) end it "verbatim epp tags" do expect(dump(parse("<%% contemplating %%>Hello World"))).to eq([ "(lambda (epp (block", " (render-s '<% contemplating %>Hello World')", ")))" ].join("\n")) end it "expressions" do expect(dump(parse("We all live in <%= 3.14 - 2.14 %> world"))).to eq([ "(lambda (epp (block", " (render-s 'We all live in ')", " (render (- 3.14 2.14))", " (render-s ' world')", ")))" ].join("\n")) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/parser_rspec_helper.rb
spec/unit/pops/parser/parser_rspec_helper.rb
require 'puppet/pops' require File.join(File.dirname(__FILE__), '/../factory_rspec_helper') module ParserRspecHelper include FactoryRspecHelper def parse(code) parser = Puppet::Pops::Parser::Parser.new() parser.parse_string(code) end def parse_epp(code) parser = Puppet::Pops::Parser::EppParser.new() parser.parse_string(code) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/lexer2_spec.rb
spec/unit/pops/parser/lexer2_spec.rb
require 'spec_helper' require 'matchers/match_tokens2' require 'puppet/pops' require 'puppet/pops/parser/lexer2' module EgrammarLexer2Spec def tokens_scanned_from(s) lexer = Puppet::Pops::Parser::Lexer2.new lexer.string = s lexer.fullscan[0..-2] end def epp_tokens_scanned_from(s) lexer = Puppet::Pops::Parser::Lexer2.new lexer.string = s lexer.fullscan_epp[0..-2] end end describe 'Lexer2' do include EgrammarLexer2Spec { :LISTSTART => '[', :RBRACK => ']', :LBRACE => '{', :RBRACE => '}', :WSLPAREN => '(', # since it is first on a line it is special (LPAREN handled separately) :RPAREN => ')', :EQUALS => '=', :ISEQUAL => '==', :GREATEREQUAL => '>=', :GREATERTHAN => '>', :LESSTHAN => '<', :LESSEQUAL => '<=', :NOTEQUAL => '!=', :NOT => '!', :COMMA => ',', :DOT => '.', :COLON => ':', :AT => '@', :LLCOLLECT => '<<|', :RRCOLLECT => '|>>', :LCOLLECT => '<|', :RCOLLECT => '|>', :SEMIC => ';', :QMARK => '?', :OTHER => '\\', :FARROW => '=>', :PARROW => '+>', :APPENDS => '+=', :DELETES => '-=', :PLUS => '+', :MINUS => '-', :DIV => '/', :TIMES => '*', :LSHIFT => '<<', :RSHIFT => '>>', :MATCH => '=~', :NOMATCH => '!~', :IN_EDGE => '->', :OUT_EDGE => '<-', :IN_EDGE_SUB => '~>', :OUT_EDGE_SUB => '<~', :PIPE => '|', }.each do |name, string| it "should lex a token named #{name.to_s}" do expect(tokens_scanned_from(string)).to match_tokens2(name) end end it "should lex [ in position after non whitespace as LBRACK" do expect(tokens_scanned_from("a[")).to match_tokens2(:NAME, :LBRACK) end { "case" => :CASE, "class" => :CLASS, "default" => :DEFAULT, "define" => :DEFINE, # "import" => :IMPORT, # done as a function in egrammar "if" => :IF, "elsif" => :ELSIF, "else" => :ELSE, "inherits" => :INHERITS, "node" => :NODE, "and" => :AND, "or" => :OR, "undef" => :UNDEF, "false" => :BOOLEAN, "true" => :BOOLEAN, "in" => :IN, "unless" => :UNLESS, "private" => :PRIVATE, "type" => :TYPE, "attr" => :ATTR, }.each do |string, name| it "should lex a keyword from '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2(name) end end context 'when --no-tasks (the default)' do it "should lex a NAME from 'plan'" do expect(tokens_scanned_from('plan')).to match_tokens2(:NAME) end end context 'when --tasks' do before(:each) { Puppet[:tasks] = true } after(:each) { Puppet[:tasks] = false } it "should lex a keyword from 'plan'" do expect(tokens_scanned_from('plan')).to match_tokens2(:PLAN) end end # TODO: Complete with all edge cases [ 'A', 'A::B', '::A', '::A::B',].each do |string| it "should lex a CLASSREF on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:CLASSREF, string]) end end # TODO: Complete with all edge cases [ 'a', 'a::b', '::a', '::a::b',].each do |string| it "should lex a NAME on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:NAME, string]) end end [ 'a-b', 'a--b', 'a-b-c', '_x'].each do |string| it "should lex a BARE WORD STRING on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:WORD, string]) end end [ '_x::y', 'x::_y'].each do |string| it "should consider the bare word '#{string}' to be a WORD" do expect(tokens_scanned_from(string)).to match_tokens2(:WORD) end end { '-a' => [:MINUS, :NAME], '--a' => [:MINUS, :MINUS, :NAME], 'a-' => [:NAME, :MINUS], 'a- b' => [:NAME, :MINUS, :NAME], 'a--' => [:NAME, :MINUS, :MINUS], 'a-$3' => [:NAME, :MINUS, :VARIABLE], }.each do |source, expected| it "should lex leading and trailing hyphens from #{source}" do expect(tokens_scanned_from(source)).to match_tokens2(*expected) end end { 'false'=>false, 'true'=>true}.each do |string, value| it "should lex a BOOLEAN on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:BOOLEAN, value]) end end [ '0', '1', '2982383139'].each do |string| it "should lex a decimal integer NUMBER on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string]) end end { ' 1' => '1', '1 ' => '1', ' 1 ' => '1'}.each do |string, value| it "should lex a NUMBER with surrounding space '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, value]) end end [ '0.0', '0.1', '0.2982383139', '29823.235', '10e23', '10e-23', '1.234e23'].each do |string| it "should lex a decimal floating point NUMBER on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string]) end end [ '00', '01', '0123', '0777'].each do |string| it "should lex an octal integer NUMBER on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string]) end end [ '0x0', '0x1', '0xa', '0xA', '0xabcdef', '0xABCDEF'].each do |string| it "should lex an hex integer NUMBER on the form '#{string}'" do expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string]) end end { "''" => '', "'a'" => 'a', "'a\\'b'" =>"a'b", "'a\\rb'" =>"a\\rb", "'a\\nb'" =>"a\\nb", "'a\\tb'" =>"a\\tb", "'a\\sb'" =>"a\\sb", "'a\\$b'" =>"a\\$b", "'a\\\"b'" =>"a\\\"b", "'a\\\\b'" =>"a\\b", "'a\\\\'" =>"a\\", }.each do |source, expected| it "should lex a single quoted STRING on the form #{source}" do expect(tokens_scanned_from(source)).to match_tokens2([:STRING, expected]) end end { "''" => [2, ""], "'a'" => [3, "a"], "'a\\'b'" => [6, "a'b"], }.each do |source, expected| it "should lex a single quoted STRING on the form #{source} as having length #{expected[0]}" do length, value = expected expect(tokens_scanned_from(source)).to match_tokens2([:STRING, value, {:line => 1, :pos=>1, :length=> length}]) end end { '""' => '', '"a"' => 'a', '"a\'b"' => "a'b", }.each do |source, expected| it "should lex a double quoted STRING on the form #{source}" do expect(tokens_scanned_from(source)).to match_tokens2([:STRING, expected]) end end { '"a$x b"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>2 }], [:VARIABLE, 'x', {:line => 1, :pos=>3, :length=>2 }], [:DQPOST, ' b', {:line => 1, :pos=>5, :length=>3 }]], '"a$x.b"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>2 }], [:VARIABLE, 'x', {:line => 1, :pos=>3, :length=>2 }], [:DQPOST, '.b', {:line => 1, :pos=>5, :length=>3 }]], '"$x.b"' => [[:DQPRE, '', {:line => 1, :pos=>1, :length=>1 }], [:VARIABLE, 'x', {:line => 1, :pos=>2, :length=>2 }], [:DQPOST, '.b', {:line => 1, :pos=>4, :length=>3 }]], '"a$x"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>2 }], [:VARIABLE, 'x', {:line => 1, :pos=>3, :length=>2 }], [:DQPOST, '', {:line => 1, :pos=>5, :length=>1 }]], '"a${x}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }], [:VARIABLE, 'x', {:line => 1, :pos=>5, :length=>1 }], [:DQPOST, '', {:line => 1, :pos=>7, :length=>1 }]], '"a${_x}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }], [:VARIABLE, '_x', {:line => 1, :pos=>5, :length=>2 }], [:DQPOST, '', {:line => 1, :pos=>8, :length=>1 }]], '"a${y::_x}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }], [:VARIABLE, 'y::_x', {:line => 1, :pos=>5, :length=>5 }], [:DQPOST, '', {:line => 1, :pos=>11, :length=>1 }]], '"a${_x[1]}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }], [:VARIABLE, '_x', {:line => 1, :pos=>5, :length=>2 }], [:LBRACK, '[', {:line => 1, :pos=>7, :length=>1 }], [:NUMBER, '1', {:line => 1, :pos=>8, :length=>1 }], [:RBRACK, ']', {:line => 1, :pos=>9, :length=>1 }], [:DQPOST, '', {:line => 1, :pos=>11, :length=>1 }]], '"a${_x.foo}"'=> [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }], [:VARIABLE, '_x', {:line => 1, :pos=>5, :length=>2 }], [:DOT, '.', {:line => 1, :pos=>7, :length=>1 }], [:NAME, 'foo', {:line => 1, :pos=>8, :length=>3 }], [:DQPOST, '', {:line => 1, :pos=>12, :length=>1 }]], }.each do |source, expected| it "should lex an interpolated variable 'x' from #{source}" do expect(tokens_scanned_from(source)).to match_tokens2(*expected) end end { '"$"' => '$', '"a$"' => 'a$', '"a$%b"' => "a$%b", '"a$$"' => "a$$", '"a$$%"' => "a$$%", }.each do |source, expected| it "should lex interpolation including false starts #{source}" do expect(tokens_scanned_from(source)).to match_tokens2([:STRING, expected]) end end it "differentiates between foo[x] and foo [x] (whitespace)" do expect(tokens_scanned_from("$a[1]")).to match_tokens2(:VARIABLE, :LBRACK, :NUMBER, :RBRACK) expect(tokens_scanned_from("$a [1]")).to match_tokens2(:VARIABLE, :LISTSTART, :NUMBER, :RBRACK) expect(tokens_scanned_from("a[1]")).to match_tokens2(:NAME, :LBRACK, :NUMBER, :RBRACK) expect(tokens_scanned_from("a [1]")).to match_tokens2(:NAME, :LISTSTART, :NUMBER, :RBRACK) end it "differentiates between '(' first on line, and not first on line" do expect(tokens_scanned_from("(")).to match_tokens2(:WSLPAREN) expect(tokens_scanned_from("\n(")).to match_tokens2(:WSLPAREN) expect(tokens_scanned_from("\n\r(")).to match_tokens2(:WSLPAREN) expect(tokens_scanned_from("\n\t(")).to match_tokens2(:WSLPAREN) expect(tokens_scanned_from("\n\r\t(")).to match_tokens2(:WSLPAREN) expect(tokens_scanned_from("\n\u00a0(")).to match_tokens2(:WSLPAREN) expect(tokens_scanned_from("x(")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("\nx(")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("\n\rx(")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("\n\tx(")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("\n\r\tx(")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("\n\u00a0x(")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("x (")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("x\t(")).to match_tokens2(:NAME, :LPAREN) expect(tokens_scanned_from("x\u00a0(")).to match_tokens2(:NAME, :LPAREN) end it "skips whitepsace" do expect(tokens_scanned_from(" if if if ")).to match_tokens2(:IF, :IF, :IF) expect(tokens_scanned_from(" if \n\r\t\nif if ")).to match_tokens2(:IF, :IF, :IF) expect(tokens_scanned_from(" if \n\r\t\n\u00a0if\u00a0 if ")).to match_tokens2(:IF, :IF, :IF) end it "skips single line comments" do expect(tokens_scanned_from("if # comment\nif")).to match_tokens2(:IF, :IF) end ["if /* comment */\nif", "if /* comment\n */\nif", "if /*\n comment\n */\nif", ].each do |source| it "skips multi line comments" do expect(tokens_scanned_from(source)).to match_tokens2(:IF, :IF) end end it 'detects unterminated multiline comment' do expect { tokens_scanned_from("/* not terminated\nmultiline\ncomment") }.to raise_error(Puppet::ParseErrorWithIssue) { |e| expect(e.issue_code).to be(Puppet::Pops::Issues::UNCLOSED_MLCOMMENT.issue_code) } end { "=~" => [:MATCH, "=~ /./"], "!~" => [:NOMATCH, "!~ /./"], "," => [:COMMA, ", /./"], "(" => [:WSLPAREN, "( /./"], "x (" => [[:NAME, :LPAREN], "x ( /./"], "x\\t (" => [[:NAME, :LPAREN], "x\t ( /./"], "[ (liststart)" => [:LISTSTART, "[ /./"], "[ (LBRACK)" => [[:NAME, :LBRACK], "a[ /./"], "[ (liststart after name)" => [[:NAME, :LISTSTART], "a [ /./"], "{" => [:LBRACE, "{ /./"], "+" => [:PLUS, "+ /./"], "-" => [:MINUS, "- /./"], "*" => [:TIMES, "* /./"], ";" => [:SEMIC, "; /./"], }.each do |token, entry| it "should lex regexp after '#{token}'" do expected = [entry[0], :REGEX].flatten expect(tokens_scanned_from(entry[1])).to match_tokens2(*expected) end end it "should lex a simple expression" do expect(tokens_scanned_from('1 + 1')).to match_tokens2([:NUMBER, '1'], :PLUS, [:NUMBER, '1']) end { "1" => ["1 /./", [:NUMBER, :DIV, :DOT, :DIV]], "'a'" => ["'a' /./", [:STRING, :DIV, :DOT, :DIV]], "true" => ["true /./", [:BOOLEAN, :DIV, :DOT, :DIV]], "false" => ["false /./", [:BOOLEAN, :DIV, :DOT, :DIV]], "/./" => ["/./ /./", [:REGEX, :DIV, :DOT, :DIV]], "a" => ["a /./", [:NAME, :DIV, :DOT, :DIV]], "A" => ["A /./", [:CLASSREF, :DIV, :DOT, :DIV]], ")" => [") /./", [:RPAREN, :DIV, :DOT, :DIV]], "]" => ["] /./", [:RBRACK, :DIV, :DOT, :DIV]], "|>" => ["|> /./", [:RCOLLECT, :DIV, :DOT, :DIV]], "|>>" => ["|>> /./", [:RRCOLLECT, :DIV, :DOT, :DIV]], "$x" => ["$x /1/", [:VARIABLE, :DIV, :NUMBER, :DIV]], "a-b" => ["a-b /1/", [:WORD, :DIV, :NUMBER, :DIV]], '"a$a"' => ['"a$a" /./', [:DQPRE, :VARIABLE, :DQPOST, :DIV, :DOT, :DIV]], }.each do |token, entry| it "should not lex regexp after '#{token}'" do expect(tokens_scanned_from(entry[ 0 ])).to match_tokens2(*entry[ 1 ]) end end it 'should lex assignment' do expect(tokens_scanned_from("$a = 10")).to match_tokens2([:VARIABLE, "a"], :EQUALS, [:NUMBER, '10']) end # TODO: Tricky, and heredoc not supported yet # it "should not lex regexp after heredoc" do # tokens_scanned_from("1 / /./").should match_tokens2(:NUMBER, :DIV, :REGEX) # end it "should lex regexp at beginning of input" do expect(tokens_scanned_from(" /./")).to match_tokens2(:REGEX) end it "should lex regexp right of div" do expect(tokens_scanned_from("1 / /./")).to match_tokens2(:NUMBER, :DIV, :REGEX) end it 'should lex regexp with escaped slash' do scanned = tokens_scanned_from('/\//') expect(scanned).to match_tokens2(:REGEX) expect(scanned[0][1][:value]).to eql(Regexp.new('/')) end it 'should lex regexp with escaped backslash' do scanned = tokens_scanned_from('/\\\\/') expect(scanned).to match_tokens2(:REGEX) expect(scanned[0][1][:value]).to eql(Regexp.new('\\\\')) end it 'should lex regexp with escaped backslash followed escaped slash ' do scanned = tokens_scanned_from('/\\\\\\//') expect(scanned).to match_tokens2(:REGEX) expect(scanned[0][1][:value]).to eql(Regexp.new('\\\\/')) end it 'should lex regexp with escaped slash followed escaped backslash ' do scanned = tokens_scanned_from('/\\/\\\\/') expect(scanned).to match_tokens2(:REGEX) expect(scanned[0][1][:value]).to eql(Regexp.new('/\\\\')) end it 'should not lex regexp with escaped ending slash' do expect(tokens_scanned_from('/\\/')).to match_tokens2(:DIV, :OTHER, :DIV) end it "should accept newline in a regular expression" do scanned = tokens_scanned_from("/\n.\n/") # Note that strange formatting here is important expect(scanned[0][1][:value]).to eql(/ . /) end context 'when lexer lexes heredoc' do it 'lexes tag, syntax and escapes, margin and right trim' do code = <<-CODE @(END:syntax/t) Tex\\tt\\n |- END CODE expect(tokens_scanned_from(code)).to match_tokens2([:HEREDOC, 'syntax'], :SUBLOCATE, [:STRING, "Tex\tt\\n"]) end it 'lexes "tag", syntax and escapes, margin, right trim and interpolation' do code = <<-CODE @("END":syntax/t) Tex\\tt\\n$var After |- END CODE expect(tokens_scanned_from(code)).to match_tokens2( [:HEREDOC, 'syntax'], :SUBLOCATE, [:DQPRE, "Tex\tt\\n"], [:VARIABLE, "var"], [:DQPOST, " After"] ) end it 'strips only last newline when using trim option' do code = <<-CODE.unindent @(END) Line 1 Line 2 -END CODE expect(tokens_scanned_from(code)).to match_tokens2( [:HEREDOC, ''], [:SUBLOCATE, ["Line 1\n", "\n", "Line 2\n"]], [:STRING, "Line 1\n\nLine 2"], ) end it 'strips only one newline at the end when using trim option' do code = <<-CODE.unindent @(END) Line 1 Line 2 -END CODE expect(tokens_scanned_from(code)).to match_tokens2( [:HEREDOC, ''], [:SUBLOCATE, ["Line 1\n", "Line 2\n", "\n"]], [:STRING, "Line 1\nLine 2\n"], ) end context 'with bad syntax' do def expect_issue(code, issue) expect { tokens_scanned_from(code) }.to raise_error(Puppet::ParseErrorWithIssue) { |e| expect(e.issue_code).to be(issue.issue_code) } end it 'detects and reports HEREDOC_UNCLOSED_PARENTHESIS' do code = <<-CODE @(END:syntax/t Text |- END CODE expect_issue(code, Puppet::Pops::Issues::HEREDOC_UNCLOSED_PARENTHESIS) end it 'detects and reports HEREDOC_WITHOUT_END_TAGGED_LINE' do code = <<-CODE @(END:syntax/t) Text CODE expect_issue(code, Puppet::Pops::Issues::HEREDOC_WITHOUT_END_TAGGED_LINE) end it 'detects and reports HEREDOC_INVALID_ESCAPE' do code = <<-CODE @(END:syntax/x) Text |- END CODE expect_issue(code, Puppet::Pops::Issues::HEREDOC_INVALID_ESCAPE) end it 'detects and reports HEREDOC_INVALID_SYNTAX' do code = <<-CODE @(END:syntax/t/p) Text |- END CODE expect_issue(code, Puppet::Pops::Issues::HEREDOC_INVALID_SYNTAX) end it 'detects and reports HEREDOC_WITHOUT_TEXT' do code = '@(END:syntax/t)' expect_issue(code, Puppet::Pops::Issues::HEREDOC_WITHOUT_TEXT) end it 'detects and reports HEREDOC_EMPTY_ENDTAG' do code = <<-CODE @("") Text |-END CODE expect_issue(code, Puppet::Pops::Issues::HEREDOC_EMPTY_ENDTAG) end it 'detects and reports HEREDOC_MULTIPLE_AT_ESCAPES' do code = <<-CODE @(END:syntax/tst) Tex\\tt\\n |- END CODE expect_issue(code, Puppet::Pops::Issues::HEREDOC_MULTIPLE_AT_ESCAPES) end end end context 'when not given multi byte characters' do it 'produces byte offsets for tokens' do code = <<-"CODE" 1 2\n3 CODE expect(tokens_scanned_from(code)).to match_tokens2( [:NUMBER, '1', {:line => 1, :offset => 0, :length=>1}], [:NUMBER, '2', {:line => 1, :offset => 2, :length=>1}], [:NUMBER, '3', {:line => 2, :offset => 4, :length=>1}] ) end end context 'when dealing with multi byte characters' do it 'should support unicode characters' do code = <<-CODE "x\\u2713y" CODE expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\u2713y"]) end it 'should support adjacent short form unicode characters' do code = <<-CODE "x\\u2713\\u2713y" CODE expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\u2713\u2713y"]) end it 'should support unicode characters in long form' do code = <<-CODE "x\\u{1f452}y" CODE expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\u{1f452}y"]) end it 'can escape the unicode escape' do code = <<-"CODE" "x\\\\u{1f452}y" CODE expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\\u{1f452}y"]) end it 'produces byte offsets that counts each byte in a comment' do code = <<-"CODE" # \u{0400}\na CODE expect(tokens_scanned_from(code.strip)).to match_tokens2([:NAME, 'a', {:line => 2, :offset => 5, :length=>1}]) end it 'produces byte offsets that counts each byte in value token' do code = <<-"CODE" '\u{0400}'\na CODE expect(tokens_scanned_from(code.strip)).to match_tokens2( [:STRING, "\u{400}", {:line => 1, :offset => 0, :length=>4}], [:NAME, 'a', {:line => 2, :offset => 5, :length=>1}] ) end it 'should not select LISTSTART token when preceded by multibyte chars' do # This test is sensitive to the number of multibyte characters and position of the expressions # within the string - it is designed to fail if the position is calculated on the byte offset of the '[' # instead of the char offset. # code = "$a = '\u00f6\u00fc\u00fc\u00fc\u00fc\u00e4\u00e4\u00f6\u00e4'\nnotify {'x': message => B['dkda'] }\n" expect(tokens_scanned_from(code)).to match_tokens2( :VARIABLE, :EQUALS, :STRING, [:NAME, 'notify'], :LBRACE, [:STRING, 'x'], :COLON, :NAME, :FARROW, :CLASSREF, :LBRACK, :STRING, :RBRACK, :RBRACE) end end context 'when lexing epp' do it 'epp can contain just text' do code = <<-CODE This is just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2(:EPP_START, [:RENDER_STRING, " This is just text\n"]) end it 'epp can contain text with interpolated rendered expressions' do code = <<-CODE This is <%= $x %> just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, " This is "], [:RENDER_EXPR, nil], [:VARIABLE, "x"], [:EPP_END, "%>"], [:RENDER_STRING, " just text\n"] ) end it 'epp can contain text with trimmed interpolated rendered expressions' do code = <<-CODE This is <%= $x -%> just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, " This is "], [:RENDER_EXPR, nil], [:VARIABLE, "x"], [:EPP_END_TRIM, "-%>"], [:RENDER_STRING, "just text\n"] ) end it 'epp can contain text with expressions that are not rendered' do code = <<-CODE This is <% $x=10 %> just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, " This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, " just text\n"] ) end it 'epp can skip trailing space and newline in tail text' do # note that trailing whitespace is significant on one of the lines code = <<-CODE.unindent This is <% $x=10 -%> just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, "This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, "just text\n"] ) end it 'epp can skip comments' do code = <<-CODE.unindent This is <% $x=10 -%> <%# This is an epp comment -%> just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, "This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, "just text\n"] ) end it 'epp comments does not strip left whitespace when preceding is right trim' do code = <<-CODE.unindent This is <% $x=10 -%> <%# This is an epp comment %> just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, "This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, " \njust text\n"] ) end it 'epp comments does not strip left whitespace when preceding is not right trim' do code = <<-CODE.unindent This is <% $x=10 %> <%# This is an epp comment -%> just text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, "This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, "\n just text\n"] ) end it 'epp comments can trim left with <%#-' do # test has 4 space before comment and 3 after it # check that there is 3 spaces before the 'and' # code = <<-CODE.unindent This is <% $x=10 -%> no-space-after-me: <%#- This is an epp comment %> and some text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, "This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, "no-space-after-me: and\nsome text\n"] ) end it 'puppet comment in left trimming epp tag works when containing a new line' do # test has 4 space before comment and 3 after it # check that there is 3 spaces before the 'and' # code = <<-CODE.unindent This is <% $x=10 -%> no-space-after-me: <%-# This is an puppet comment %> and some text CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, "This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, "no-space-after-me:"], [:RENDER_STRING, " and\nsome text\n"] ) end it 'epp can escape epp tags' do code = <<-CODE This is <% $x=10 -%> <%% this is escaped epp %%> CODE expect(epp_tokens_scanned_from(code)).to match_tokens2( :EPP_START, [:RENDER_STRING, " This is "], [:VARIABLE, "x"], :EQUALS, [:NUMBER, "10"], [:RENDER_STRING, " <% this is escaped epp %>\n"] ) end context 'with bad epp syntax' do def expect_issue(code, issue) expect { epp_tokens_scanned_from(code) }.to raise_error(Puppet::ParseErrorWithIssue) { |e| expect(e.issue_code).to be(issue.issue_code) } end it 'detects and reports EPP_UNBALANCED_TAG' do expect_issue('<% asf', Puppet::Pops::Issues::EPP_UNBALANCED_TAG) end it 'detects and reports EPP_UNBALANCED_COMMENT' do expect_issue('<%# asf', Puppet::Pops::Issues::EPP_UNBALANCED_COMMENT) end it 'detects and reports EPP_UNBALANCED_EXPRESSION' do expect_issue('asf <%', Puppet::Pops::Issues::EPP_UNBALANCED_EXPRESSION) end end end context 'when parsing bad code' do def expect_issue(code, issue) expect { tokens_scanned_from(code) }.to raise_error(Puppet::ParseErrorWithIssue) do |e| expect(e.issue_code).to be(issue.issue_code) end end it 'detects and reports issue ILLEGAL_CLASS_REFERENCE' do expect_issue('A::3', Puppet::Pops::Issues::ILLEGAL_CLASS_REFERENCE) end it 'detects and reports issue ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE' do expect_issue('::A::3', Puppet::Pops::Issues::ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE) end it 'detects and reports issue ILLEGAL_FULLY_QUALIFIED_NAME' do expect_issue('::a::3', Puppet::Pops::Issues::ILLEGAL_FULLY_QUALIFIED_NAME) end it 'detects and reports issue ILLEGAL_NUMBER' do expect_issue('3g', Puppet::Pops::Issues::ILLEGAL_NUMBER) end it 'detects and reports issue INVALID_HEX_NUMBER' do expect_issue('0x3g', Puppet::Pops::Issues::INVALID_HEX_NUMBER) end it 'detects and reports issue INVALID_OCTAL_NUMBER' do expect_issue('038', Puppet::Pops::Issues::INVALID_OCTAL_NUMBER) end it 'detects and reports issue INVALID_DECIMAL_NUMBER' do expect_issue('4.3g', Puppet::Pops::Issues::INVALID_DECIMAL_NUMBER) end it 'detects and reports issue NO_INPUT_TO_LEXER' do expect { Puppet::Pops::Parser::Lexer2.new.fullscan }.to raise_error(Puppet::ParseErrorWithIssue) { |e| expect(e.issue_code).to be(Puppet::Pops::Issues::NO_INPUT_TO_LEXER.issue_code) } end it 'detects and reports issue UNCLOSED_QUOTE' do expect_issue('"asd', Puppet::Pops::Issues::UNCLOSED_QUOTE) end end context 'when dealing with non UTF-8 and Byte Order Marks (BOMs)' do { 'UTF_8' => [0xEF, 0xBB, 0xBF], 'UTF_16_1' => [0xFE, 0xFF], 'UTF_16_2' => [0xFF, 0xFE], 'UTF_32_1' => [0x00, 0x00, 0xFE, 0xFF], 'UTF_32_2' => [0xFF, 0xFE, 0x00, 0x00], 'UTF_1' => [0xF7, 0x64, 0x4C], 'UTF_EBCDIC' => [0xDD, 0x73, 0x66, 0x73], 'SCSU' => [0x0E, 0xFE, 0xFF], 'BOCU' => [0xFB, 0xEE, 0x28], 'GB_18030' => [0x84, 0x31, 0x95, 0x33] }.each do |key, bytes| it "errors on the byte order mark for #{key} '[#{bytes.map() {|b| '%X' % b}.join(' ')}]'" do format_name = key.split('_')[0,2].join('-') bytes_str = "\\[#{bytes.map {|b| '%X' % b}.join(' ')}\\]" fix = " - remove these from the puppet source" expect { tokens_scanned_from(bytes.pack('C*')) }.to raise_error(Puppet::ParseErrorWithIssue, /Illegal #{format_name} .* at beginning of input: #{bytes_str}#{fix}/) end it "can use a possibly 'broken' UTF-16 string without problems for #{key}" do format_name = key.split('_')[0,2].join('-') string = bytes.pack('C*').force_encoding('UTF-16') bytes_str = "\\[#{string.bytes.map {|b| '%X' % b}.join(' ')}\\]" fix = " - remove these from the puppet source" expect { tokens_scanned_from(string) }.to raise_error(Puppet::ParseErrorWithIssue, /Illegal #{format_name} .* at beginning of input: #{bytes_str}#{fix}/) end end end end describe Puppet::Pops::Parser::Lexer2 do include PuppetSpec::Files # First line of Rune version of Rune poem at http://www.columbia.edu/~fdc/utf8/ # characters chosen since they will not parse on Windows with codepage 437 or 1252 # Section 3.2.1.3 of Ruby spec guarantees that \u strings are encoded as UTF-8 # Runes (may show up as garbage if font is not available): ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ let (:rune_utf8) { "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2" + "\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA" + "\u16B3\u16A2\u16D7" } context 'when lexing files from disk' do it 'should always read files as UTF-8' do manifest_code = "notify { '#{rune_utf8}': }" manifest = file_containing('manifest.pp', manifest_code) lexed_file = described_class.new.lex_file(manifest) expect(lexed_file.string.encoding).to eq(Encoding::UTF_8) expect(lexed_file.string).to eq(manifest_code) end it 'currently errors when the UTF-8 BOM (Byte Order Mark) is present when lexing files' do bom = "\uFEFF" manifest_code = "#{bom}notify { '#{rune_utf8}': }" manifest = file_containing('manifest.pp', manifest_code) expect { described_class.new.lex_file(manifest) }.to raise_error(Puppet::ParseErrorWithIssue, 'Illegal UTF-8 Byte Order mark at beginning of input: [EF BB BF] - remove these from the puppet source') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/parse_plan_spec.rb
spec/unit/pops/parser/parse_plan_spec.rb
require 'spec_helper' require 'puppet/pops' require_relative 'parser_rspec_helper' describe "egrammar parsing of 'plan'" do include ParserRspecHelper context 'with --tasks' do before(:each) do Puppet[:tasks] = true end it "an empty body" do expect(dump(parse("plan foo { }"))).to eq("(plan foo ())") end it "a non empty body" do prog = <<-EPROG plan foo { $a = 10 $b = 20 } EPROG expect(dump(parse(prog))).to eq( [ "(plan foo (block", " (= $a 10)", " (= $b 20)", "))", ].join("\n")) end it "accepts parameters" do s = "plan foo($p1 = 'yo', $p2) { }" expect(dump(parse(s))).to eq("(plan foo (parameters (= p1 'yo') p2) ())") end end context 'with --no-tasks' do before(:each) do Puppet[:tasks] = false end it "the keyword 'plan' is a name" do expect(dump(parse("$a = plan"))).to eq("(= $a plan)") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false